code
stringlengths 2
1.05M
| repo_name
stringlengths 5
114
| path
stringlengths 4
991
| language
stringclasses 1
value | license
stringclasses 15
values | size
int32 2
1.05M
|
---|---|---|---|---|---|
'use strict';
var angular = angular;
var module = angular.module('Authentication', []);
module.controller('RegistrationController', function ($scope, $rootScope, $state, AUTH_EVENTS, AuthService, URLS) {
$scope.credentials = {
firstName : '',
lastName : '',
username : '',
email : '',
password : '',
confirmpassword : '',
gender : '',
age : '',
gymtimings : '',
mailingAddress : '',
phonenumber : ''
};
$scope.registrationError = false;
$scope.registrationSuccess = false;
$scope.register = function (credentials) {
$scope.authFailureMessage = "";
$scope.authSuccessMessage = "";
$scope.registrationError = false;
$scope.registrationSuccess = false;
if($scope.registerForm.$valid) {
credentials.username = credentials.username.toLowerCase().replace(/\s+/g,'');
credentials.email = credentials.email.toLowerCase().replace(/\s+/g,'');
AuthService.register(credentials)
.then(function (user) {
$rootScope.registrationSuccess = true;
$state.go('login');
$scope.registrationError = false;
$scope.CallMailService(credentials.username, credentials.email,credentials.password);
})
.catch(function (res) {
$scope.authFailureMessage = res.data.error.message;
$scope.registrationError = true;
$rootScope.registrationSuccess = false;
})
.finally(function () {
$scope.credentials.password = "";
$scope.credentials.confirmpassword = "";
});
}
};
});
module.controller('LoginController', function ($scope, $rootScope, $state, AUTH_EVENTS, USER_ROLES, AuthService, $timeout, facebook, SessionService, AdminDataService) {
$scope.credentials = {
username: "",
password: ""
};
$scope.loginError = false;
$scope.loginSuccess=false;
$scope.authSuccessMessage = "";
if($rootScope.registrationSuccess){
$scope.authSuccessMessage = AUTH_EVENTS.registraionSuccess;
$scope.loginSuccess = true;
$rootScope.registrationSuccess= false;
}
$scope.$on('$viewContentLoaded', function(event) {
$timeout(function() {
$("#username")[0].value ="";
$("#password")[0].value="";
},100);
});
$scope.login = function (credentials) {
$scope.authFailureMessage = "";
$scope.authSuccessMessage = "";
$scope.loginError = false;
$scope.loginSuccess=false;
if($scope.loginForm.$valid) {
credentials.username = credentials.username.toLowerCase().replace(/\s+/g,'');
$scope.loginError = false
$scope.callLoginService(credentials);
}
};
$scope.callLoginService = function(credentials){
AuthService.login(credentials)
.then(function (data) {
$scope.loginError = false;
$rootScope.$broadcast(AUTH_EVENTS.loginSuccess);
$rootScope.loggedIn = true;
$scope.getUserPrivileges(data.user);
})
.catch(function (res) {
$scope.authFailureMessage = AUTH_EVENTS.loginFailed;
$scope.loginError = true;
})
.then(function () {
$scope.credentials.password = "";
$scope.credentials.username = "";
});
}
$scope.getUserPrivileges = function(user){
AdminDataService.getUserPrivileges(user.id)
.success(function (data) {
//$scope.fitnesCompanyAdmin = (data.fitnessCompaniesAdministrated.length > 0) ? true : false;
//$scope.fitnesCenterAdmin = (data.fitnessCentersAdministrated.length > 0) ? true : false;
//$scope.admin = (data.roles.length > 0) ? true : false;
if(data.roles.length > 0){
user.userRoles = USER_ROLES.admin;
$scope.setCurrentUser(user);
//$state.go("admin");
}else{
user.userRoles = USER_ROLES.guest;
$scope.setCurrentUser(user);
//$state.go("workout-statistics");
}
})
.catch(function (res) {
var message = AUTH_MESSAGES[res.data.error.message] || res.data.error.message;
$scope.authFailureMessage = message;
$scope.authError = true;
});
}
$scope.getPublicProfile = function(){
facebook.getUser().then(function(r){
var response = r.user;
console.log(r.user);
var userDetails = {
firstName : response.first_name,
lastName : response.last_name,
username : response.name.toLowerCase().replace(/\s+/g,''),
email : response.email.toLowerCase().replace(/\s+/g,''),
password : response.first_name+"@1234",
gender : response.gender,
age : (response.age_range) ? response.age_range : 21,
gymtimings : '',
mailingAddress : '',
phonenumber : ''
};
// $scope.ValidateUserRegistration(userDetails);
console.log(userDetails)
});
}
$scope.img = "";
$scope.getProfilePicture = function(){
facebook.getUserPicture("me",{width:300, height:300}).then(function(r){
$scope.img = r.picture.url;
});
}
$scope.ValidateUserRegistration = function(userProfile){
$scope.facebookUserProfileRegistration(userProfile);
/*AuthService.emailValidate(userDetails.email)
.then(function (data) {
if(data){
$scope.setCurrentUser(data.user);
SessionService.create(user);
$rootScope.$broadcast(AUTH_EVENTS.loginSuccess);
$rootScope.loggedIn = true;
$state.go("workout-statistics");
}else{
$scope.facebookUserProfileRegistration(userProfile);
}
})
.catch(function (res) {
$scope.authFailureMessage = AUTH_EVENTS.loginFailed;
$scope.loginError = true;
});*/
}
$scope.facebookUserProfileRegistration = function(userProfile){
AuthService.register(userProfile)
.then(function (user) {
var credentials={
username : userProfile.username,
password : userProfile.password
}
$scope.callLoginService(credentials);
})
.catch(function (res) {
$scope.authFailureMessage = res.data.error.message;
$scope.registrationError = true;
});
};
});
module.controller('ForgotPasswordController', function ($scope, $rootScope, AUTH_EVENTS, AuthService) {
$scope.credentials = {
email: ''
};
$scope.authError = false;
$scope.authSuccess=false;
$scope.fotgotpassword = function (credentials) {
$scope.authFailureMessage = "";
$scope.$broadcast('runCustomValidations', {
forms: ['loginForm']
});
if($scope.loginForm.$valid) {
AuthService.resetpassword(credentials)
.then(function (user) {
})
.catch(function (res) {
$scope.authFailureMessage = res.data.error.message;
})
.then(function () {
$scope.credentials.email = "";
});
}
};
});
module.controller('LogoutController', function ($scope, $rootScope, AUTH_EVENTS, AuthService) {
$scope.authError = false;
$scope.authSuccess=false;
$scope.logout = function () {
$scope.logoutStatus = "Logging out...";
AuthService.logout()
.then(function () {
$scope.authError = false;
$scope.authSuccess=true;
$scope.logoutStatus = "You have been logged out. Goodbye!";
})
.catch(function () {
$scope.authError = true;
$scope.authSuccess=false;
$scope.logoutStatus = "There was some kind of error logging you out! You may still be logged in...";
})
.finally(function () {
$rootScope.$broadcast(AUTH_EVENTS.logoutSuccess);
$scope.setCurrentUser(null);
$rootScope.loggedIn = false;
});
};
$scope.logout();
});
module.factory('AuthService', function ($http, SessionService, AUTH_MESSAGES, URLS) {
var authService = {};
//user Registration Service
authService.register = function (credentials) {
//Real login
return $http
.post((URLS.SITE_URL + URLS.REGISTER), credentials, {
cache: false,
withCredentials: true,
})
.then(function (res) {
if (res.data.error) {
var message = AUTH_MESSAGES[res.data.error.message] || res.data.error.message;
throw Error(message);
} else {
console.log("Login attempt: ");
console.dir(res.data);
return res.data;
}
});
};
//user login Service
authService.login = function (credentials) {
//Real login
return $http
.post((URLS.SITE_URL + URLS.LOGIN), credentials, {
cache: false,
withCredentials: true,
})
.then(function (res) {
if (res.data.error) {
var message = AUTH_MESSAGES[res.data.error] || res.data.error;
throw Error(message);
} else {
console.log("Login attempt: ");
console.dir(res.data);
SessionService.create(res.data);
return res.data;
}
});
};
//user logout Service
authService.logout = function () {
return $http({
url: URLS.SITE_URL + URLS.LOGOUT,
method: "POST",
headers: {'Authorization': SessionService.getID()}
})
.success(function () {
SessionService.destroy();
}).error(function (res) {
console.log(res)
});
};
// get user details
authService.getUserDetails = function() {
return $http
.get((URLS.SITE_URL + URLS.GET_USER_INFO + SessionService.getUserID()), {
cache: false,
withCredentials: true,
headers: {'Authorization': SessionService.getID()}
}).then(function (res) {
if (res.data.error) {
var message = AUTH_MESSAGES[res.data.error] || res.data.error;
throw Error(message);
} else {
return res.data;
}
});
};
//update user details
authService.updateUserDetails = function(userDetails) {
return $http
.put((URLS.SITE_URL + URLS.UPDATE_USER_DETAILS + SessionService.getUserID()), userDetails, {
cache: false,
withCredentials: true,
headers: {'Authorization': SessionService.getID()}
}).then(function (res) {
if (res.data.error) {
var message = AUTH_MESSAGES[res.data.error] || res.data.error;
throw Error(message);
} else {
return res.data;
}
});
};
// password resest service
authService.resetpassword = function (credentials) {
//Real login
return $http
.post((URLS.SITE_URL + URLS.RESETPASSWORD), credentials, {
cache: false,
withCredentials: true,
headers: {'Authorization': SessionService.getID()}
})
.then(function (res) {
if (res.data.error) {
var message = AUTH_MESSAGES[res.data.error] || res.data.error;
throw Error(message);
} else {
console.log("Login attempt: ");
console.dir(res.data);
return res.data;
}
});
};
// password resest service
authService.changepassword = function (credentials) {
//Real login
return $http
.put((URLS.SITE_URL + URLS.CHANGE_PASSWORD + SessionService.getUserID()), credentials, {
cache: false,
withCredentials: true,
headers: {'Authorization': SessionService.getID()}
})
.then(function (res) {
if (res.data.error) {
var message = AUTH_MESSAGES[res.data.error] || res.data.error;
throw Error(message);
} else {
console.log("Login attempt: ");
console.dir(res.data);
return res.data;
}
});
};
authService.isAuthenticated = function () {
return !!Session.userId;
};
authService.isAuthorized = function (authorizedRoles) {
if (!angular.isArray(authorizedRoles)) {
authorizedRoles = [authorizedRoles];
}
return (authService.isAuthenticated() &&
authorizedRoles.indexOf(Session.userRole) !== -1);
};
return authService;
});
module.factory('SessionService', function () {
var sessionService = {};
sessionService.create = function (data) {
this.id = data.id;
this.userID = data.userId;
this.username = data.user.username;
this.userEmail = data.user.email;
};
sessionService.destroy = function () {
this.id = null;
this.userID = null;
this.username = null;
this.userEmail = null;
};
sessionService.getID = function () {
return this.id;
};
sessionService.getUserID = function () {
return this.userID;
};
sessionService.getUsername = function () {
return this.username;
}
sessionService.getUserEmail = function () {
return this.userEmail;
};
sessionService.isAuthorized = function () {
return ((!!this.userID));
};
return sessionService;
})
| rkdesign/cri-web | app/angular-constructs/authentication/Authentication.js | JavaScript | apache-2.0 | 12,327 |
/* dialog js
----------------------------------------------------------
@package: Zotonic 2009, 2012
@Author: Tim Benniks <[email protected]>
Copyright 2009 Tim Benniks
Copyright 2012 Arjan Scherpenisse
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.
---------------------------------------------------------- */
(function($)
{
$.extend(
{
dialogAdd: function(options)
{
$('#zmodal').remove();
options = $.extend({}, $.ui.dialog.defaults, options);
var width = options.width;
var title = $("<div>").addClass("modal-header")
.append($("<a>").addClass("close").attr("data-dismiss", "modal").html("×"))
.append($("<h3>").text(options.title));
var body = $("<div>").addClass("modal-body")
.html(options.text);
var dialogClass = 'modal';
if (typeof(options.addclass) == "string")
dialogClass += ' ' + options.addclass;
var dialog = $("<div>")
.attr("id", "zmodal")
.addClass(dialogClass)
.append(title)
.append(body)
.appendTo($("body"));
dialog.modal({backdrop: true});
if (width > 0) {
dialog.css({
width: width,
'margin-left': function () {
return -($(this).width() / 2);
}
});
}
if ($(window).width() <= 480) {
dialog.css({top: ($(window).scrollTop() + 10) + "px"});
} else if (dialog.height() > 0.8 * $(window).height()) {
dialog.addClass('high');
}
if (typeof($.widgetManager) != 'undefined') {
dialog.widgetManager();
}
z_tinymce_add(dialog);
},
dialogClose: function()
{
$('#zmodal').modal('hide');
},
dialogRemove: function(obj)
{
obj = obj || $('#zmodal');
z_tinymce_remove(obj);
obj.draggable('destroy').resizable('destroy').fadeOut(300, function()
{
$(this).remove();
});
}
});
$.widget("ui.show_dialog",
{
_init: function()
{
var title = this.options.title;
var text = this.options.text;
var width = this.options.width;
this.element.click(function()
{
$.dialogAdd(
{
title: title,
text: text,
width: width
});
});
}
});
$.ui.dialog.defaults = {
title: 'Title',
text: 'tekst'
};
})(jQuery);
| erlanger-ru/erlanger-ru.meta | modules/mod_base/lib/js/modules/z.dialog.js | JavaScript | apache-2.0 | 4,240 |
WebUtils.Models.QueryTable = Classify.newClass({
parent: WebUtils.Models.Table,
constructor: function(config) {
var self = this;
this.queryName = config.queryName;
this.schemaName = config.schemaName;
this.viewName = config.viewName || '';
var queryConfig = {};
if (this.viewName !== '') {
queryConfig.viewName = this.viewName;
}
var handleData = function(data){
self.rowHeaders(data.headers);
var columns = data.columns;
self.rows(data.rows.map(function(row) {
return new WebUtils.Models.TableRow({data: columns.map(function(columnName) { return row[columnName]; })});
}));
};
var data;
try {
data = WebUtils.API.selectRowsFromCache(this.schemaName, this.queryName, this.viewName);
handleData({
headers: data.colMetadata.map(function(colObject){
return colObject.shortCaption
}),
columns: data.colDisplayData.map(function(columnObject) {
return (columnObject.dataIndex).toLowerCase();
}),
rows: data.rows
});
}
catch(e) {
WebUtils.API.selectRows(this.schemaName, this.queryName, queryConfig).then(function(data) {
handleData({
headers: data.columnModel.map(function(columnObject) {
return columnObject.header;
}),
columns: data.columnModel.map(function(columnObject) {
return columnObject.dataIndex;
}),
rows: data.rows
});
});
}
}
}); | WNPRC-EHR-Services/wnprc-modules | WebUtils/resources/web/webutils/models/QueryTable.js | JavaScript | apache-2.0 | 1,805 |
const { parseString } = require('xml2js');
const errors = require('../errors');
/*
Format of xml request:
<Retention>
<Mode>COMPLIANCE|GOVERNANCE</Mode>
<RetainUntilDate>2020-05-20T04:58:45.413000Z</RetainUntilDate>
</Retention>
*/
/**
* validateMode - validate retention mode
* @param {array} mode - parsed xml mode array
* @return {object} - contains mode or error
*/
function validateMode(mode) {
const modeObj = {};
const expectedModes = new Set(['GOVERNANCE', 'COMPLIANCE']);
if (!mode || !mode[0]) {
modeObj.error = errors.MalformedXML.customizeDescription(
'request xml does not contain Mode');
return modeObj;
}
if (mode.length > 1) {
modeObj.error = errors.MalformedXML.customizeDescription(
'request xml contains more than one Mode');
return modeObj;
}
if (!expectedModes.has(mode[0])) {
modeObj.error = errors.MalformedXML.customizeDescription(
'Mode request xml must be one of "GOVERNANCE", "COMPLIANCE"');
return modeObj;
}
modeObj.mode = mode[0];
return modeObj;
}
/**
* validateRetainDate - validate retain until date
* @param {array} retainDate - parsed xml retention date array
* @return {object} - contains retain until date or error
*/
function validateRetainDate(retainDate) {
const dateObj = {};
if (!retainDate || !retainDate[0]) {
dateObj.error = errors.MalformedXML.customizeDescription(
'request xml does not contain RetainUntilDate');
return dateObj;
}
const retentionDate = Date.parse(retainDate[0]);
if (isNaN(retentionDate)) {
dateObj.error = errors.InvalidRequest.customizeDescription(
'RetainUntilDate is not a valid timestamp');
return dateObj;
}
const date = new Date(retentionDate);
if (date < Date.now()) {
dateObj.error = errors.InvalidRequest.customizeDescription(
'RetainUntilDate must be in the future');
return dateObj;
}
dateObj.date = retainDate[0];
return dateObj;
}
/**
* validate retention - validate retention xml
* @param {object} parsedXml - parsed retention xml object
* @return {object} - contains retention information on success,
* error on failure
*/
function validateRetention(parsedXml) {
const retentionObj = {};
if (!parsedXml) {
retentionObj.error = errors.MalformedXML.customizeDescription(
'request xml is undefined or empty');
return retentionObj;
}
const retention = parsedXml.Retention;
if (!retention) {
retentionObj.error = errors.MalformedXML.customizeDescription(
'request xml does not contain Retention');
return retentionObj;
}
const modeObj = validateMode(retention.Mode);
if (modeObj.error) {
retentionObj.error = modeObj.error;
return retentionObj;
}
const dateObj = validateRetainDate(retention.RetainUntilDate);
if (dateObj.error) {
retentionObj.error = dateObj.error;
return retentionObj;
}
retentionObj.mode = modeObj.mode;
retentionObj.date = dateObj.date;
return retentionObj;
}
/**
* parseRetentionXml - Parse and validate xml body, returning callback with
* object retentionObj: { mode: <value>, date: <value> }
* @param {string} xml - xml body to parse and validate
* @param {object} log - Werelogs logger
* @param {function} cb - callback to server
* @return {undefined} - calls callback with object retention or error
*/
function parseRetentionXml(xml, log, cb) {
parseString(xml, (err, result) => {
if (err) {
log.trace('xml parsing failed', {
error: err,
method: 'parseRetentionXml',
});
log.debug('invalid xml', { xml });
return cb(errors.MalformedXML);
}
const retentionObj = validateRetention(result);
if (retentionObj.error) {
log.debug('retention validation failed', {
error: retentionObj.error,
method: 'validateRetention',
xml,
});
return cb(retentionObj.error);
}
return cb(null, retentionObj);
});
}
/**
* convertToXml - Convert retention info object to xml
* @param {string} mode - retention mode
* @param {string} date - retention retain until date
* @return {string} - returns retention information xml string
*/
function convertToXml(mode, date) {
const xml = [];
xml.push('<Retention xmlns="http://s3.amazonaws.com/doc/2006-03-01/">');
if (mode && date) {
xml.push(`<Mode>${mode}</Mode>`);
xml.push(`<RetainUntilDate>${date}</RetainUntilDate>`);
} else {
return '';
}
xml.push('</Retention>');
return xml.join('');
}
module.exports = {
parseRetentionXml,
convertToXml,
};
| scality/Arsenal | lib/s3middleware/objectRetention.js | JavaScript | apache-2.0 | 4,908 |
OG.shape.Expander = function (label) {
OG.shape.Expander.superclass.call(this, 'tree/shape/expand.svg', label);
this.SHAPE_ID = 'OG.shape.Expander';
this.LABEL_EDITABLE = false;
this.label = label;
this.MOVABLE = false;
this.CONNECTABLE = false;
this.DELETABLE = false;
};
OG.shape.Expander.prototype = new OG.shape.ImageShape();
OG.shape.Expander.superclass = OG.shape.ImageShape;
OG.shape.Expander.prototype.constructor = OG.shape.Expander;
OG.Expander = OG.shape.Expander; | EXEM-OSS/flamingo | flamingo-opengraph/src/main/webapp/examples/tree/shape/Expander.js | JavaScript | apache-2.0 | 504 |
// Copyright 2022 Google LLC
//
// 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
//
// https://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.
//
// ** This file is automatically generated by gapic-generator-typescript. **
// ** https://github.com/googleapis/gapic-generator-typescript **
// ** All changes to this file may be overwritten. **
'use strict';
function main(parent) {
// [START cloudasset_v1p5beta1_generated_AssetService_ListAssets_async]
/**
* TODO(developer): Uncomment these variables before running the sample.
*/
/**
* Required. Name of the organization or project the assets belong to. Format:
* "organizations/[organization-number]" (such as "organizations/123"),
* "projects/[project-number]" (such as "projects/my-project-id"), or
* "projects/[project-id]" (such as "projects/12345").
*/
// const parent = 'abc123'
/**
* Timestamp to take an asset snapshot. This can only be set to a timestamp
* between 2018-10-02 UTC (inclusive) and the current time. If not specified,
* the current time will be used. Due to delays in resource data collection
* and indexing, there is a volatile window during which running the same
* query may get different results.
*/
// const readTime = {}
/**
* A list of asset types of which to take a snapshot for. For example:
* "compute.googleapis.com/Disk". If specified, only matching assets will be
* returned. See Introduction to Cloud Asset
* Inventory (https://cloud.google.com/resource-manager/docs/cloud-asset-inventory/overview)
* for all supported asset types.
*/
// const assetTypes = 'abc123'
/**
* Asset content type. If not specified, no content but the asset name will
* be returned.
*/
// const contentType = {}
/**
* The maximum number of assets to be returned in a single response. Default
* is 100, minimum is 1, and maximum is 1000.
*/
// const pageSize = 1234
/**
* The `next_page_token` returned from the previous `ListAssetsResponse`, or
* unspecified for the first `ListAssetsRequest`. It is a continuation of a
* prior `ListAssets` call, and the API should return the next page of assets.
*/
// const pageToken = 'abc123'
// Imports the Asset library
const {AssetServiceClient} = require('asset').v1p5beta1;
// Instantiates a client
const assetClient = new AssetServiceClient();
async function callListAssets() {
// Construct request
const request = {
parent,
};
// Run request
const iterable = await assetClient.listAssetsAsync(request);
for await (const response of iterable) {
console.log(response);
}
}
callListAssets();
// [END cloudasset_v1p5beta1_generated_AssetService_ListAssets_async]
}
process.on('unhandledRejection', err => {
console.error(err.message);
process.exitCode = 1;
});
main(...process.argv.slice(2));
| googleapis/nodejs-asset | samples/generated/v1p5beta1/asset_service.list_assets.js | JavaScript | apache-2.0 | 3,355 |
require(['jquery', 'knockout', 'formAlerts', 'cmsLayout', 'dataTable'], function ($, ko, formAlertsModule) {
function FolderViewModel() {
var self = this;
self.folderName = ko.observable();
self.orderNumber = ko.observable(0);
self.folderNameIsRequiredStyle = ko.computed(function () {
return self.folderName() === null || self.folderName() === '' ? 'error' : 'invisible';
});
self.addFolderFormIsValid = ko.computed(function () {
return self.folderName() !== null && self.folderName() !== '';
});
}
var viewModel = {
folderViewModel: new FolderViewModel(),
formAlerts: new formAlertsModule.formAlerts()
};
$(document).ready(function () {
ko.applyBindings(viewModel);
$('#foldersList').dataTable({
'iTabIndex': -1,
'sPaginationType': 'full_numbers',
'bProcessing': true,
'bServerSide': true,
'bFilter': false,
'aLengthMenu': [10, 20, 30],
'bPaginate': true,
'bLengthChange': true,
'sAjaxSource': 'foldersList',
aoColumns: [
{'bSortable': false, mData: '#'},
{'bSortable': false, mData: 'folderName'},
{'bSortable': false, mData: 'orderNumber'},
{
'bSortable': false, mData: 'id',
"fnRender": function (o) {
return '<button class="button red tiny" name="deleteFolderButton" value="' + o.aData.id + '" tabindex="-1">Delete</button>';
}
}
]
});
});
$('#addFolderButton').click(function () {
addFolder();
});
$('body').on('click', 'button[name="deleteFolderButton"]', function () {
deleteFolder($(this).val());
});
$('#resetAddFolder').click(function () {
viewModel.folderViewModel.folderName(null);
viewModel.folderViewModel.orderNumber(0);
viewModel.formAlerts.cleanAllMessages();
});
function addFolder() {
viewModel.formAlerts.cleanAllMessages();
$.ajax({
type: 'POST',
dataType: 'json',
url: 'addFolder',
data: "folderName=" + viewModel.folderViewModel.folderName() + "&orderNumber=" + viewModel.folderViewModel.orderNumber(),
success: function (response) {
if (response.status === 'SUCCESS') {
$("#foldersList").dataTable().fnDraw();
viewModel.folderViewModel.folderName(null);
viewModel.folderViewModel.orderNumber(0);
} else {
for (var i = 0; i < response.errorMessages.length; i++) {
viewModel.formAlerts.addWarning(response.errorMessages[i].error);
}
}
},
error: function (response) {
viewModel.formAlerts.addMessage(response, 'error');
}
});
}
function deleteFolder(idValue) {
$.ajax({
type: 'POST',
dataType: 'json',
url: 'deleteFolder',
data: "id=" + idValue,
success: function (response) {
if (response.status === 'SUCCESS') {
$("#foldersList").dataTable().fnDraw();
} else {
for (var i = 0; i < response.errorMessages.length; i++) {
viewModel.formAlerts.addWarning(response.errorMessages[i].error);
}
}
},
error: function (response) {
viewModel.formAlerts.addMessage(response, 'error');
}
});
}
});
| RadoslawOsinski/cwsfe_cms | cwsfe_cms_website/src/main/webapp/resources-cwsfe-cms/js/cms/folders/Folders.js | JavaScript | apache-2.0 | 3,810 |
/**
* @license
* Copyright The Closure Library Authors.
* SPDX-License-Identifier: Apache-2.0
*/
/**
* @fileoverview Closure user agent detection.
* @see http://en.wikipedia.org/wiki/User_agent
* For more information on browser brand, platform, or device see the other
* sub-namespaces in goog.labs.userAgent (browser, platform, and device).
*/
goog.provide('goog.labs.userAgent.engine');
goog.require('goog.array');
goog.require('goog.labs.userAgent.util');
goog.require('goog.string');
/**
* @return {boolean} Whether the rendering engine is Presto.
*/
goog.labs.userAgent.engine.isPresto = function() {
'use strict';
return goog.labs.userAgent.util.matchUserAgent('Presto');
};
/**
* @return {boolean} Whether the rendering engine is Trident.
*/
goog.labs.userAgent.engine.isTrident = function() {
'use strict';
// IE only started including the Trident token in IE8.
return goog.labs.userAgent.util.matchUserAgent('Trident') ||
goog.labs.userAgent.util.matchUserAgent('MSIE');
};
/**
* @return {boolean} Whether the rendering engine is EdgeHTML.
*/
goog.labs.userAgent.engine.isEdge = function() {
'use strict';
return goog.labs.userAgent.util.matchUserAgent('Edge');
};
/**
* @return {boolean} Whether the rendering engine is WebKit. This will return
* true for Chrome, Blink-based Opera (15+), Edge Chromium and Safari.
*/
goog.labs.userAgent.engine.isWebKit = function() {
'use strict';
return goog.labs.userAgent.util.matchUserAgentIgnoreCase('WebKit') &&
!goog.labs.userAgent.engine.isEdge();
};
/**
* @return {boolean} Whether the rendering engine is Gecko.
*/
goog.labs.userAgent.engine.isGecko = function() {
'use strict';
return goog.labs.userAgent.util.matchUserAgent('Gecko') &&
!goog.labs.userAgent.engine.isWebKit() &&
!goog.labs.userAgent.engine.isTrident() &&
!goog.labs.userAgent.engine.isEdge();
};
/**
* @return {string} The rendering engine's version or empty string if version
* can't be determined.
*/
goog.labs.userAgent.engine.getVersion = function() {
'use strict';
var userAgentString = goog.labs.userAgent.util.getUserAgent();
if (userAgentString) {
var tuples = goog.labs.userAgent.util.extractVersionTuples(userAgentString);
var engineTuple = goog.labs.userAgent.engine.getEngineTuple_(tuples);
if (engineTuple) {
// In Gecko, the version string is either in the browser info or the
// Firefox version. See Gecko user agent string reference:
// http://goo.gl/mULqa
if (engineTuple[0] == 'Gecko') {
return goog.labs.userAgent.engine.getVersionForKey_(tuples, 'Firefox');
}
return engineTuple[1];
}
// MSIE has only one version identifier, and the Trident version is
// specified in the parenthetical. IE Edge is covered in the engine tuple
// detection.
var browserTuple = tuples[0];
var info;
if (browserTuple && (info = browserTuple[2])) {
var match = /Trident\/([^\s;]+)/.exec(info);
if (match) {
return match[1];
}
}
}
return '';
};
/**
* @param {!Array<!Array<string>>} tuples Extracted version tuples.
* @return {!Array<string>|undefined} The engine tuple or undefined if not
* found.
* @private
*/
goog.labs.userAgent.engine.getEngineTuple_ = function(tuples) {
'use strict';
if (!goog.labs.userAgent.engine.isEdge()) {
return tuples[1];
}
for (var i = 0; i < tuples.length; i++) {
var tuple = tuples[i];
if (tuple[0] == 'Edge') {
return tuple;
}
}
};
/**
* @param {string|number} version The version to check.
* @return {boolean} Whether the rendering engine version is higher or the same
* as the given version.
*/
goog.labs.userAgent.engine.isVersionOrHigher = function(version) {
'use strict';
return goog.string.compareVersions(
goog.labs.userAgent.engine.getVersion(), version) >= 0;
};
/**
* @param {!Array<!Array<string>>} tuples Version tuples.
* @param {string} key The key to look for.
* @return {string} The version string of the given key, if present.
* Otherwise, the empty string.
* @private
*/
goog.labs.userAgent.engine.getVersionForKey_ = function(tuples, key) {
'use strict';
// TODO(nnaze): Move to util if useful elsewhere.
var pair = goog.array.find(tuples, function(pair) {
'use strict';
return key == pair[0];
});
return pair && pair[1] || '';
};
| GoogleChromeLabs/chromeos_smart_card_connector | third_party/closure-library/src/closure/goog/labs/useragent/engine.js | JavaScript | apache-2.0 | 4,432 |
/*jshint strict: false */
/*global require, TRANSACTION */
////////////////////////////////////////////////////////////////////////////////
/// @brief transaction actions
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2014 ArangoDB GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Jan Steemann
/// @author Copyright 2014, ArangoDB GmbH, Cologne, Germany
/// @author Copyright 2012, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
var arangodb = require("org/arangodb");
var actions = require("org/arangodb/actions");
// -----------------------------------------------------------------------------
// --SECTION-- private functions
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @startDocuBlock JSF_post_api_transaction
/// @brief execute a server-side transaction
///
/// @RESTHEADER{POST /_api/transaction, Execute transaction}
///
/// @RESTBODYPARAM{body,string,required}
/// Contains the *collections* and *action*.
///
/// @RESTDESCRIPTION
///
/// The transaction description must be passed in the body of the POST request.
///
/// The following attributes must be specified inside the JSON object:
///
/// - *collections*: contains the list of collections to be used in the
/// transaction (mandatory). *collections* must be a JSON array that can
/// have the optional sub-attributes *read* and *write*. *read*
/// and *write* must each be either lists of collections names or strings
/// with a single collection name.
///
/// - *action*: the actual transaction operations to be executed, in the
/// form of stringified Javascript code. The code will be executed on server
/// side, with late binding. It is thus critical that the code specified in
/// *action* properly sets up all the variables it needs.
/// If the code specified in *action* ends with a return statement, the
/// value returned will also be returned by the REST API in the *result*
/// attribute if the transaction committed successfully.
///
/// The following optional attributes may also be specified in the request:
///
/// - *waitForSync*: an optional boolean flag that, if set, will force the
/// transaction to write all data to disk before returning.
///
/// - *lockTimeout*: an optional numeric value that can be used to set a
/// timeout for waiting on collection locks. If not specified, a default
/// value will be used. Setting *lockTimeout* to *0* will make ArangoDB
/// not time out waiting for a lock.
///
/// - *params*: optional arguments passed to *action*.
///
/// If the transaction is fully executed and committed on the server,
/// *HTTP 200* will be returned. Additionally, the return value of the
/// code defined in *action* will be returned in the *result* attribute.
///
/// For successfully committed transactions, the returned JSON object has the
/// following properties:
///
/// - *error*: boolean flag to indicate if an error occurred (*false*
/// in this case)
///
/// - *code*: the HTTP status code
///
/// - *result*: the return value of the transaction
///
/// If the transaction specification is either missing or malformed, the server
/// will respond with *HTTP 400*.
///
/// The body of the response will then contain a JSON object with additional error
/// details. The object has the following attributes:
///
/// - *error*: boolean flag to indicate that an error occurred (*true* in this case)
///
/// - *code*: the HTTP status code
///
/// - *errorNum*: the server error number
///
/// - *errorMessage*: a descriptive error message
///
/// If a transaction fails to commit, either by an exception thrown in the
/// *action* code, or by an internal error, the server will respond with
/// an error.
/// Any other errors will be returned with any of the return codes
/// *HTTP 400*, *HTTP 409*, or *HTTP 500*.
///
/// @RESTRETURNCODES
///
/// @RESTRETURNCODE{200}
/// If the transaction is fully executed and committed on the server,
/// *HTTP 200* will be returned.
///
/// @RESTRETURNCODE{400}
/// If the transaction specification is either missing or malformed, the server
/// will respond with *HTTP 400*.
///
/// @RESTRETURNCODE{404}
/// If the transaction specification contains an unknown collection, the server
/// will respond with *HTTP 404*.
///
/// @RESTRETURNCODE{500}
/// Exceptions thrown by users will make the server respond with a return code of
/// *HTTP 500*
///
/// @EXAMPLES
///
/// Executing a transaction on a single collection:
///
/// @EXAMPLE_ARANGOSH_RUN{RestTransactionSingle}
/// var cn = "products";
/// db._drop(cn);
/// var products = db._create(cn);
/// var url = "/_api/transaction";
/// var body = {
/// collections: {
/// write : "products"
/// },
/// action: "function () { var db = require('internal').db; db.products.save({}); return db.products.count(); }"
/// };
///
/// var response = logCurlRequest('POST', url, body);
/// assert(response.code === 200);
///
/// logJsonResponse(response);
/// db._drop(cn);
/// @END_EXAMPLE_ARANGOSH_RUN
///
/// Executing a transaction using multiple collections:
///
/// @EXAMPLE_ARANGOSH_RUN{RestTransactionMulti}
/// var cn1 = "materials";
/// db._drop(cn1);
/// var materials = db._create(cn1);
/// var cn2 = "products";
/// db._drop(cn2);
/// var products = db._create(cn2);
/// products.save({ "a": 1});
/// materials.save({ "b": 1});
/// var url = "/_api/transaction";
/// var body = {
/// collections: {
/// write : [ "products", "materials" ]
/// },
/// action: (
/// "function () {" +
/// "var db = require('internal').db;" +
/// "db.products.save({});" +
/// "db.materials.save({});" +
/// "return 'worked!';" +
/// "}"
/// )
/// };
///
/// var response = logCurlRequest('POST', url, body);
/// assert(response.code === 200);
///
/// logJsonResponse(response);
/// db._drop(cn1);
/// db._drop(cn2);
/// @END_EXAMPLE_ARANGOSH_RUN
///
/// Aborting a transaction due to an internal error:
///
/// @EXAMPLE_ARANGOSH_RUN{RestTransactionAbortInternal}
/// var cn = "products";
/// db._drop(cn);
/// var products = db._create(cn);
/// var url = "/_api/transaction";
/// var body = {
/// collections: {
/// write : "products"
/// },
/// action : (
/// "function () {" +
/// "var db = require('internal').db;" +
/// "db.products.save({ _key: 'abc'});" +
/// "db.products.save({ _key: 'abc'});" +
/// "}"
/// )
/// };
///
/// var response = logCurlRequest('POST', url, body);
/// assert(response.code === 400);
///
/// logJsonResponse(response);
/// db._drop(cn);
/// @END_EXAMPLE_ARANGOSH_RUN
///
/// Aborting a transaction by explicitly throwing an exception:
///
/// @EXAMPLE_ARANGOSH_RUN{RestTransactionAbort}
/// var cn = "products";
/// db._drop(cn);
/// var products = db._create(cn, { waitForSync: true });
/// products.save({ "a": 1 });
/// var url = "/_api/transaction";
/// var body = {
/// collections: {
/// read : "products"
/// },
/// action : "function () { throw 'doh!'; }"
/// };
///
/// var response = logCurlRequest('POST', url, body);
/// assert(response.code === 500);
///
/// logJsonResponse(response);
/// db._drop(cn);
/// @END_EXAMPLE_ARANGOSH_RUN
///
/// Referring to a non-existing collection:
///
/// @EXAMPLE_ARANGOSH_RUN{RestTransactionNonExisting}
/// var cn = "products";
/// db._drop(cn);
/// var url = "/_api/transaction";
/// var body = {
/// collections: {
/// read : "products"
/// },
/// action : "function () { return true; }"
/// };
///
/// var response = logCurlRequest('POST', url, body);
/// assert(response.code === 404);
///
/// logJsonResponse(response);
/// @END_EXAMPLE_ARANGOSH_RUN
/// @endDocuBlock
////////////////////////////////////////////////////////////////////////////////
function post_api_transaction(req, res) {
var json = actions.getJsonBody(req, res);
if (json === undefined) {
actions.resultBad(req, res, arangodb.ERROR_HTTP_BAD_PARAMETER);
return;
}
var result = TRANSACTION(json);
actions.resultOk(req, res, actions.HTTP_OK, { result : result });
}
// -----------------------------------------------------------------------------
// --SECTION-- initialiser
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief gateway
////////////////////////////////////////////////////////////////////////////////
actions.defineHttp({
url : "_api/transaction",
callback : function (req, res) {
try {
switch (req.requestType) {
case actions.POST:
post_api_transaction(req, res);
break;
default:
actions.resultUnsupported(req, res);
}
}
catch (err) {
actions.resultException(req, res, err);
}
}
});
// -----------------------------------------------------------------------------
// --SECTION-- END-OF-FILE
// -----------------------------------------------------------------------------
// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @page\\|// --SECTION--\\|/// @\\}"
// End:
| morsdatum/ArangoDB | js/actions/api-transaction.js | JavaScript | apache-2.0 | 10,360 |
import React from "react";
import { configure, shallow } from "enzyme";
import Adapter from "enzyme-adapter-react-16";
import LandingPage from "./LandingPage";
import LoginButtonSet from "../../components/UI/LoginButtonSet/LoginButtonSet";
configure({ adapter: new Adapter() });
describe("<LandingPage />", () => {
let wrapper;
beforeEach(() => {
wrapper = shallow(<LandingPage />);
});
it("should render", () => {
expect(wrapper.exists()).toBeTruthy();
});
it("should have a h1 header which displays 'Who's the next trendsetter?'", () => {
expect(wrapper.find("h1").text()).toEqual("Who's the next trendsetter?");
});
it("should have a h3 header which displays the brief description of the game", () => {
expect(wrapper.find("h3").text()).toEqual(
"Something something a description of what the game does, what benefits it has. Something something ..."
);
});
it("should contain a LoginButtonSet", () => {
expect(wrapper.find(LoginButtonSet).exists()).toBeTruthy();
});
// it("should contain an illustration image", () => {
// expect(wrapper.find("img").exists()).toBeTruthy();
// });
});
| googleinterns/sgonks | project/frontend/src/containers/LandingPage/LandingPage.test.js | JavaScript | apache-2.0 | 1,164 |
// Copyright 2009 The Closure Library Authors. 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.
/**
* @fileoverview Character Picker widget for picking any Unicode character.
*
*
* @see ../demos/charpicker.html
*/
goog.provide('goog.ui.CharPicker');
goog.require('goog.array');
goog.require('goog.dom');
goog.require('goog.events');
goog.require('goog.events.EventType');
goog.require('goog.events.InputHandler');
goog.require('goog.i18n.CharListDecompressor');
goog.require('goog.i18n.uChar');
goog.require('goog.structs.Set');
goog.require('goog.style');
goog.require('goog.ui.Button');
goog.require('goog.ui.ContainerScroller');
goog.require('goog.ui.FlatButtonRenderer');
goog.require('goog.ui.HoverCard');
goog.require('goog.ui.LabelInput');
goog.require('goog.ui.Menu');
goog.require('goog.ui.MenuButton');
goog.require('goog.ui.MenuItem');
/**
* Character Picker Class. This widget can be used to pick any Unicode
* character by traversing a category-subcategory structure or by inputing its
* hex value.
*
* See charpicker.html demo for example usage.
* @param {goog.i18n.CharPickerData} charPickerData Category names and charlist.
* @param {Array.<string>=} opt_recents List of characters to be displayed in
* resently selected characters area.
* @param {number=} opt_initCategory Sequence number of initial category.
* @param {number=} opt_initSubcategory Sequence number of initial subcategory.
* @param {number=} opt_rowCount Number of rows in the grid.
* @param {number=} opt_columnCount Number of columns in the grid.
* @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper.
* @constructor
* @extends {goog.ui.Component}
*/
goog.ui.CharPicker = function(charPickerData, opt_recents, opt_initCategory,
opt_initSubcategory, opt_rowCount,
opt_columnCount, opt_domHelper) {
goog.ui.Component.call(this, opt_domHelper);
/**
* Object containing character lists and category names.
* @type {goog.i18n.CharPickerData}
* @private
*/
this.data_ = charPickerData;
/**
* The category number to be used on widget init.
* @type {number}
* @private
*/
this.initCategory_ = opt_initCategory || 0;
/**
* The subcategory number to be used on widget init.
* @type {number}
* @private
*/
this.initSubcategory_ = opt_initSubcategory || 0;
/**
* Number of columns in the grid.
* @type {number}
* @private
*/
this.columnCount_ = opt_columnCount || 10;
/**
* Number of entries to be added to the grid.
* @type {number}
* @private
*/
this.gridsize_ = (opt_rowCount || 10) * this.columnCount_;
/**
* Number of the recently selected characters displayed.
* @type {number}
* @private
*/
this.recentwidth_ = this.columnCount_ + 1;
/**
* List of recently used characters.
* @type {Array.<string>}
* @private
*/
this.recents_ = opt_recents || [];
/**
* Handler for events.
* @type {goog.events.EventHandler}
* @private
*/
this.eventHandler_ = new goog.events.EventHandler(this);
/**
* Decompressor used to get the list of characters from a base88 encoded
* character list.
* @type {Object}
* @private
*/
this.decompressor_ = new goog.i18n.CharListDecompressor();
};
goog.inherits(goog.ui.CharPicker, goog.ui.Component);
/**
* The last selected character.
* @type {?string}
* @private
*/
goog.ui.CharPicker.prototype.selectedChar_ = null;
/**
* Set of formatting characters whose display need to be swapped with nbsp
* to prevent layout issues.
* @type {goog.structs.Set}
* @private
*/
goog.ui.CharPicker.prototype.layoutAlteringChars_ = null;
/**
* The top category menu.
* @type {goog.ui.Menu}
* @private
*/
goog.ui.CharPicker.prototype.menu_ = null;
/**
* The top category menu button.
* @type {goog.ui.MenuButton}
* @private
*/
goog.ui.CharPicker.prototype.menubutton_ = null;
/**
* The subcategory menu.
* @type {goog.ui.Menu}
* @private
*/
goog.ui.CharPicker.prototype.submenu_ = null;
/**
* The subcategory menu button.
* @type {goog.ui.MenuButton}
* @private
*/
goog.ui.CharPicker.prototype.submenubutton_ = null;
/**
* The element representing the number of rows visible in the grid.
* This along with goog.ui.CharPicker.stick_ would help to create a scrollbar
* of right size.
* @type {Element}
* @private
*/
goog.ui.CharPicker.prototype.stickwrap_ = null;
/**
* The component containing all the buttons for each character in display.
* @type {goog.ui.Component}
* @private
*/
goog.ui.CharPicker.prototype.grid_ = null;
/**
* The component used for extra information about the character set displayed.
* @type {goog.ui.Component}
* @private
*/
goog.ui.CharPicker.prototype.notice_ = null;
/**
* Grid displaying recently selected characters.
* @type {goog.ui.Component}
* @private
*/
goog.ui.CharPicker.prototype.recentgrid_ = null;
/**
* Input field for entering the hex value of the character.
* @type {goog.ui.Component}
* @private
*/
goog.ui.CharPicker.prototype.input_ = null;
/**
* OK button for entering hex value of the character.
* @type {goog.ui.Component}
* @private
*/
goog.ui.CharPicker.prototype.okbutton_ = null;
/**
* Element displaying character in preview.
* @type {Element}
* @private
*/
goog.ui.CharPicker.prototype.zoomEl_ = null;
/**
* Element displaying character name or number in preview.
* @type {Element}
* @private
*/
goog.ui.CharPicker.prototype.unicodeEl_ = null;
/**
* Hover card for displaying the preview of a character.
* Preview would contain character in large size and its U+ notation. It would
* also display the name, if available.
* @type {goog.ui.HoverCard}
* @private
*/
goog.ui.CharPicker.prototype.hc_ = null;
/**
* Gets the last selected character.
* @return {?string} The last selected character.
*/
goog.ui.CharPicker.prototype.getSelectedChar = function() {
return this.selectedChar_;
};
/**
* Gets the list of characters user selected recently.
* @return {Array.<string>} The recent character list.
*/
goog.ui.CharPicker.prototype.getRecentChars = function() {
return this.recents_;
};
/** @inheritDoc */
goog.ui.CharPicker.prototype.createDom = function() {
goog.ui.CharPicker.superClass_.createDom.call(this);
this.decorateInternal(this.getDomHelper().createElement('div'));
};
/** @inheritDoc */
goog.ui.CharPicker.prototype.disposeInternal = function() {
this.hc_.dispose();
this.hc_ = null;
this.eventHandler_.dispose();
this.eventHandler_ = null;
goog.ui.CharPicker.superClass_.disposeInternal.call(this);
};
/** @inheritDoc */
goog.ui.CharPicker.prototype.decorateInternal = function(element) {
goog.ui.CharPicker.superClass_.decorateInternal.call(this, element);
// The chars below cause layout disruption or too narrow to hover:
// \u0020, \u00AD, \u2000 - \u200f, \u2028 - \u202f, \u3000, \ufeff
var chrs = this.decompressor_.toCharList(':2%C^O80V1H2s2G40Q%s0');
this.layoutAlteringChars_ = new goog.structs.Set(chrs);
this.menu_ = new goog.ui.Menu();
var categories = this.data_.categories;
for (var i = 0; i < this.data_.categories.length; i++) {
this.menu_.addChild(this.createMenuItem_(i, categories[i]), true);
}
this.menubutton_ = new goog.ui.MenuButton('Category Menu', this.menu_);
this.addChild(this.menubutton_, true);
this.submenu_ = new goog.ui.Menu();
this.submenubutton_ = new goog.ui.MenuButton('Subcategory Menu',
this.submenu_);
this.addChild(this.submenubutton_, true);
// The containing compnent for grid component and the scroller.
var gridcontainer = new goog.ui.Component();
this.addChild(gridcontainer, true);
var stickwrap = new goog.ui.Component();
gridcontainer.addChild(stickwrap, true);
this.stickwrap_ = stickwrap.getElement();
var stick = new goog.ui.Component();
stickwrap.addChild(stick, true);
this.stick_ = stick.getElement();
this.grid_ = new goog.ui.Component();
gridcontainer.addChild(this.grid_, true);
this.notice_ = new goog.ui.Component();
this.notice_.setElementInternal(goog.dom.createDom('div'));
this.addChild(this.notice_, true);
// The component used for displaying 'Recent Selections' label.
/**
* @desc The text label above the list of recently selected characters.
*/
var MSG_CHAR_PICKER_RECENT_SELECTIONS = goog.getMsg('Recent Selections:');
var recenttext = new goog.ui.Component();
recenttext.setElementInternal(goog.dom.createDom('span', null,
MSG_CHAR_PICKER_RECENT_SELECTIONS));
this.addChild(recenttext, true);
this.recentgrid_ = new goog.ui.Component();
this.addChild(this.recentgrid_, true);
// The component used for displaying 'U+'.
var uplus = new goog.ui.Component();
uplus.setElementInternal(goog.dom.createDom('span', null, 'U+'));
this.addChild(uplus, true);
/**
* @desc The text inside the input box to specify the hex code of a character.
*/
var MSG_CHAR_PICKER_HEX_INPUT = goog.getMsg('Hex Input');
this.input_ = new goog.ui.LabelInput(MSG_CHAR_PICKER_HEX_INPUT);
this.addChild(this.input_, true);
this.okbutton_ = new goog.ui.Button('OK');
this.addChild(this.okbutton_, true);
this.okbutton_.setEnabled(false);
this.zoomEl_ = goog.dom.createDom('div',
{id: 'zoom', className: goog.getCssName('goog-char-picker-char-zoom')});
this.unicodeEl_ = goog.dom.createDom('div',
{id: 'unicode', className: goog.getCssName('goog-char-picker-unicode')});
var card = goog.dom.createDom('div', {'id': 'preview'}, this.zoomEl_,
this.unicodeEl_);
goog.style.showElement(card, false);
this.hc_ = new goog.ui.HoverCard({'DIV': 'char'});
this.hc_.setElement(card);
var self = this;
/**
* Function called by hover card just before it is visible to collect data.
*/
function onBeforeShow() {
var trigger = self.hc_.getAnchorElement();
var ch = self.getChar_(trigger);
if (ch) {
self.zoomEl_.innerHTML = self.displayChar_(ch);
self.unicodeEl_.innerHTML = self.getTagFromChar_(ch);
}
}
goog.events.listen(this.hc_, goog.ui.HoverCard.EventType.BEFORE_SHOW,
onBeforeShow);
goog.dom.classes.add(element, goog.getCssName('goog-char-picker'));
goog.dom.classes.add(this.stick_, goog.getCssName('goog-stick'));
goog.dom.classes.add(this.stickwrap_, goog.getCssName('goog-stickwrap'));
goog.dom.classes.add(gridcontainer.getElement(),
goog.getCssName('goog-char-picker-grid-container'));
goog.dom.classes.add(this.grid_.getElement(),
goog.getCssName('goog-char-picker-grid'));
goog.dom.classes.add(this.recentgrid_.getElement(),
goog.getCssName('goog-char-picker-grid'));
goog.dom.classes.add(this.recentgrid_.getElement(),
goog.getCssName('goog-char-picker-recents'));
goog.dom.classes.add(this.notice_.getElement(),
goog.getCssName('goog-char-picker-notice'));
goog.dom.classes.add(uplus.getElement(),
goog.getCssName('goog-char-picker-uplus'));
goog.dom.classes.add(this.input_.getElement(),
goog.getCssName('goog-char-picker-input-box'));
goog.dom.classes.add(this.okbutton_.getElement(),
goog.getCssName('goog-char-picker-okbutton'));
goog.dom.classes.add(card, goog.getCssName('goog-char-picker-hovercard'));
this.hc_.className = goog.getCssName('goog-char-picker-hovercard');
this.grid_.buttoncount = this.gridsize_;
this.recentgrid_.buttoncount = this.recentwidth_;
this.populateGridWithButtons_(this.grid_);
this.populateGridWithButtons_(this.recentgrid_);
this.updateGrid_(this.recentgrid_, this.recents_);
this.setSelectedCategory_(this.initCategory_, this.initSubcategory_);
new goog.ui.ContainerScroller(this.menu_);
new goog.ui.ContainerScroller(this.submenu_);
goog.dom.classes.add(this.menu_.getElement(),
goog.getCssName('goog-char-picker-menu'));
goog.dom.classes.add(this.submenu_.getElement(),
goog.getCssName('goog-char-picker-menu'));
};
/** @inheritDoc */
goog.ui.CharPicker.prototype.enterDocument = function() {
goog.ui.CharPicker.superClass_.enterDocument.call(this);
var inputkh = new goog.events.InputHandler(this.input_.getElement());
this.keyHandler_ = new goog.events.KeyHandler(this.input_.getElement());
// Stop the propagation of ACTION events at menu and submenu buttons.
// If stopped at capture phase, the button will not be set to normal state.
// If not stopped, the user widget will receive the event, which is
// undesired. User widget should receive an event only on the character
// click.
this.eventHandler_.listen(
this.menubutton_,
goog.ui.Component.EventType.ACTION,
goog.events.Event.stopPropagation).listen(
this.submenubutton_,
goog.ui.Component.EventType.ACTION,
goog.events.Event.stopPropagation).listen(
this,
goog.ui.Component.EventType.ACTION,
this.handleSelectedItem_,
true).listen(
inputkh,
goog.events.InputHandler.EventType.INPUT,
this.handleInput_).listen(
this.keyHandler_,
goog.events.KeyHandler.EventType.KEY,
this.handleEnter_);
goog.events.listen(this.okbutton_.getElement(),
goog.events.EventType.MOUSEDOWN, this.handleOkClick_, true, this);
goog.events.listen(this.stickwrap_, goog.events.EventType.SCROLL,
this.handleScroll_, true, this);
};
/**
* On scroll, updates the grid with characters correct to the scroll position.
* @param {goog.events.Event} e Scroll event to handle.
* @private
*/
goog.ui.CharPicker.prototype.handleScroll_ = function(e) {
var height = e.target.scrollHeight;
var top = e.target.scrollTop;
var itempos = Math.ceil(top * this.items.length / (this.columnCount_ *
height)) * this.columnCount_;
if (this.itempos != itempos) {
this.itempos = itempos;
this.modifyGridWithItems_(this.grid_, this.items, itempos);
}
e.stopPropagation();
};
/**
* On a menu click, sets correct character set in the grid; on a grid click
* accept the character as the selected one and adds to recent selection, if not
* already present.
* @param {goog.events.Event} e Event for the click on menus or grid.
* @private
*/
goog.ui.CharPicker.prototype.handleSelectedItem_ = function(e) {
if (e.target.getParent() == this.menu_) {
this.menu_.setVisible(false);
this.setSelectedCategory_(e.target.getValue());
} else if (e.target.getParent() == this.submenu_) {
this.submenu_.setVisible(false);
this.setSelectedSubcategory_(e.target.getValue());
} else if (e.target.getParent() == this.grid_) {
var button = e.target.getElement();
this.selectedChar_ = this.getChar_(button);
this.updateRecents_(this.selectedChar_);
} else if (e.target.getParent() == this.recentgrid_) {
this.selectedChar_ = this.getChar_(e.target.getElement());
}
};
/**
* When user types the characters displays the preview. Enables the OK button,
* if the character is valid.
* @param {goog.events.Event} e Event for typing in input field.
* @private
*/
goog.ui.CharPicker.prototype.handleInput_ = function(e) {
var ch = this.getInputChar_();
if (ch) {
var unicode = this.getTagFromChar_(ch);
this.zoomEl_.innerHTML = ch;
this.unicodeEl_.innerHTML = unicode;
var coord =
new goog.ui.Tooltip.ElementTooltipPosition(this.input_.getElement());
this.hc_.setPosition(coord);
this.hc_.triggerForElement(this.input_.getElement());
this.okbutton_.setEnabled(true);
} else {
this.hc_.cancelTrigger();
this.hc_.setVisible(false);
this.okbutton_.setEnabled(false);
}
};
/**
* On OK click accepts the character and updates the recent char list.
* @param {goog.events.Event=} opt_event Event for click on OK button.
* @return {boolean} Indicates whether to propagate event.
* @private
*/
goog.ui.CharPicker.prototype.handleOkClick_ = function(opt_event) {
var ch = this.getInputChar_();
if (ch && ch.charCodeAt(0)) {
this.selectedChar_ = ch;
this.updateRecents_(ch);
return true;
}
return false;
};
/**
* Behaves exactly like the OK button on Enter key.
* @param {goog.events.KeyEvent} e Event for enter on the input field.
* @return {boolean} Indicates whether to propagate event.
* @private
*/
goog.ui.CharPicker.prototype.handleEnter_ = function(e) {
if (e.keyCode == goog.events.KeyCodes.ENTER) {
return this.handleOkClick_() ?
this.dispatchEvent(goog.ui.Component.EventType.ACTION) : false;
}
};
/**
* Gets the character from the event target.
* @param {Element} e Event target containing the 'char' attribute.
* @return {string} The character specified in the event.
* @private
*/
goog.ui.CharPicker.prototype.getChar_ = function(e) {
return e.getAttribute('char');
};
/**
* Creates a menu entry for either the category listing or subcategory listing.
* @param {number} id Id to be used for the entry.
* @param {string} caption Text displayed for the menu item.
* @return {goog.ui.MenuItem} Menu item to be added to the menu listing.
* @private
*/
goog.ui.CharPicker.prototype.createMenuItem_ = function(id, caption) {
var item = new goog.ui.MenuItem(caption);
item.setValue(id);
item.setVisible(true);
return item;
};
/**
* Sets the category and updates the submenu items and grid accordingly.
* @param {number} category Category index used to index the data tables.
* @param {number=} opt_subcategory Subcategory index used with category index.
* @private
*/
goog.ui.CharPicker.prototype.setSelectedCategory_ = function(category,
opt_subcategory) {
this.category = category;
this.menubutton_.setCaption(this.data_.categories[category]);
while (this.submenu_.hasChildren()) {
this.submenu_.removeChildAt(0, true).dispose();
}
var subcategories = this.data_.subcategories[category];
var charList = this.data_.charList[category];
for (var i = 0; i < subcategories.length; i++) {
var subtitle = charList[i].length == 0;
var item = this.createMenuItem_(i, subcategories[i]);
this.submenu_.addChild(item, true);
}
this.setSelectedSubcategory_(opt_subcategory || 0);
};
/**
* Sets the subcategory and updates the grid accordingly.
* @param {number} subcategory Sub-category index used to index the data tables.
* @private
*/
goog.ui.CharPicker.prototype.setSelectedSubcategory_ = function(subcategory) {
var subcategories = this.data_.subcategories;
var name = subcategories[this.category][subcategory];
this.submenubutton_.setCaption(name);
this.setSelectedGrid_(this.category, subcategory);
};
/**
* Updates the grid according to a given category and subcategory.
* @param {number} category Index to the category table.
* @param {number} subcategory Index to the subcategory table.
* @private
*/
goog.ui.CharPicker.prototype.setSelectedGrid_ = function(category,
subcategory) {
var charLists = this.data_.charList;
var charListStr = charLists[category][subcategory];
var content = this.decompressor_.toCharList(charListStr);
this.updateGrid_(this.grid_, content);
};
/**
* Updates the grid with new character list.
* @param {goog.ui.Component} grid The grid which is updated with a new set of
* characters.
* @param {Array.<string>} items Characters to be added to the grid.
* @private
*/
goog.ui.CharPicker.prototype.updateGrid_ = function(grid, items) {
if (grid == this.grid_) {
/**
* @desc The message used when there are invisible characters like space
* or format control characters.
*/
var MSG_PLEASE_HOVER =
goog.getMsg('Please hover over each cell for the character name.');
this.notice_.getElement().innerHTML = goog.i18n.uChar.toName(items[0]) ?
MSG_PLEASE_HOVER : '';
this.items = items;
if (this.stickwrap_.offsetHeight > 0) {
this.stick_.style.height =
this.stickwrap_.offsetHeight * items.length / this.gridsize_ + 'px';
} else {
// This is the last ditch effort if height is not avaialble.
// Maximum of 3em is assumed to the the cell height. Extra space after
// last character in the grid is OK.
this.stick_.style.height = 3 * this.columnCount_ * items.length /
this.gridsize_ + 'em';
}
this.stickwrap_.scrollTop = 0;
}
this.modifyGridWithItems_(grid, items, 0);
};
/**
* Updates the grid with new character list for a given starting point.
* @param {goog.ui.Component} grid The grid which is updated with a new set of
* characters.
* @param {Array.<string>} items Characters to be added to the grid.
* @param {number} start The index from which the characters should be
* displayed.
* @private
*/
goog.ui.CharPicker.prototype.modifyGridWithItems_ = function(grid, items,
start) {
for (var buttonpos = 0, itempos = start;
buttonpos < grid.buttoncount && itempos < items.length;
buttonpos++, itempos++) {
this.modifyCharNode_(grid.getChildAt(buttonpos), items[itempos]);
}
for (; buttonpos < grid.buttoncount; buttonpos++) {
grid.getChildAt(buttonpos).setVisible(false);
}
var first = grid.getChildAt(0);
goog.dom.setFocusableTabIndex(first.getElement(), true);
};
/**
* Creates the grid for characters to displayed for selection.
* @param {goog.ui.Component} grid The grid which is updated with a new set of
* characters.
* @private
*/
goog.ui.CharPicker.prototype.populateGridWithButtons_ = function(grid) {
for (var i = 0; i < grid.buttoncount; i++) {
var button = new goog.ui.Button(' ',
goog.ui.FlatButtonRenderer.getInstance());
grid.addChild(button, true);
button.setVisible(false);
var buttonEl = button.getElement();
goog.dom.a11y.setRole(buttonEl, 'gridcell');
}
};
/**
* Updates the grid cell with new character.
* @param {goog.ui.Component} button This button is proped up for new character.
* @param {string} ch Character to be displayed by the button.
* @private
*/
goog.ui.CharPicker.prototype.modifyCharNode_ = function(button, ch) {
var text = this.displayChar_(ch);
var buttonEl = button.getElement();
buttonEl.innerHTML = text;
buttonEl.setAttribute('char', ch);
goog.dom.setFocusableTabIndex(buttonEl, false);
button.setVisible(true);
};
/**
* Adds a given character to the recent character list.
* @param {string} character Character to be added to the recent list.
* @private
*/
goog.ui.CharPicker.prototype.updateRecents_ = function(character) {
if (character && character.charCodeAt(0) &&
!goog.array.contains(this.recents_, character)) {
this.recents_.unshift(character);
if (this.recents_.length > this.recentwidth_) {
this.recents_.pop();
}
this.updateGrid_(this.recentgrid_, this.recents_);
}
};
/**
* Gets the user inputed unicode character.
* @return {string} Unicode character inputed by user.
* @private
*/
goog.ui.CharPicker.prototype.getInputChar_ = function() {
var text = this.input_.getValue();
var code = parseInt(text, 16);
return /** @type {string} */ (goog.i18n.uChar.fromCharCode(code));
};
/**
* Gets the description text for the given character.
* @param {string} ch Character whose description is fetched.
* @return {string} The description of the given character.
* @private
*/
goog.ui.CharPicker.prototype.getTagFromChar_ = function(ch) {
var unicodetext = goog.i18n.uChar.toHexString(ch);
var name = goog.i18n.uChar.toName(ch);
if (name) {
unicodetext += ' ' + name;
}
return unicodetext;
};
/**
* Gets the display character for the given character.
* @param {string} ch Character whose display is fetched.
* @return {string} The display of the given character.
* @private
*/
goog.ui.CharPicker.prototype.displayChar_ = function(ch) {
return this.layoutAlteringChars_.contains(ch) ? '\u00A0' : ch;
};
| maxogden/googlyscript | closure-library/closure/goog/ui/charpicker.js | JavaScript | apache-2.0 | 24,534 |
/*
var arr = ['a', 'x', 'b', 'd', 'm', 'a', 'k', 'm', 'p', 'j', 'a'];
var obj = {}; //此对象中存放字符及其数量
//遍历数组arr,统计其中每个字符的数量
for (var i = 0; i < arr.length; i++) {
var arr1 = arr[i]; //arr1中包含了arr中所有字符
if (obj[arr1]) {
obj[arr1]++; //obj中有这个字符,就把其数量加1
} else {
obj[arr1] = 1; //如没有,这个字符的数量就等于1
}
}
//遍历对象obj,找到出现最多次数的字符及次数
var num = 0;
var key = null;
for (var temp in obj) {
if (obj[arr1] > num) {
num = obj[arr1];
key = arr1;
}
}
//遍历数组arr,找到最多次数的字符出现的下标
var arr2 = new Array(); //此数组存放下标
var b = 0;
for (var s = 0; s < arr.length; s++) {
if (key == arr[s]) {
arr2[b++] = s;
}
}
alert("出现最多的字符是:" + key + " , 共出现" + num + "次。出现的下标位置分别为:" + arr2.join('、') + "。")
*/
function findNum(data) {
var dataBox = {}; //存放数据
var maxChar = ''; //存放出现最多次数的字符
var maxCount = 0; //存放出现最多的次数
for (var i = 0; i < data.length; i++) {
var att = data[i];
if (!dataBox[att]) {
dataBox[att] = [];
}
dataBox[att].push(i);
if (dataBox[att].length > maxCount) {
maxChar = data[i];
maxCount = dataBox[att].length;
}
}
alert("出现最多的字符是:" + maxChar + " , 共出现" + maxCount + "次。出现的下标位置分别为:" + dataBox[maxChar] + "。")
}
| sccando/jike-sc | array/js/findNum.js | JavaScript | apache-2.0 | 1,649 |
/**
* Copyright (c) 2014-2017 Netflix, 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.
*/
/**
* Test email/password store.
*
* @author Wesley Miaw <[email protected]>
*/
(function(require, module) {
"use strict";
var EmailPasswordStore = require('msl-core/userauth/EmailPasswordStore.js');
/**
* Create a new user and password pair.
*
* @param {MslUser} user MSL user.
* @param {string} password user password.
*/
function UserAndPassword(user, password) {
this.user = user;
this.password = password;
}
var MockEmailPasswordStore = module.exports = EmailPasswordStore.extend({
init: function init() {
// Map of email addresses onto user ID and password pairs.
var credentials = {};
// The properties.
var props = {
_credentials: { value: credentials, writable: true, enumerable: false, configurable: false }
};
Object.defineProperties(this, props);
},
/**
* Add a user to the store.
*
* @param {string} email email address.
* @param {string} password password.
* @param {MslUser} user user.
*/
addUser: function addUser(email, password, user) {
if (email.trim().length == 0)
throw new TypeError("Email cannot be blank.");
if (password.trim().length == 0)
throw new TypeError("Password cannot be blank.");
var iap = new UserAndPassword(user, password);
this._credentials[email] = iap;
},
/**
* Clear all known users.
*/
clear: function clear() {
this._credentials = {};
},
/** @inheritDoc */
isUser: function isUser(email, password) {
var iap = this._credentials[email];
if (!iap || iap.password != password)
return null;
return iap.user;
}
});
})(require, (typeof module !== 'undefined') ? module : mkmodule('MockEmailPasswordStore'));
| Netflix/msl | tests/src/main/javascript/userauth/MockEmailPasswordStore.js | JavaScript | apache-2.0 | 2,676 |
(function() {
'use strict';
angular
.module('argile')
.run(runBlock);
/** @ngInject */
function runBlock($log) {
$log.debug('runBlock end');
}
})();
| zacrahm/argile | src/app/index.run.js | JavaScript | apache-2.0 | 175 |
// All material copyright ESRI, All Rights Reserved, unless otherwise specified.
// See http://js.arcgis.com/3.22/esri/copyright.txt for details.
//>>built
require({cache:{"url:esri/dijit/SizeInfoSlider/templates/SizeInfoSlider.html":'\x3cdiv class\x3d"${baseClass}"\x3e\r\n \x3cdiv data-dojo-attach-point\x3d"containerNode"\x3e\r\n \x3cdiv data-dojo-attach-point\x3d"_titleNode"\x3e\x3c/div\x3e\r\n \x3cdiv data-dojo-attach-point\x3d"_sliderNode"\x3e\x3c/div\x3e\r\n \x3cdiv data-dojo-attach-point\x3d"_scaleNode"\x3e\x3c/div\x3e\r\n \x3c/div\x3e\r\n\x3c/div\x3e'}});
define("esri/dijit/SizeInfoSlider","../kernel ../numberUtils ../dijit/RendererSlider ../dijit/RendererSlider/sliderUtils ../Color dijit/_TemplatedMixin dijit/_WidgetBase dojo/_base/array dojo/_base/declare dojo/_base/lang dojo/debounce dojo/dom-style dojo/Evented dojo/has dojo/dom-construct dojo/dom-class dojox/gfx dojo/text!./SizeInfoSlider/templates/SizeInfoSlider.html".split(" "),function(p,q,r,k,m,l,t,u,v,g,n,d,w,x,y,z,h,A){l=v([t,l,w],{declaredClass:"esri.dijit.SizeInfoSlider",baseClass:"esriSizeInfoSlider",
templateString:A,values:null,minValue:null,maxValue:null,minSize:null,maxSize:null,histogram:null,statistics:!1,zoomOptions:null,showHistogram:!0,showStatistics:!0,showLabels:!0,showTicks:!0,showHandles:!0,histogramWidth:100,rampWidth:26,symbolWidth:50,_rampNode:null,_sliderHeight:null,_barsGroup:null,_updateTimer:null,_forceMinValue:null,_forceMaxValue:null,_isRampFlipped:!1,constructor:function(a,b){b&&(void 0!==a.minValue&&this.set("_forceMinValue",a.minValue),void 0!==a.maxValue&&this.set("_forceMaxValue",
a.maxValue),this._css={handlerTickSize:"esri-handler-tick-size"},this._updateTimeout=n(this._updateTimeout,0),this._attachSymbols=n(this._attachSymbols,0))},postCreate:function(){this.inherited(arguments);this._setupDataDefaults()},startup:function(){this.inherited(arguments);this._slider=new r({type:"SizeInfoSlider",values:this.values,isDate:this.isDate,minimum:this.zoomOptions?this.zoomOptions.minSliderValue:this.minValue,maximum:this.zoomOptions?this.zoomOptions.maxSliderValue:this.maxValue,_minZoomLabel:this.zoomOptions?
this.minValue:null,_maxZoomLabel:this.zoomOptions?this.maxValue:null,_isZoomed:this.zoomOptions?!0:!1,showLabels:this.showLabels,showTicks:this.showTicks,showHandles:this.showHandles},this._sliderNode);this._slider.startup();this._rampNode=this._slider._sliderAreaRight;this._sliderHeight=d.get(this._rampNode,"height")||155;this._createSVGSurfaces();this._slider.on("slide",g.hitch(this,function(a){this._fillRamp(a.values)}));this._slider.on("change",g.hitch(this,function(a){this.sizeInfo.minDataValue=
a.values[0];this.sizeInfo.maxDataValue=a.values[1];this.set("values",[this.sizeInfo.minDataValue,this.sizeInfo.maxDataValue]);this._fillRamp();this.emit("change",g.clone(this.sizeInfo))}));this._slider.on("handle-value-change",g.hitch(this,function(a){this.set("values",a.values);this.sizeInfo.minDataValue=a.values[0];this.sizeInfo.maxDataValue=a.values[1];this._updateRendererSlider();this.emit("handle-value-change",g.clone(this.sizeInfo))}));this._slider.on("data-value-change",g.hitch(this,function(a){this.set({minValue:a.min,
maxValue:a.max});this._updateRendererSlider();this.emit("data-value-change",{minValue:a.min,maxValue:a.max,sizeInfo:g.clone(this.sizeInfo)})}));this._slider.on("stop",g.hitch(this,function(){this.emit("handle-value-change",g.clone(this.sizeInfo))}));this._slider.on("zoom-out",g.hitch(this,function(a){this.set("zoomOptions",null)}));this.statistics&&this.showStatistics&&this._generateStatistics();this.showHistogram&&(this.histogram||this.zoomOptions&&this.zoomOptions.histogram)&&this._generateHistogram();
this.watch("minValue",this._updateTimeout);this.watch("maxValue",this._updateTimeout);this.watch("symbol",this._updateTimeout);this.watch("sizeInfo",this._updateTimeout);this.watch("minSize",this._updateTimeout);this.watch("maxSize",this._updateTimeout);this.watch("statistics",this._updateTimeout);this.watch("histogram",this._updateTimeout);this.watch("zoomOptions",this._updateTimeout);this.watch("showHistogram",this._toggleHistogram);this.watch("zoomOptions",this._zoomEventHandler)},destroy:function(){this.inherited(arguments);
this._slider&&this._slider.destroy();this._avgHandleObjs&&this._avgHandleObjs.avgHandleTooltip&&this._avgHandleObjs.avgHandleTooltip.destroy();this.countTooltips&&u.forEach(this.countTooltips,function(a){a.destroy()})},_updateTimeout:function(){this._updateRendererSlider()},_updateRendererSlider:function(){this.set({minSize:this.sizeInfo.minSize,maxSize:this.sizeInfo.maxSize,values:[this.sizeInfo.minDataValue,this.sizeInfo.maxDataValue]});this._isRampFlipped=this.minSize>this.maxSize||this.minSize.stops&&
this.minSize.stops[0]&&this.maxSize.stops&&this.maxSize.stops[0]&&this.maxSize.stops[0].size<this.minSize.stops[0].size;null!==this.zoomOptions&&!1!==this.zoomOptions?(this.toggleSliderBottom=this.zoomOptions.minSliderValue>this.minValue,this.toggleSliderTop=this.zoomOptions.maxSliderValue<this.maxValue,this._slider.set({minimum:this.zoomOptions.minSliderValue,maximum:this.zoomOptions.maxSliderValue,_minZoomLabel:this.minValue,_maxZoomLabel:this.maxValue,_isZoomed:!0})):this._slider.set({minimum:this.minValue,
maximum:this.maxValue,_minZoomLabel:null,_maxZoomLabel:null,_isZoomed:!1});this._slider.set("values",this.values);this._slider._reset();this._slider._updateRoundedLabels();this._slider._generateMoveables();this._clearRect();this._createSVGSurfaces();this.statistics&&this.showStatistics&&this._generateStatistics();this.showHistogram&&(this.histogram||this.zoomOptions&&this.zoomOptions.histogram)&&this._generateHistogram()},_zoomEventHandler:function(){this.emit("zoomed",!!this.zoomOptions)},_setupDataDefaults:function(){this.set({minSize:this.sizeInfo.minSize,
maxSize:this.sizeInfo.maxSize});this._isRampFlipped=this.minSize>this.maxSize||this.minSize.stops&&this.minSize.stops[0]&&this.maxSize.stops&&this.maxSize.stops[0]&&this.maxSize.stops[0].size<this.minSize.stops[0].size;this.statistics?this.set({minValue:this.statistics.min,maxValue:this.statistics.max}):this.set({minValue:0,maxValue:100});null!==this._forceMinValue&&this.set("minValue",this._forceMinValue);null!==this._forceMaxValue&&this.set("maxValue",this._forceMaxValue);null!==this.zoomOptions&&
!1!==this.zoomOptions&&(this.toggleSliderBottom=this.zoomOptions.minSliderValue>this.minValue,this.toggleSliderTop=this.zoomOptions.maxSliderValue<this.maxValue);null===this.sizeInfo.minDataValue&&null===this.sizeInfo.maxDataValue||0===this.sizeInfo.minDataValue&&0===this.sizeInfo.maxDataValue?null===this.minValue&&null===this.maxValue&&this.set({minValue:0,maxValue:100,values:[20,80]}):this.minValue===this.maxValue?0===this.minValue?this.set({maxValue:100,values:[20,80]}):null===this.minValue?this.set({minValue:0,
maxValue:100,values:[20,80]}):this.set({minValue:0,maxValue:2*this.minValue,values:[this.maxValue/5,this.maxValue/5*4]}):this.set("values",[this.sizeInfo.minDataValue,this.sizeInfo.maxDataValue]);null===this.minValue&&this.set("minValue",0);null===this.maxValue&&this.set("maxValue",100)},_createSVGSurfaces:function(){this._proportionalSymbolSurface=h.createSurface(this._rampNode,this.rampWidth,this._sliderHeight);this._surfaceRect=this._proportionalSymbolSurface.createRect({width:this.rampWidth,height:this._sliderHeight});
this._histogramSurface=k.generateHistogramSurface(this._rampNode,this.histogramWidth,this._sliderHeight,this.rampWidth);this._fillRamp();this._attachSymbols()},_attachSymbols:function(){var a=this._isRampFlipped?this.minSize:this.maxSize;this._attachSymbol(this._slider.moveables[0],this._isRampFlipped?this.maxSize:this.minSize);this._attachSymbol(this._slider.moveables[1],a)},_attachSymbol:function(a,b){a._symbol||(a._symbol=y.create("div",{style:"position: absolute; left: 10px;"},a));var e=d.get(a._handleContainer,
"height"),c=a._symbol,f=this.symbol;f&&"simplelinesymbol"==f.type?(f=b===this.minSize?5:13,this._generateLineSymbol(a,f,e)):(f=b===this.minSize?12:48,this._generateCircleSymbol(c,f,e));return c},_generateLineSymbol:function(a,b,e){var c=a._symbol;z.add(a._tick,this._css.handlerTickSize);d.set(c,"top",e/2-b+"px");d.set(c,"height",2*b+"px");d.set(c,"width",b-4+"px");c.innerHTML="";a=h.createSurface(c);a.rawNode.style.position="absolute";a.rawNode.style.top=1===b?"1px":b/2+"px";this.isLeftToRight()||
(a.rawNode.style.left="-45px");a.setDimensions(this.rampWidth,b);a.createRect({width:this.rampWidth,height:b}).setFill(new m([0,121,193,.8]));return a},_generateCircleSymbol:function(a,b,e){var c=b/2;b=12===b?!0:!1;d.set(a,"top",e/2-(c+1)+"px");d.set(a,"height",2*(c+1)+"px");d.set(a,"width",b?2*(c+1):c+"px");d.set(a,"left",b?"8px":"10px");a.innerHTML="";a=h.createSurface(a);a.rawNode.style.position="absolute";this.isLeftToRight()||(a.rawNode.style.left="-45px");b?(a.setDimensions(2*(c+1),2*(c+1)),
a.createCircle({cx:7,cy:c+1,r:c}).setFill(new m([0,121,193,.8])).setStroke("#fff")):(a.setDimensions(c+1,2*(c+1)),a.createCircle({cx:0,cy:c+1,r:c}).setFill(new m([0,121,193,.8])).setStroke("#fff"));return a},_fillRamp:function(a){var b=this._slider,e=this._sliderHeight,c=Math.round(e-((a?a[0]:b.values[0])-b.minimum)/(b.maximum-b.minimum)*e);a=Math.round(e-((a?a[1]:b.values[1])-b.minimum)/(b.maximum-b.minimum)*e);var b=this.rampWidth,f={color:"#fff",width:3};this._proportionalSymbolSurface.clear();
this._isRampFlipped?this._proportionalSymbolSurface.createPath().moveTo(10,0).lineTo(10,a).lineTo(b,c).lineTo(b,e).lineTo(0,e).lineTo(0,0).closePath().setFill("#9a9a9a"):this._proportionalSymbolSurface.createPath().moveTo(b,0).lineTo(b,a).lineTo(10,c).lineTo(10,e).lineTo(0,e).lineTo(0,0).closePath().setFill("#9a9a9a");d.set(this._proportionalSymbolSurface.rawNode,"overflow","visible");d.set(this._proportionalSymbolSurface.rawNode,"background-color","#d9d9d9");null!==this.zoomOptions&&!1!==this.zoomOptions&&
(this.toggleSliderBottom&&this.toggleSliderTop?(this._proportionalSymbolSurface.createPath("M0,1 L6.25,-1 L12.5,1 L18.75,-1 L25,1").setStroke(f).setTransform(h.matrix.translate(0,5)),this._proportionalSymbolSurface.createPath("M0,1 L6.25,-1 L12.5,1 L18.75,-1 L25,1").setStroke(f).setTransform(h.matrix.translate(0,195))):this.toggleSliderBottom?this._proportionalSymbolSurface.createPath("M0,1 L6.25,-1 L12.5,1 L18.75,-1 L25,1").setStroke(f).setTransform(h.matrix.translate(0,195)):this.toggleSliderTop&&
this._proportionalSymbolSurface.createPath("M0,1 L6.25,-1 L12.5,1 L18.75,-1 L25,1").setStroke(f).setTransform(h.matrix.translate(0,5)))},_clearRect:function(){this._proportionalSymbolSurface.destroy();this._histogramSurface.destroy()},_showHistogram:function(){this.histogram||this.zoomOptions&&this.zoomOptions.histogram?this._generateHistogram():this._barsGroup&&(this._barsGroup.destroy(),this._barsGroup=null)},_toggleHistogram:function(){this.showHistogram?(d.set(this._barsGroup.rawNode,"display",
"inline-block"),this._showHistogram()):d.set(this._barsGroup.rawNode,"display","none")},_generateHistogram:function(){var a=this.zoomOptions&&this.zoomOptions.histogram?this.zoomOptions.histogram:this.histogram;this._barsGroup=k.generateHistogram(this._histogramSurface,a,this.histogramWidth,this.rampWidth,this.isLeftToRight());this.countTooltips=k.generateCountTooltips(a,this._barsGroup)},_generateStatistics:function(){if(!(2>this.statistics.count||isNaN(this.statistics.avg))){var a,b=this.statistics;
a=this._slider;var e=this.zoomOptions||null,c=k.getPrecision(this.maxValue),f,d;b.min===b.max&&b.min===b.avg?(f=0,d=2*b.avg):(f=b.min,d=b.max);if(f!==a.minimum||d!==a.maximum)f=a.minimum,d=a.maximum;e&&(f=e.minSliderValue,d=e.maxSliderValue);a=this._sliderHeight*(d-b.avg)/(d-f);b=q.round([b.avg,d,f])[0];this._avgHandleObjs=k.generateAvgLine(this._histogramSurface,b,a,c,this.isLeftToRight(),this.isDate)}}});x("extend-esri")&&g.setObject("dijit.SizeInfoSlider",l,p);return l}); | wanglongbiao/webapp-tools | Highlander/ship-gis/src/main/webapp/js/arcgis_js_api/library/3.22/esri/dijit/SizeInfoSlider.js | JavaScript | apache-2.0 | 11,917 |
var classorg_1_1onosproject_1_1ovsdb_1_1rfc_1_1table_1_1Manager =
[
[ "ManagerColumn", "enumorg_1_1onosproject_1_1ovsdb_1_1rfc_1_1table_1_1Manager_1_1ManagerColumn.html", "enumorg_1_1onosproject_1_1ovsdb_1_1rfc_1_1table_1_1Manager_1_1ManagerColumn" ],
[ "Manager", "classorg_1_1onosproject_1_1ovsdb_1_1rfc_1_1table_1_1Manager.html#ab0d37b97fb5f9db1e02d196f310c30be", null ],
[ "getConnectionModeColumn", "classorg_1_1onosproject_1_1ovsdb_1_1rfc_1_1table_1_1Manager.html#ac39c4b713393981eecae4c5bcf967e2b", null ],
[ "getExternalIdsColumn", "classorg_1_1onosproject_1_1ovsdb_1_1rfc_1_1table_1_1Manager.html#aaccf25dffd2baf37a7e6fa37d143af47", null ],
[ "getInactivityProbeColumn", "classorg_1_1onosproject_1_1ovsdb_1_1rfc_1_1table_1_1Manager.html#ab36e2ab802e5d6fd5e4d100981358e46", null ],
[ "getIsConnectedColumn", "classorg_1_1onosproject_1_1ovsdb_1_1rfc_1_1table_1_1Manager.html#a548c6d7d3f1f8312af6bc01cd6ee9e07", null ],
[ "getMaxBackoffColumn", "classorg_1_1onosproject_1_1ovsdb_1_1rfc_1_1table_1_1Manager.html#a223d1d68efb7454f756001b07e55f2fd", null ],
[ "getOtherConfigColumn", "classorg_1_1onosproject_1_1ovsdb_1_1rfc_1_1table_1_1Manager.html#aeda9a5e542fe290ef030f665687aa3cd", null ],
[ "getStatusColumn", "classorg_1_1onosproject_1_1ovsdb_1_1rfc_1_1table_1_1Manager.html#a3a44b3f71277cfef28a1099e3ae4a989", null ],
[ "getTargetColumn", "classorg_1_1onosproject_1_1ovsdb_1_1rfc_1_1table_1_1Manager.html#a9d31245aadd8df9dee10af20333e626c", null ],
[ "setConnectionMode", "classorg_1_1onosproject_1_1ovsdb_1_1rfc_1_1table_1_1Manager.html#ad5f8da527c329304bf5cb28d9fe2a20d", null ],
[ "setExternalIds", "classorg_1_1onosproject_1_1ovsdb_1_1rfc_1_1table_1_1Manager.html#a9b155703a2fce3a0ea2b461db6be6e85", null ],
[ "setInactivityProbe", "classorg_1_1onosproject_1_1ovsdb_1_1rfc_1_1table_1_1Manager.html#a474bd5d0210293466da8aa4a1e54db50", null ],
[ "setIsConnected", "classorg_1_1onosproject_1_1ovsdb_1_1rfc_1_1table_1_1Manager.html#a26e1a7adba7a9ec347f6367ab2188ed9", null ],
[ "setMaxBackoff", "classorg_1_1onosproject_1_1ovsdb_1_1rfc_1_1table_1_1Manager.html#a66d3e38cadf704119c75f13b0cebd74e", null ],
[ "setOtherConfig", "classorg_1_1onosproject_1_1ovsdb_1_1rfc_1_1table_1_1Manager.html#a7a350f1b36afa3cf806391a1bedd5926", null ],
[ "setStatus", "classorg_1_1onosproject_1_1ovsdb_1_1rfc_1_1table_1_1Manager.html#a440371bfad1f7b3307d4c7f5274d888a", null ],
[ "setTarget", "classorg_1_1onosproject_1_1ovsdb_1_1rfc_1_1table_1_1Manager.html#a56473d0030778d0ba83aa9c9e376e47e", null ]
]; | onosfw/apis | onos/apis/classorg_1_1onosproject_1_1ovsdb_1_1rfc_1_1table_1_1Manager.js | JavaScript | apache-2.0 | 2,568 |
AngryCat = Backbone.Model.extend({
defaults: {
vote: 0
}
});
| gt3389b/simpleMarionetteMocha | assets/js/models/angrycat.js | JavaScript | apache-2.0 | 73 |
exports.up = function(knex, Promise) {
return knex.schema.createTable('projects', (table) => {
table.increments('id').primary()
table.string('name')
table.string('github_link')
table.string('deployment_link')
})
}
exports.down = function(knex, Promise) {
return knex.schema.dropTable('projects')
}
| rene-justin-dado/rj-dev-back-end | migrations/20161013151729_projects.js | JavaScript | apache-2.0 | 322 |
(function() {
'use strict';
angular
.module('netdelsolutionApp')
.factory('LogsService', LogsService);
LogsService.$inject = ['$resource'];
function LogsService ($resource) {
var service = $resource('management/logs', {}, {
'findAll': { method: 'GET', isArray: true},
'changeLevel': { method: 'PUT'}
});
return service;
}
})();
| bhav0904/netDelSolution | src/main/webapp/app/admin/logs/logs.service.js | JavaScript | apache-2.0 | 416 |
/*!
* ${copyright}
*/
// Provides class sap.ui.model.odata.ODataListBinding
sap.ui.define([
'jquery.sap.global',
'sap/ui/model/ChangeReason', 'sap/ui/model/Filter', 'sap/ui/model/FilterType', 'sap/ui/model/ListBinding', 'sap/ui/model/Sorter',
'./ODataUtils', './CountMode'
], function(jQuery, ChangeReason, Filter, FilterType, ListBinding, Sorter, ODataUtils, CountMode) {
"use strict";
/**
* @class
* List binding implementation for oData format.
*
* @param {sap.ui.model.odata.ODataModel} oModel Model that this list binding belongs to
* @param {string} sPath Path into the model data, relative to the given <code>oContext</code>
* @param {sap.ui.model.Context} oContext Context that the <code>sPath</code> is based on
* @param {array} [aSorters] Initial sort order (can be either a sorter or an array of sorters)
* @param {array} [aFilters] Predefined filter/s (can be either a filter or an array of filters)
* @param {object} [mParameters] A map which contains additional parameters for the binding
* @param {string} [mParameters.expand] Value for the OData <code>$expand</code> query parameter which should be included in the request
* @param {string} [mParameters.select] Value for the OData <code>$select</code> query parameter which should be included in the request
* @param {map} [mParameters.custom] An optional map of custom query parameters. Custom parameters must not start with <code>$</code>
* @param {sap.ui.model.odata.CountMode} [mParameters.countMode] Defines the count mode of this binding;
* if not specified, the default count mode of the <code>oModel</code> is applied
*
* @public
* @alias sap.ui.model.odata.ODataListBinding
* @extends sap.ui.model.ListBinding
*/
var ODataListBinding = ListBinding.extend("sap.ui.model.odata.ODataListBinding", /** @lends sap.ui.model.odata.ODataListBinding.prototype */ {
constructor : function(oModel, sPath, oContext, aSorters, aFilters, mParameters) {
ListBinding.apply(this, arguments);
this.sFilterParams = null;
this.sSortParams = null;
this.sRangeParams = null;
this.sCustomParams = this.oModel.createCustomParams(this.mParameters);
this.iStartIndex = 0;
this.bPendingChange = false;
this.aKeys = [];
this.bInitial = true;
this.sCountMode = (mParameters && mParameters.countMode) || this.oModel.sDefaultCountMode;
this.bRefresh = false;
this.bNeedsUpdate = false;
this.bDataAvailable = false;
this.bIgnoreSuspend = false;
// check filter integrity
this.oModel.checkFilterOperation(this.aApplicationFilters);
// load the entity type for the collection only once and not e.g. every time when filtering
if (!this.oModel.getServiceMetadata()) {
var that = this,
fnCallback = function(oEvent) {
that.bInitial = false;
that._initSortersFilters();
that.oModel.detachMetadataLoaded(fnCallback);
};
this.oModel.attachMetadataLoaded(this, fnCallback);
} else {
this.bInitial = false;
this._initSortersFilters();
}
// if nested list is already available and no filters or sorters are set,
// use the data and don't send additional requests
// TODO: what if nested list is not complete, because it was too large?
var oRef = this.oModel._getObject(this.sPath, this.oContext);
this.aExpandRefs = oRef;
if (Array.isArray(oRef) && !aSorters && !aFilters) {
this.aKeys = oRef;
this.iLength = oRef.length;
this.bLengthFinal = true;
this.bDataAvailable = true;
} else if (oRef === null && this.oModel.resolve(this.sPath, this.oContext)) { // means that expanded data has no data available e.g. for 0..n relations
this.aKeys = [];
this.iLength = 0;
this.bLengthFinal = true;
this.bDataAvailable = true;
} else {
// call getLength when metadata is already loaded or don't do anything
// if the metadata gets loaded it will call a refresh on all bindings
if (this.oModel.getServiceMetadata()) {
this.resetData();
}
}
}
});
/**
* Return contexts for the list
*
* @param {int} [iStartIndex=0] the start index of the requested contexts
* @param {int} [iLength] the requested amount of contexts
* @param {int} [iThreshold=0]
* @return {sap.ui.model.Context[]} the array of contexts for each row of the bound list
* @protected
*/
ODataListBinding.prototype.getContexts = function(iStartIndex, iLength, iThreshold) {
if (this.bInitial) {
return [];
}
this.iLastLength = iLength;
this.iLastStartIndex = iStartIndex;
this.iLastThreshold = iThreshold;
// Set default values if startindex, threshold or length are not defined
if (!iStartIndex) {
iStartIndex = 0;
}
if (!iLength) {
iLength = this.oModel.iSizeLimit;
if (this.bLengthFinal && this.iLength < iLength) {
iLength = this.iLength;
}
}
if (!iThreshold) {
iThreshold = 0;
}
var bLoadContexts = true,
aContexts = this._getContexts(iStartIndex, iLength),
oContextData = {},
oSection;
oSection = this.calculateSection(iStartIndex, iLength, iThreshold, aContexts);
bLoadContexts = aContexts.length != iLength && !(this.bLengthFinal && aContexts.length >= this.iLength - iStartIndex);
// check if metadata are already available
if (this.oModel.getServiceMetadata()) {
// If rows are missing send a request
if (!this.bPendingRequest && oSection.length > 0 && (bLoadContexts || iLength < oSection.length)) {
this.loadData(oSection.startIndex, oSection.length);
aContexts.dataRequested = true;
}
}
if (this.bRefresh) {
// if refreshing and length is 0, pretend a request to be fired to make a refresh with
// with preceding $count request look like a request with $inlinecount=allpages
if (this.bLengthFinal && this.iLength == 0) {
this.loadData(oSection.startIndex, oSection.length, true);
aContexts.dataRequested = true;
}
this.bRefresh = false;
} else {
// Do not create context data and diff in case of refresh, only if real data has been received
// The current behaviour is wrong and makes diff detection useless for OData in case of refresh
for (var i = 0; i < aContexts.length; i++) {
oContextData[aContexts[i].getPath()] = aContexts[i].getObject();
}
if (this.bUseExtendedChangeDetection) {
//Check diff
if (this.aLastContexts && iStartIndex < this.iLastEndIndex) {
var that = this;
var aDiff = jQuery.sap.arrayDiff(this.aLastContexts, aContexts, function(oOldContext, oNewContext) {
return jQuery.sap.equal(
oOldContext && that.oLastContextData && that.oLastContextData[oOldContext.getPath()],
oNewContext && oContextData && oContextData[oNewContext.getPath()]
);
}, true);
aContexts.diff = aDiff;
}
}
this.iLastEndIndex = iStartIndex + iLength;
this.aLastContexts = aContexts.slice(0);
this.oLastContextData = jQuery.sap.extend(true, {}, oContextData);
}
return aContexts;
};
ODataListBinding.prototype.getCurrentContexts = function() {
return this.aLastContexts || [];
};
/**
* Return contexts for the list
*
* @param {int} [iStartIndex=0] the start index of the requested contexts
* @param {int} [iLength] the requested amount of contexts
*
* @return {Array} the contexts array
* @private
*/
ODataListBinding.prototype._getContexts = function(iStartIndex, iLength) {
var aContexts = [],
oContext,
sKey;
if (!iStartIndex) {
iStartIndex = 0;
}
if (!iLength) {
iLength = this.oModel.iSizeLimit;
if (this.bLengthFinal && this.iLength < iLength) {
iLength = this.iLength;
}
}
// Loop through known data and check whether we already have all rows loaded
for (var i = iStartIndex; i < iStartIndex + iLength; i++) {
sKey = this.aKeys[i];
if (!sKey) {
break;
}
oContext = this.oModel.getContext('/' + sKey);
aContexts.push(oContext);
}
return aContexts;
};
/*
* @private
*/
ODataListBinding.prototype.calculateSection = function(iStartIndex, iLength, iThreshold, aContexts) {
var iSectionLength,
iSectionStartIndex,
iPreloadedSubsequentIndex,
iPreloadedPreviousIndex,
iRemainingEntries,
oSection = {},
sKey;
iSectionStartIndex = iStartIndex;
iSectionLength = 0;
// check which data exists before startindex; If all necessary data is loaded iPreloadedPreviousIndex stays undefined
for (var i = iStartIndex; i >= Math.max(iStartIndex - iThreshold,0); i--) {
sKey = this.aKeys[i];
if (!sKey) {
iPreloadedPreviousIndex = i + 1;
break;
}
}
// check which data is already loaded after startindex; If all necessary data is loaded iPreloadedSubsequentIndex stays undefined
for (var j = iStartIndex + iLength; j < iStartIndex + iLength + iThreshold; j++) {
sKey = this.aKeys[j];
if (!sKey) {
iPreloadedSubsequentIndex = j;
break;
}
}
// calculate previous remaining entries
iRemainingEntries = iStartIndex - iPreloadedPreviousIndex;
if (iPreloadedPreviousIndex && iStartIndex > iThreshold && iRemainingEntries < iThreshold) {
if (aContexts.length != iLength) {
iSectionStartIndex = iStartIndex - iThreshold;
} else {
iSectionStartIndex = iPreloadedPreviousIndex - iThreshold;
}
iSectionLength = iThreshold;
}
// prevent iSectionStartIndex to become negative
iSectionStartIndex = Math.max(iSectionStartIndex, 0);
// No negative preload needed; move startindex if we already have some data
if (iSectionStartIndex == iStartIndex) {
iSectionStartIndex += aContexts.length;
}
//read the rest of the requested data
if (aContexts.length != iLength) {
iSectionLength += iLength - aContexts.length;
}
//calculate subsequent remaining entries
iRemainingEntries = iPreloadedSubsequentIndex - iStartIndex - iLength;
if (iRemainingEntries == 0) {
iSectionLength += iThreshold;
}
if (iPreloadedSubsequentIndex && iRemainingEntries < iThreshold && iRemainingEntries > 0) {
//check if we need to load previous entries; If not we can move the startindex
if (iSectionStartIndex > iStartIndex) {
iSectionStartIndex = iPreloadedSubsequentIndex;
iSectionLength += iThreshold;
}
}
//check final length and adapt sectionLength if needed.
if (this.bLengthFinal && this.iLength < (iSectionLength + iSectionStartIndex)) {
iSectionLength = this.iLength - iSectionStartIndex;
}
oSection.startIndex = iSectionStartIndex;
oSection.length = iSectionLength;
return oSection;
};
/**
* Setter for context
* @param {Object} oContext the new context object
*/
ODataListBinding.prototype.setContext = function(oContext) {
if (this.oContext != oContext) {
this.oContext = oContext;
if (this.isRelative()) {
// get new entity type with new context and init filters now correctly
this._initSortersFilters();
if (!this.bInitial) {
// if nested list is already available, use the data and don't send additional requests
// TODO: what if nested list is not complete, because it was too large?
var oRef = this.oModel._getObject(this.sPath, this.oContext);
this.aExpandRefs = oRef;
if (Array.isArray(oRef) && !this.aSorters.length > 0 && !this.aFilters.length > 0) {
this.aKeys = oRef;
this.iLength = oRef.length;
this.bLengthFinal = true;
this._fireChange({ reason: ChangeReason.Context });
} else if (!this.oModel.resolve(this.sPath, this.oContext) || oRef === null){
// if path does not resolve, or data is known to be null (e.g. expanded list)
this.aKeys = [];
this.iLength = 0;
this.bLengthFinal = true;
this._fireChange({ reason: ChangeReason.Context });
} else {
this.refresh();
}
}
}
}
};
/**
* Get a download URL with the specified format considering the
* sort/filter/custom parameters.
*
* @param {string} sFormat Value for the $format Parameter
* @return {string} URL which can be used for downloading
* @since 1.24
* @public
*/
ODataListBinding.prototype.getDownloadUrl = function(sFormat) {
var aParams = [],
sPath;
if (sFormat) {
aParams.push("$format=" + encodeURIComponent(sFormat));
}
if (this.sSortParams) {
aParams.push(this.sSortParams);
}
if (this.sFilterParams) {
aParams.push(this.sFilterParams);
}
if (this.sCustomParams) {
aParams.push(this.sCustomParams);
}
sPath = this.oModel.resolve(this.sPath,this.oContext);
if (sPath) {
return this.oModel._createRequestUrl(sPath, null, aParams);
}
};
/**
* Load list data from the server
*/
ODataListBinding.prototype.loadData = function(iStartIndex, iLength, bPretend) {
var that = this,
bInlineCountRequested = false;
// create range parameters and store start index for sort/filter requests
if (iStartIndex || iLength) {
this.sRangeParams = "$skip=" + iStartIndex + "&$top=" + iLength;
this.iStartIndex = iStartIndex;
} else {
iStartIndex = this.iStartIndex;
}
// create the request url
var aParams = [];
if (this.sRangeParams) {
aParams.push(this.sRangeParams);
}
if (this.sSortParams) {
aParams.push(this.sSortParams);
}
if (this.sFilterParams) {
aParams.push(this.sFilterParams);
}
if (this.sCustomParams) {
aParams.push(this.sCustomParams);
}
if (!this.bLengthFinal &&
(this.sCountMode == CountMode.Inline ||
this.sCountMode == CountMode.Both)) {
aParams.push("$inlinecount=allpages");
bInlineCountRequested = true;
}
function fnSuccess(oData) {
// Collecting contexts
jQuery.each(oData.results, function(i, entry) {
that.aKeys[iStartIndex + i] = that.oModel._getKey(entry);
});
// update iLength (only when the inline count was requested and is available)
if (bInlineCountRequested && oData.__count) {
that.iLength = parseInt(oData.__count, 10);
that.bLengthFinal = true;
}
// if we got data and the results + startindex is larger than the
// length we just apply this value to the length and add the requested
// length again to enable paging/scrolling
if (that.iLength < iStartIndex + oData.results.length) {
that.iLength = iStartIndex + oData.results.length;
that.bLengthFinal = false;
}
// if less entries are returned than have been requested
// set length accordingly
if (oData.results.length < iLength || iLength === undefined) {
that.iLength = iStartIndex + oData.results.length;
that.bLengthFinal = true;
}
// check if there are any results at all...
if (iStartIndex == 0 && oData.results.length == 0) {
that.iLength = 0;
that.bLengthFinal = true;
}
that.oRequestHandle = null;
that.bPendingRequest = false;
// If request is originating from this binding, change must be fired afterwards
that.bNeedsUpdate = true;
that.bIgnoreSuspend = true;
}
function fnCompleted(oData) {
that.fireDataReceived({data: oData});
}
function fnError(oError, bAborted) {
that.oRequestHandle = null;
that.bPendingRequest = false;
if (!bAborted) {
// reset data and trigger update
that.aKeys = [];
that.iLength = 0;
that.bLengthFinal = true;
that.bDataAvailable = true;
that._fireChange({reason: ChangeReason.Change});
}
that.fireDataReceived();
}
function fnUpdateHandle(oHandle) {
that.oRequestHandle = oHandle;
}
var sPath = this.sPath,
oContext = this.oContext;
if (this.isRelative()) {
sPath = this.oModel.resolve(sPath,oContext);
}
if (sPath) {
if (bPretend) {
// Pretend to send a request by firing the appropriate events
var sUrl = this.oModel._createRequestUrl(sPath, null, aParams);
this.fireDataRequested();
this.oModel.fireRequestSent({url: sUrl, method: "GET", async: true});
setTimeout(function() {
// If request is originating from this binding, change must be fired afterwards
that.bNeedsUpdate = true;
that.checkUpdate();
that.oModel.fireRequestCompleted({url: sUrl, method: "GET", async: true, success: true});
that.fireDataReceived({data: {}});
}, 0);
} else {
// Execute the request and use the metadata if available
this.bPendingRequest = true;
this.fireDataRequested();
this.oModel._loadData(sPath, aParams, fnSuccess, fnError, false, fnUpdateHandle, fnCompleted);
}
}
};
ODataListBinding.prototype.getLength = function() {
// If length is not final and larger than zero, add some additional length to enable
// scrolling/paging for controls that only do this if more items are available
if (this.bLengthFinal || this.iLength == 0) {
return this.iLength;
} else {
var iAdditionalLength = this.iLastThreshold || this.iLastLength || 10;
return this.iLength + iAdditionalLength;
}
};
ODataListBinding.prototype.isLengthFinal = function() {
return this.bLengthFinal;
};
/**
* Return the length of the list
*
* @return {int} the length
*/
ODataListBinding.prototype._getLength = function() {
var that = this;
// create a request object for the data request
var aParams = [];
if (this.sFilterParams) {
aParams.push(this.sFilterParams);
}
// use only custom params for count and not expand,select params
if (this.mParameters && this.mParameters.custom) {
var oCust = { custom: {}};
jQuery.each(this.mParameters.custom, function (sParam, oValue){
oCust.custom[sParam] = oValue;
});
aParams.push(this.oModel.createCustomParams(oCust));
}
function _handleSuccess(oData) {
that.iLength = parseInt(oData, 10);
that.bLengthFinal = true;
}
function _handleError(oError) {
var sErrorMsg = "Request for $count failed: " + oError.message;
if (oError.response) {
sErrorMsg += ", " + oError.response.statusCode + ", " + oError.response.statusText + ", " + oError.response.body;
}
jQuery.sap.log.warning(sErrorMsg);
}
// Use context and check for relative binding
var sPath = this.oModel.resolve(this.sPath, this.oContext);
// Only send request, if path is defined
if (sPath) {
var sUrl = this.oModel._createRequestUrl(sPath + "/$count", null, aParams);
var oRequest = this.oModel._createRequest(sUrl, "GET", false);
// count needs other accept header
oRequest.headers["Accept"] = "text/plain, */*;q=0.5";
// execute the request and use the metadata if available
// (since $count requests are synchronous we skip the withCredentials here)
this.oModel._request(oRequest, _handleSuccess, _handleError, undefined, undefined, this.oModel.getServiceMetadata());
}
};
/**
* Refreshes the binding, check whether the model data has been changed and fire change event
* if this is the case. For server side models this should refetch the data from the server.
* To update a control, even if no data has been changed, e.g. to reset a control after failed
* validation, please use the parameter bForceUpdate.
*
* @param {boolean} [bForceUpdate] Update the bound control even if no data has been changed
* @public
*/
ODataListBinding.prototype.refresh = function(bForceUpdate, mChangedEntities, mEntityTypes) {
var bChangeDetected = false;
if (!bForceUpdate) {
if (mEntityTypes) {
var sResolvedPath = this.oModel.resolve(this.sPath, this.oContext);
var oEntityType = this.oModel.oMetadata._getEntityTypeByPath(sResolvedPath);
if (oEntityType && (oEntityType.entityType in mEntityTypes)) {
bChangeDetected = true;
}
}
if (mChangedEntities && !bChangeDetected) {
jQuery.each(this.aKeys, function(i, sKey) {
if (sKey in mChangedEntities) {
bChangeDetected = true;
return false;
}
});
}
if (!mChangedEntities && !mEntityTypes) { // default
bChangeDetected = true;
}
}
if (bForceUpdate || bChangeDetected) {
this.abortPendingRequest();
this.resetData();
this._fireRefresh({reason: ChangeReason.Refresh});
}
};
/**
* fireRefresh
*/
ODataListBinding.prototype._fireRefresh = function(mArguments) {
if (this.oModel.resolve(this.sPath, this.oContext)) {
this.bRefresh = true;
this.fireEvent("refresh", mArguments);
}
};
/**
* Initialize binding. Fires a change if data is already available ($expand) or a refresh.
* If metadata is not yet available, do nothing, method will be called again when
* metadata is loaded.
*
* @public
*/
ODataListBinding.prototype.initialize = function() {
if (this.oModel.oMetadata.isLoaded()) {
if (this.bDataAvailable) {
this._fireChange({reason: ChangeReason.Change});
} else {
this._fireRefresh({reason: ChangeReason.Refresh});
}
}
};
/**
* Check whether this Binding would provide new values and in case it changed,
* inform interested parties about this.
*
* @param {boolean} bForceUpdate
* @param {object} mChangedEntities
*/
ODataListBinding.prototype.checkUpdate = function(bForceUpdate, mChangedEntities) {
var bChangeReason = this.sChangeReason ? this.sChangeReason : ChangeReason.Change,
bChangeDetected = false,
oLastData, oCurrentData,
that = this,
oRef,
bRefChanged;
if (this.bSuspended && !this.bIgnoreSuspend) {
return;
}
if (!bForceUpdate && !this.bNeedsUpdate) {
// check if data in listbinding contains data loaded via expand
// if yes and there was a change detected we:
// - set the new keys if there are no sortes/filters set
// - trigger a refresh if there are sorters/filters set
oRef = this.oModel._getObject(this.sPath, this.oContext);
bRefChanged = Array.isArray(oRef) && !jQuery.sap.equal(oRef,this.aExpandRefs);
this.aExpandRefs = oRef;
if (bRefChanged) {
if (this.aSorters.length > 0 || this.aFilters.length > 0) {
this.refresh();
return;
} else {
this.aKeys = oRef;
this.iLength = oRef.length;
this.bLengthFinal = true;
bChangeDetected = true;
}
} else if (mChangedEntities) {
jQuery.each(this.aKeys, function(i, sKey) {
if (sKey in mChangedEntities) {
bChangeDetected = true;
return false;
}
});
} else {
bChangeDetected = true;
}
if (bChangeDetected && this.aLastContexts) {
// Reset bChangeDetected and compare actual data of entries
bChangeDetected = false;
//Get contexts for visible area and compare with stored contexts
var aContexts = this._getContexts(this.iLastStartIndex, this.iLastLength, this.iLastThreshold);
if (this.aLastContexts.length != aContexts.length) {
bChangeDetected = true;
} else {
jQuery.each(this.aLastContexts, function(iIndex, oContext) {
oLastData = that.oLastContextData[oContext.getPath()];
oCurrentData = aContexts[iIndex].getObject();
// Compare whether last data is completely contained in current data
if (!jQuery.sap.equal(oLastData, oCurrentData, true)) {
bChangeDetected = true;
return false;
}
});
}
}
}
if (bForceUpdate || bChangeDetected || this.bNeedsUpdate) {
this.bNeedsUpdate = false;
this._fireChange({reason: bChangeReason});
}
this.sChangeReason = undefined;
this.bIgnoreSuspend = false;
};
/**
* Resets the current list data and length
*
* @private
*/
ODataListBinding.prototype.resetData = function() {
this.aKeys = [];
this.iLength = 0;
this.bLengthFinal = false;
this.sChangeReason = undefined;
this.bDataAvailable = false;
if (this.oModel.isCountSupported() &&
(this.sCountMode == CountMode.Request ||
this.sCountMode == CountMode.Both)) {
this._getLength();
}
};
/**
* Aborts the current pending request (if any)
*
* This can be called if we are sure that the data from the current request is no longer relevant,
* e.g. when filtering/sorting is triggered or the context is changed.
*
* @private
*/
ODataListBinding.prototype.abortPendingRequest = function() {
if (this.oRequestHandle) {
this.oRequestHandle.abort();
this.oRequestHandle = null;
this.bPendingRequest = false;
}
};
/**
* Sorts the list.
*
* @param {sap.ui.model.Sorter|Array} aSorters the Sorter or an array of sorter objects object which define the sort order
* @return {sap.ui.model.ListBinding} returns <code>this</code> to facilitate method chaining
* @public
*/
ODataListBinding.prototype.sort = function(aSorters, bReturnSuccess) {
var bSuccess = false;
if (!aSorters) {
aSorters = [];
}
if (aSorters instanceof Sorter) {
aSorters = [aSorters];
}
this.aSorters = aSorters;
this.createSortParams(aSorters);
if (!this.bInitial) {
// Only reset the keys, length usually doesn't change when sorting
this.aKeys = [];
this.abortPendingRequest();
this.sChangeReason = ChangeReason.Sort;
this._fireRefresh({reason : this.sChangeReason});
// TODO remove this if the sort event gets removed which is now deprecated
this._fireSort({sorter: aSorters});
bSuccess = true;
}
if (bReturnSuccess) {
return bSuccess;
} else {
return this;
}
};
ODataListBinding.prototype.createSortParams = function(aSorters) {
this.sSortParams = ODataUtils.createSortParams(aSorters);
};
/**
*
* Filters the list.
*
* When using sap.ui.model.Filter the filters are first grouped according to their binding path.
* All filters belonging to a group are combined with OR and after that the
* results of all groups are combined with AND.
* Usually this means, all filters applied to a single table column
* are combined with OR, while filters on different table columns are combined with AND.
* Please note that a custom filter function is not supported.
*
* @param {sap.ui.model.Filter[]|sap.ui.model.odata.Filter[]} aFilters Array of filter objects
* @param {sap.ui.model.FilterType} sFilterType Type of the filter which should be adjusted, if it is not given, the standard behaviour applies
* @return {sap.ui.model.ListBinding} returns <code>this</code> to facilitate method chaining
*
* @public
*/
ODataListBinding.prototype.filter = function(aFilters, sFilterType, bReturnSuccess) {
var bSuccess = false;
if (!aFilters) {
aFilters = [];
}
if (aFilters instanceof Filter) {
aFilters = [aFilters];
}
// check filter integrity
this.oModel.checkFilterOperation(aFilters);
if (sFilterType == FilterType.Application) {
this.aApplicationFilters = aFilters;
} else {
this.aFilters = aFilters;
}
if (!aFilters || !Array.isArray(aFilters) || aFilters.length == 0) {
this.aFilters = [];
}
//if no application-filters are present, or they are not in array form/empty array, init the filters with []
if (!this.aApplicationFilters || !Array.isArray(this.aApplicationFilters) || this.aApplicationFilters.length === 0) {
this.aApplicationFilters = [];
}
//if we have some Application Filters, they will ANDed to the Control-Filters
this.createFilterParams(this.aFilters, this.aApplicationFilters);
if (!this.bInitial) {
this.resetData();
this.abortPendingRequest();
this.sChangeReason = ChangeReason.Filter;
this._fireRefresh({reason : this.sChangeReason});
// TODO remove this if the filter event gets removed which is now deprecated
if (sFilterType == FilterType.Application) {
this._fireFilter({filters: this.aApplicationFilters});
} else {
this._fireFilter({filters: this.aFilters});
}
bSuccess = true;
}
if (bReturnSuccess) {
return bSuccess;
} else {
return this;
}
};
/**
* Creates a $filter query option string, which will be used
* as part of URL for OData-Requests. If an Array of Application Filters is given as the second
* If an array of application filters is given as second argument, the control filters and application filters are combined with AND.
* @param {sap.ui.model.Filter[]|sap.ui.model.odata.Filter[]} aControlFilters An Array of control filters
* @param {sap.ui.model.Filter[]|sap.ui.model.odata.Filter[]} [aApplicationFilters] An Array of application filters
* @private
*/
ODataListBinding.prototype.createFilterParams = function(aControlFilters, aApplicationFilters) {
// create URL Parameters for the Control- and Application-Filters
// either one or both may return undefined if the arrays given are wrong somehow
var sFilterParams,
sControlParams = ODataUtils._createFilterParams(aControlFilters, this.oModel.oMetadata, this.oEntityType),
sApplicationParams = ODataUtils._createFilterParams(aApplicationFilters, this.oModel.oMetadata, this.oEntityType);
if (sControlParams) {
sFilterParams = sControlParams;
}
if (sApplicationParams) {
//if there are control-filtes, AND the application filters
if (sControlParams) {
//Apply braces to the ANDed parts
sFilterParams = "(" + sFilterParams + ")" + "%20and%20" + "(" + sApplicationParams + ")";
} else {
//if the control-filters are undefined, we just use the application filter as a fallback
sFilterParams = sApplicationParams;
}
}
//prepend the system query option "$filter=" to the parameters (if parameters are given...)
if (sFilterParams) {
this.sFilterParams = "$filter=" + sFilterParams;
} else {
// no filter params could be constructed, since no control/application filter are given
// reset the filter params to 'undefined', so following requests exclude the filter query
this.sFilterParams = undefined;
}
};
ODataListBinding.prototype._initSortersFilters = function() {
// if path could not be resolved entity type cannot be retrieved and
// also filters/sorters don't need to be set
var sResolvedPath = this.oModel.resolve(this.sPath, this.oContext);
if (!sResolvedPath) {
return;
}
this.oEntityType = this._getEntityType();
this.createSortParams(this.aSorters);
this.createFilterParams(this.aFilters.concat(this.aApplicationFilters));
};
ODataListBinding.prototype._getEntityType = function(){
var sResolvedPath = this.oModel.resolve(this.sPath, this.oContext);
if (sResolvedPath) {
var oEntityType = this.oModel.oMetadata._getEntityTypeByPath(sResolvedPath);
jQuery.sap.assert(oEntityType, "EntityType for path " + sResolvedPath + " could not be found!");
return oEntityType;
}
return undefined;
};
ODataListBinding.prototype.resume = function() {
this.bIgnoreSuspend = false;
ListBinding.prototype.resume.apply(this, arguments);
};
return ODataListBinding;
});
| cschuff/openui5 | src/sap.ui.core/src/sap/ui/model/odata/ODataListBinding.js | JavaScript | apache-2.0 | 30,323 |
/**
* This is the main module of the app. It provides some useful services and configures the modules.
*/
(function(ng, $) {
// dependcies to all other modules.
var module = ng.module("incomb", [
"pascalprecht.translate",
"ngTagsInput",
"infinite-scroll",
"angularMoment",
"errors",
"home",
"news",
"category",
"provider",
"user",
"settings",
"router",
"nav",
"tagPreferences",
"categoryPreferences",
"userSettings",
"search",
"forms",
"comb",
"read",
"userLocales",
"slider",
"styles",
"profile" // has to be last because of the URLs.
]);
/**
* Sets the $locationProvider to HTML5 mode so we don't need to use the hash in the URL.
* Configures the $translateProvider that it automatically load the translation files from
* the right resource on the server.
*/
module.config(function($locationProvider, $translateProvider) {
$locationProvider.html5Mode(true);
$translateProvider.determinePreferredLanguage();
$translateProvider.useStaticFilesLoader({
prefix: '/api/translations/',
suffix: ''
});
});
/**
* Sets the locale of the "moment" module to the current.
*/
module.run(function(amMoment, localeUtil) {
amMoment.changeLocale(localeUtil.getCurrent());
});
/**
* This service is for modifing the window title. The <title> tag.
*/
module.service("pageTitle", function($rootScope, $translate) {
return {
/**
* Changes the window title to the given string and appends the general appendix to it.
* @param title string - the new title.
*/
change: function(title) {
$translate("pageTitles.appendix").then(function(appendix) {
$rootScope.pageTitle = title + appendix;
});
}
}
});
/**
* This service is to work with locales.
*/
module.service("localeUtil", function($translate) {
return {
/**
* @return string - the current browser locale.
*/
getCurrent: function() {
var locale = $translate.preferredLanguage();
if(locale.indexOf("_") > -1) {
var parts = locale.split("_");
locale = parts[0] + "_" + parts[1].toUpperCase();
}
return locale;
}
};
});
/**
* This filter removes all tags from the given input.
*/
module.filter("plain", function() {
return function(text) {
return String(text).replace(/<[^>]+>/gm, '');
};
});
/**
* This filter encodes the given URL part.
*/
module.filter("urlencode", function() {
return function(text) {
return encodeURIComponent(String(text));
};
});
/**
* This directive executes the function in the after-render attribute after the element was rendered.
*/
module.directive("afterRender", function($timeout) {
return function(scope, element, attrs) {
$timeout(function() {
scope.$eval(attrs.afterRender);
});
};
});
})(angular, jQuery);
| XMBomb/InComb | WebContent/js/incomb.js | JavaScript | apache-2.0 | 2,819 |
/**
* AlMighty page object example module for Fabric8 start page
* See: http://martinfowler.com/bliki/PageObject.html,
* https://www.thoughtworks.com/insights/blog/using-page-objects-overcome-protractors-shortcomings
* @author [email protected]
*/
'use strict';
/*
* Fabric8 Start Page Definition
*/
let testSupport = require('../testSupport');
let constants = require("../constants");
let Fabric8RHDLoginPage = require("./fabric8-RHD-login.page");
let until = protractor.ExpectedConditions;
class Fabric8StartPage {
constructor(login) {
browser.get("http://prod-preview.openshift.io/public");
};
get githubLoginButton () {
return element(by.css(".fa.fa-github"));
}
clickGithubLoginButton () {
browser.wait(until.presenceOf(this.githubLoginButton), constants.WAIT, 'Failed to find github login');
this.githubLoginButton.click();
return new Fabric8RHDLoginPage();
}
}
module.exports = Fabric8StartPage;
| pmuir/fabric8-planner | src/tests/work-item/work-item-list/page-objects/fabric8-start.page.js | JavaScript | apache-2.0 | 954 |
/// <reference path="Base.js" />
var Event = Base.inherit({
init: function () {
this.handlers = [];
},
subscribe: function (handler) {
this.handlers.push(handler);
},
trigger: function () {
var eventData = arguments;
this.handlers.forEach(function (handler) {
handler.apply(null, eventData);
});
}
}); | andrewdavey/reference-application | App/Client/Shared/Event.js | JavaScript | apache-2.0 | 404 |
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var pow = require( '@stdlib/math/base/special/pow' );
var ln = require( '@stdlib/math/base/special/ln' );
var PINF = require( '@stdlib/constants/float64/pinf' );
var NINF = require( '@stdlib/constants/float64/ninf' );
// MAIN //
/**
* Evaluates the logarithm of the probability density function (PDF) for a Rayleigh distribution with scale parameter `sigma` at a value `x`.
*
* @param {number} x - input value
* @param {NonNegativeNumber} sigma - scale parameter
* @returns {number} evaluated logPDF
*
* @example
* var y = logpdf( 0.3, 1.0 );
* // returns ~-1.249
*
* @example
* var y = logpdf( 2.0, 0.8 );
* // returns ~-1.986
*
* @example
* var y = logpdf( -1.0, 0.5 );
* // returns -Infinity
*
* @example
* var y = logpdf( 0.0, NaN );
* // returns NaN
*
* @example
* var y = logpdf( NaN, 2.0 );
* // returns NaN
*
* @example
* // Negative scale parameter:
* var y = logpdf( 2.0, -1.0 );
* // returns NaN
*/
function logpdf( x, sigma ) {
var s2i;
var s2;
if (
isnan( x ) ||
isnan( sigma ) ||
sigma < 0.0
) {
return NaN;
}
if ( sigma === 0.0 ) {
return ( x === 0.0 ) ? PINF : NINF;
}
if ( x < 0.0 || x === PINF ) {
return NINF;
}
s2 = pow( sigma, 2.0 );
s2i = 1.0 / s2;
return ln( s2i * x ) - (pow( x, 2.0 ) / ( 2.0 * s2 ));
}
// EXPORTS //
module.exports = logpdf;
| stdlib-js/stdlib | lib/node_modules/@stdlib/stats/base/dists/rayleigh/logpdf/lib/logpdf.js | JavaScript | apache-2.0 | 2,003 |
"use strict";
/**
* dockerUtils.js - Common parts for dockerode
*
* Copyright (C) 2016 Anton Zagorskii aka amberovsky. All rights reserved. Contacts: <[email protected]>
*/
class DockerUtils {
/**
* @constructor
*/
constructor() {
this.Docker = require('dockerode');
};
/**
* @param {Object} request - expressjs request
* @returns {Function} - docker instance for a request
*/
createDockerForRequest(request) {
var self = this;
return function() {
if (typeof request.docker === 'undefined') {
request.docker = new self.Docker({
host: request.node.getIp(),
protocol: 'https',
ca: request.project.getCA(),
cert: request.project.getCERT(),
key: request.project.getKEY(),
port: request.node.getPort()
});
}
return request.docker;
}
}
/**
* Create docker object by custom parameters
*
* @param {string} ip - node IP
* @param {number} port - node port
* @param {string} CA - CA
* @param {string} CERT - CERT
* @param {string} KEY - KEY
*/
createDockerCustom(ip, port, CA, CERT, KEY) {
return new this.Docker({
host: ip,
protocol: 'https',
ca: CA,
cert: CERT,
key: KEY,
port: port
});
}
}
module.exports = DockerUtils;
| amberovsky/docker-blah | library/dockerUtils.js | JavaScript | apache-2.0 | 1,541 |
// component preview locators
const HELP_ICON_PREVIEW = 'a[data-component="help"]';
export default HELP_ICON_PREVIEW;
| Sage/carbon | cypress/locators/help/locators.js | JavaScript | apache-2.0 | 119 |
'use strict';
var _ = require('lodash');
var Poll = require('./poll.model');
// Get list of polls
exports.index = function(req, res) {
Poll.find(function (err, polls) {
if(err) { return handleError(res, err); }
return res.status(200).json(polls);
});
};
// Get a single poll
exports.show = function(req, res) {
Poll.findById(req.params.id, function (err, poll) {
if(err) { return handleError(res, err); }
if(!poll) { return res.status(404).send('Not Found'); }
return res.json(poll);
});
};
// Creates a new poll in the DB.
exports.create = function(req, res) {
Poll.create(req.body, function(err, poll) {
if(err) { return handleError(res, err); }
return res.status(201).json(poll);
});
};
// Updates an existing poll in the DB.
exports.update = function(req, res) {
if(req.body._id) { delete req.body._id; }
Poll.findById(req.params.id, function (err, poll) {
if (err) { return handleError(res, err); }
if(!poll) { return res.status(404).send('Not Found'); }
var updated = _.merge(poll, req.body);
updated.save(function (err) {
if (err) { return handleError(res, err); }
return res.status(200).json(poll);
});
});
};
// Deletes a poll from the DB.
exports.destroy = function(req, res) {
Poll.findById(req.params.id, function (err, poll) {
if(err) { return handleError(res, err); }
if(!poll) { return res.status(404).send('Not Found'); }
poll.remove(function(err) {
if(err) { return handleError(res, err); }
return res.status(204).send('No Content');
});
});
};
/**
* Insert Vote into Poll.choices.votes
*
* @param req with params.pollid and body { choiceid: "", fingerprint: "" }
* @param res
*/
exports.vote = function (req, res) {
var pollid = req.params.id;
var choiceid = req.body.choiceid;
var fingerprint = req.body.fingerprint;
//ensure fingerprint
if (fingerprint === undefined || fingerprint === null || fingerprint === "") {
return res.status(400).send('No client id');
}
Poll.findById(pollid, function (err, poll) {
if(err) { return handleError(res, err); }
if(!poll) { return res.status(404).send('Not Found'); }
//check if already voted
for (var c in poll.choices) {
var curChoice = poll.choices[c];
for (var v in curChoice.votes) {
var curVote = curChoice.votes[v];
if (curVote.fingerprint === fingerprint) {
return res.status(400).send('already voted for poll');
}
}
}
var choice = poll.choices.id(choiceid);
choice.votes.push({ fingerprint: fingerprint });
poll.save(function(err, doc) {
if (err) {
return handleError(res, err);
}
return res.status(200).json(doc);
});
});
};
function handleError(res, err) {
return res.status(500).send(err);
}
| SBejga/ng-vote | server/api/poll/poll.controller.js | JavaScript | apache-2.0 | 2,827 |
import React, { Component, PropTypes } from 'react';
import ChooseOneOption from './ChooseOneOption';
import styles from '../../style/test.scss';
export default class ChooseOneTask extends Component {
static propTypes = {
prompt: PropTypes.string.isRequired,
options: PropTypes.array.isRequired,
correctAnswer: PropTypes.string.isRequired,
taskComplete: PropTypes.func.isRequired
};
optionSelected(option) {
if (this.state && this.state.selected) {
this.setState({
selected: null
});
this.props.taskComplete(option);
} else {
this.setState({
selected: option
});
}
}
render() {
const { prompt, options, correctAnswer } = this.props;
const { selected } = this.state || {};
return <div>
<h3 className={styles.prompt}>{prompt}</h3>
<ul className="list-group">
{options.map((option, idx) =>
<ChooseOneOption
key={idx} option={option} onSelect={this.optionSelected.bind(this)}
correct={option === selected && option === correctAnswer}
incorrect={option === selected && option !== correctAnswer}
/>
)}
</ul>
</div>;
}
}
| alexeyryzhikov/kanjitesto | src/components/test/ChooseOneTask.js | JavaScript | apache-2.0 | 1,211 |
/**
* @license Apache-2.0
*
* Copyright (c) 2020 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var bench = require( '@stdlib/bench' );
var randu = require( '@stdlib/random/base/randu' );
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var pow = require( '@stdlib/math/base/special/pow' );
var Float64Array = require( '@stdlib/array/float64' );
var array = require( '@stdlib/ndarray/array' );
var pkg = require( './../package.json' ).name;
var dswap = require( './../lib/main.js' );
// FUNCTIONS //
/**
* Creates a benchmark function.
*
* @private
* @param {PositiveInteger} len - array length
* @returns {Function} benchmark function
*/
function createBenchmark( len ) {
var x;
var y;
var i;
x = new Float64Array( len );
y = new Float64Array( len );
for ( i = 0; i < len; i++ ) {
x[ i ] = ( randu()*10.0 ) - 20.0;
y[ i ] = ( randu()*10.0 ) - 20.0;
}
x = array( x );
y = array( y );
return benchmark;
function benchmark( b ) {
var d;
var i;
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
d = dswap( x, y );
if ( isnan( d[ i%x.length ] ) ) {
b.fail( 'should not return NaN' );
}
}
b.toc();
if ( isnan( d ) ) {
b.fail( 'should not return NaN' );
}
b.pass( 'benchmark finished' );
b.end();
}
}
// MAIN //
/**
* Main execution sequence.
*
* @private
*/
function main() {
var len;
var min;
var max;
var f;
var i;
min = 1; // 10^min
max = 6; // 10^max
for ( i = min; i <= max; i++ ) {
len = pow( 10, i );
f = createBenchmark( len );
bench( pkg+':len='+len, f );
}
}
main();
| stdlib-js/stdlib | lib/node_modules/@stdlib/blas/dswap/benchmark/benchmark.js | JavaScript | apache-2.0 | 2,111 |
var parser = require("biojs-io-xmfa");
var fastaParser = require("biojs-io-fasta");
var brewer = require("colorbrewer");
var d3 = require("d3");
var biojsvizxmfa;
module.exports = biojsvizxmfa = function(opts){
this.el = opts.el;
this.opts = {
"x_offset": 10,
"y_offset": 10,
"scale": 4,
"genome_sep": 30,
"color": brewer['Set1'][8]
};
var self = this;
parser.read("/outseq.xmfa", function(err, model) {
var text = document.createElement("div");
// Convert lcbs to easy-to-read table
var table = document.createElement("div");
table.innerHTML = "<h1>LCB Table</h1>" + biojsvizxmfa.lcbsAsTable(self, model);
text.appendChild(table);
var svgContainer = d3.select(self.el).append("svg")
.attr("width", 1000)
.attr("height", 200);
fastaParser.read("/outseq.fa", function(err, fa_model) {
var lcb_fa_table = {};
for(var fa_idx in fa_model){
var seq = fa_model[fa_idx];
var seq_seq = seq.seq;
lcb_fa_table[1 + parseInt(fa_idx)] = seq.name;
var line_attr = {
"x1": self.opts.x_offset + 0,
"y1": self.opts.y_offset + self.opts.genome_sep * fa_idx,
"x2": self.opts.x_offset + (seq_seq.length / self.opts.scale),
"y2": self.opts.y_offset + self.opts.genome_sep * fa_idx,
"stroke-width": 2,
"stroke": "black"
};
var line_label_attr = {
"dx": 0,
"dy": "-.35em",
"font-family": "sans-serif",
"font-size": "10px",
"fill": "black"
};
var line = svgContainer.append("line")
.attr(line_attr)
.append("text")
.attr("dx", 12)
.attr("dy", ".35em")
.text("Blah");
//.text(seq.name)
//.attr(line_label_attr);
}
for(var lcb_idx in model){if(model[lcb_idx].length > 1){
var lcb_group = svgContainer.append("g");
// Find a nice colour
var current_colour = self.opts.color[lcb_idx];
// Store polygon points as left/right sides
var current_poly_left = [];
var current_poly_right = [];
var regions = [];
// Loop across Regions in LCB
// Plot them + record left/right sides
for(var lcb_subidx in model[lcb_idx]){
var hsp = model[lcb_idx][lcb_subidx];
var region_highlight_attr = {
"x": self.opts.x_offset + (hsp['start'] / self.opts.scale),
"width": ((hsp['end'] - hsp['start']) / self.opts.scale),
"y": self.opts.y_offset + self.opts.genome_sep * (hsp['lcb_idx'] - 1) - 3,
"height": 6,
"fill": current_colour
}
regions.push(region_highlight_attr);
var left_x, right_x;
if(hsp['strand'] == '+'){
left_x = hsp['start'];
right_x = hsp['end'];
}else{
left_x = hsp['end'];
right_x = hsp['start'];
}
current_poly_left.push({
'x': self.opts.x_offset + (left_x / self.opts.scale),
'y': self.opts.y_offset + self.opts.genome_sep * (hsp['lcb_idx'] - 1)
});
current_poly_right.push({
'x': self.opts.x_offset + (right_x / self.opts.scale),
'y': self.opts.y_offset + self.opts.genome_sep * (hsp['lcb_idx'] - 1)
});
}
current_poly_left.reverse();
for(var tmp in current_poly_left){
current_poly_right.push(current_poly_left[tmp]);
}
var poly = lcb_group.append("polygon")
.data([current_poly_right])
.attr("points",function(d) {
return d.map(function(d) {
return [d.x, d.y].join(",");
}).join(" ");
})
.attr("opacity", 0.6)
.attr("fill", current_colour);
for(var idx in regions){
lcb_group.append("rect").attr(regions[idx]);
}
}}
svgContainer.selectAll("g")
.on("mouseover", function(){
d3.select(this).select("polygon")
.style("opacity", 0.6)
.transition()
.duration(500)
.style("opacity", 1.0);
d3.select(this).selectAll("rect")
.style("stroke-width", 0)
.style("stroke", "black")
.transition()
.duration(500)
.style("stroke-width", 1)
.style("stroke", "black");
var element = d3.select(this)[0][0];
element.parentNode.appendChild(element);
})
.on("mouseout", function() {
d3.select(this).select("polygon")
.style("opacity", 1.0)
.transition()
.duration(500)
.style("opacity", 0.6);
d3.select(this).selectAll("rect")
.style("stroke-width", 1)
.style("stroke", "black")
.transition()
.duration(500)
.style("stroke-width", 0)
.style("stroke", "black");
});
});
self.el.appendChild(text);
});
};
biojsvizxmfa.lcbsAsTable = function (self, lcbs) {
var table_text = "";
for(var lcb_idx in lcbs){if(lcbs[lcb_idx].length > 1){
for(var lcb_subidx in lcbs[lcb_idx]){
var hsp = lcbs[lcb_idx][lcb_subidx];
var row = [lcb_idx, hsp['lcb_idx'], hsp['start'], hsp['end'], hsp['strand']];
table_text += "<tr style='background:" + self.opts.color[lcb_idx] + "'><td>" + row.join("</td><td>") + "</td></tr>";
}
}}
var thead = "<thead><tr><th>" + ["LCB", "Sequence", "Start", "End", "Strand"].join("</th><th>") + " </th></tr></thead>";
return "<table>" + thead + "<tbody>" + table_text + "</tbody></table>";
};
| erasche/biojs-vis-xmfa | lib/index.js | JavaScript | apache-2.0 | 6,431 |
/*
* Copyright 2013 The Generic Skeleton Website
*
* The Generic Skeleton Website Project licenses this file to you 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.
*/
(function (root, doc, factory) {
if (typeof define === "function" && define.amd) {
// AMD. Register as an anonymous module.
define([ "jquery" ], function ($) {
factory($, root, doc);
return $.mobile;
});
} else {
// Browser globals
factory(root.jQuery, root, doc);
}
}(this, document, function (jQuery, window, document, undefined) {
(function ($) {
$.mobile = {};
}(jQuery));
(function ($, window, undefined) {
var nsNormalizeDict = {};
// jQuery.mobile configurable options
$.mobile = $.extend($.mobile, {
// Version of the jQuery Mobile Framework
version: "1.3.2",
// Namespace used framework-wide for data-attrs. Default is no namespace
ns: "",
// Define the url parameter used for referencing widget-generated sub-pages.
// Translates to to example.html&ui-page=subpageIdentifier
// hash segment before &ui-page= is used to make Ajax request
subPageUrlKey: "ui-page",
// Class assigned to page currently in view, and during transitions
activePageClass: "ui-page-active",
// Class used for "active" button state, from CSS framework
activeBtnClass: "ui-btn-active",
// Class used for "focus" form element state, from CSS framework
focusClass: "ui-focus",
// Automatically handle clicks and form submissions through Ajax, when same-domain
ajaxEnabled: true,
// Automatically load and show pages based on location.hash
hashListeningEnabled: true,
// disable to prevent jquery from bothering with links
linkBindingEnabled: true,
// Set default page transition - 'none' for no transitions
defaultPageTransition: "fade",
// Set maximum window width for transitions to apply - 'false' for no limit
maxTransitionWidth: false,
// Minimum scroll distance that will be remembered when returning to a page
minScrollBack: 250,
// DEPRECATED: the following property is no longer in use, but defined until 2.0 to prevent conflicts
touchOverflowEnabled: false,
// Set default dialog transition - 'none' for no transitions
defaultDialogTransition: "pop",
// Error response message - appears when an Ajax page request fails
pageLoadErrorMessage: "Error Loading Page",
// For error messages, which theme does the box uses?
pageLoadErrorMessageTheme: "e",
// replace calls to window.history.back with phonegaps navigation helper
// where it is provided on the window object
phonegapNavigationEnabled: false,
//automatically initialize the DOM when it's ready
autoInitializePage: true,
pushStateEnabled: true,
// allows users to opt in to ignoring content by marking a parent element as
// data-ignored
ignoreContentEnabled: false,
// turn of binding to the native orientationchange due to android orientation behavior
orientationChangeEnabled: true,
buttonMarkup: {
hoverDelay: 200
},
// define the window and the document objects
window: $(window),
document: $(document),
// TODO might be useful upstream in jquery itself ?
keyCode: {
ALT: 18,
BACKSPACE: 8,
CAPS_LOCK: 20,
COMMA: 188,
COMMAND: 91,
COMMAND_LEFT: 91, // COMMAND
COMMAND_RIGHT: 93,
CONTROL: 17,
DELETE: 46,
DOWN: 40,
END: 35,
ENTER: 13,
ESCAPE: 27,
HOME: 36,
INSERT: 45,
LEFT: 37,
MENU: 93, // COMMAND_RIGHT
NUMPAD_ADD: 107,
NUMPAD_DECIMAL: 110,
NUMPAD_DIVIDE: 111,
NUMPAD_ENTER: 108,
NUMPAD_MULTIPLY: 106,
NUMPAD_SUBTRACT: 109,
PAGE_DOWN: 34,
PAGE_UP: 33,
PERIOD: 190,
RIGHT: 39,
SHIFT: 16,
SPACE: 32,
TAB: 9,
UP: 38,
WINDOWS: 91 // COMMAND
},
// Place to store various widget extensions
behaviors: {},
// Scroll page vertically: scroll to 0 to hide iOS address bar, or pass a Y value
silentScroll: function (ypos) {
if ($.type(ypos) !== "number") {
ypos = $.mobile.defaultHomeScroll;
}
// prevent scrollstart and scrollstop events
$.event.special.scrollstart.enabled = false;
setTimeout(function () {
window.scrollTo(0, ypos);
$.mobile.document.trigger("silentscroll", { x: 0, y: ypos });
}, 20);
setTimeout(function () {
$.event.special.scrollstart.enabled = true;
}, 150);
},
// Expose our cache for testing purposes.
nsNormalizeDict: nsNormalizeDict,
// Take a data attribute property, prepend the namespace
// and then camel case the attribute string. Add the result
// to our nsNormalizeDict so we don't have to do this again.
nsNormalize: function (prop) {
if (!prop) {
return;
}
return nsNormalizeDict[ prop ] || ( nsNormalizeDict[ prop ] = $.camelCase($.mobile.ns + prop) );
},
// Find the closest parent with a theme class on it. Note that
// we are not using $.fn.closest() on purpose here because this
// method gets called quite a bit and we need it to be as fast
// as possible.
getInheritedTheme: function (el, defaultTheme) {
var e = el[ 0 ],
ltr = "",
re = /ui-(bar|body|overlay)-([a-z])\b/,
c, m;
while (e) {
c = e.className || "";
if (c && ( m = re.exec(c) ) && ( ltr = m[ 2 ] )) {
// We found a parent with a theme class
// on it so bail from this loop.
break;
}
e = e.parentNode;
}
// Return the theme letter we found, if none, return the
// specified default.
return ltr || defaultTheme || "a";
},
// TODO the following $ and $.fn extensions can/probably should be moved into jquery.mobile.core.helpers
//
// Find the closest javascript page element to gather settings data jsperf test
// http://jsperf.com/single-complex-selector-vs-many-complex-selectors/edit
// possibly naive, but it shows that the parsing overhead for *just* the page selector vs
// the page and dialog selector is negligable. This could probably be speed up by
// doing a similar parent node traversal to the one found in the inherited theme code above
closestPageData: function ($target) {
return $target
.closest(':jqmData(role="page"), :jqmData(role="dialog")')
.data("mobile-page");
},
enhanceable: function ($set) {
return this.haveParents($set, "enhance");
},
hijackable: function ($set) {
return this.haveParents($set, "ajax");
},
haveParents: function ($set, attr) {
if (!$.mobile.ignoreContentEnabled) {
return $set;
}
var count = $set.length,
$newSet = $(),
e, $element, excluded;
for (var i = 0; i < count; i++) {
$element = $set.eq(i);
excluded = false;
e = $set[ i ];
while (e) {
var c = e.getAttribute ? e.getAttribute("data-" + $.mobile.ns + attr) : "";
if (c === "false") {
excluded = true;
break;
}
e = e.parentNode;
}
if (!excluded) {
$newSet = $newSet.add($element);
}
}
return $newSet;
},
getScreenHeight: function () {
// Native innerHeight returns more accurate value for this across platforms,
// jQuery version is here as a normalized fallback for platforms like Symbian
return window.innerHeight || $.mobile.window.height();
}
}, $.mobile);
// Mobile version of data and removeData and hasData methods
// ensures all data is set and retrieved using jQuery Mobile's data namespace
$.fn.jqmData = function (prop, value) {
var result;
if (typeof prop !== "undefined") {
if (prop) {
prop = $.mobile.nsNormalize(prop);
}
// undefined is permitted as an explicit input for the second param
// in this case it returns the value and does not set it to undefined
if (arguments.length < 2 || value === undefined) {
result = this.data(prop);
} else {
result = this.data(prop, value);
}
}
return result;
};
$.jqmData = function (elem, prop, value) {
var result;
if (typeof prop !== "undefined") {
result = $.data(elem, prop ? $.mobile.nsNormalize(prop) : prop, value);
}
return result;
};
$.fn.jqmRemoveData = function (prop) {
return this.removeData($.mobile.nsNormalize(prop));
};
$.jqmRemoveData = function (elem, prop) {
return $.removeData(elem, $.mobile.nsNormalize(prop));
};
$.fn.removeWithDependents = function () {
$.removeWithDependents(this);
};
$.removeWithDependents = function (elem) {
var $elem = $(elem);
( $elem.jqmData('dependents') || $() ).remove();
$elem.remove();
};
$.fn.addDependents = function (newDependents) {
$.addDependents($(this), newDependents);
};
$.addDependents = function (elem, newDependents) {
var dependents = $(elem).jqmData('dependents') || $();
$(elem).jqmData('dependents', $.merge(dependents, newDependents));
};
// note that this helper doesn't attempt to handle the callback
// or setting of an html element's text, its only purpose is
// to return the html encoded version of the text in all cases. (thus the name)
$.fn.getEncodedText = function () {
return $("<div/>").text($(this).text()).html();
};
// fluent helper function for the mobile namespaced equivalent
$.fn.jqmEnhanceable = function () {
return $.mobile.enhanceable(this);
};
$.fn.jqmHijackable = function () {
return $.mobile.hijackable(this);
};
// Monkey-patching Sizzle to filter the :jqmData selector
var oldFind = $.find,
jqmDataRE = /:jqmData\(([^)]*)\)/g;
$.find = function (selector, context, ret, extra) {
selector = selector.replace(jqmDataRE, "[data-" + ( $.mobile.ns || "" ) + "$1]");
return oldFind.call(this, selector, context, ret, extra);
};
$.extend($.find, oldFind);
$.find.matches = function (expr, set) {
return $.find(expr, null, null, set);
};
$.find.matchesSelector = function (node, expr) {
return $.find(expr, null, null, [ node ]).length > 0;
};
})(jQuery, this);
/*!
* jQuery UI Widget v1.10.0pre - 2012-11-13 (ff055a0c353c3c8ce6e5bfa07ad7cb03e8885bc5)
* http://jqueryui.com
*
* Copyright 2010, 2013 jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
* http://api.jqueryui.com/jQuery.widget/
*/
(function ($, undefined) {
var uuid = 0,
slice = Array.prototype.slice,
_cleanData = $.cleanData;
$.cleanData = function (elems) {
for (var i = 0, elem; (elem = elems[i]) != null; i++) {
try {
$(elem).triggerHandler("remove");
// http://bugs.jquery.com/ticket/8235
} catch (e) {
}
}
_cleanData(elems);
};
$.widget = function (name, base, prototype) {
var fullName, existingConstructor, constructor, basePrototype,
namespace = name.split(".")[ 0 ];
name = name.split(".")[ 1 ];
fullName = namespace + "-" + name;
if (!prototype) {
prototype = base;
base = $.Widget;
}
// create selector for plugin
$.expr[ ":" ][ fullName.toLowerCase() ] = function (elem) {
return !!$.data(elem, fullName);
};
$[ namespace ] = $[ namespace ] || {};
existingConstructor = $[ namespace ][ name ];
constructor = $[ namespace ][ name ] = function (options, element) {
// allow instantiation without "new" keyword
if (!this._createWidget) {
return new constructor(options, element);
}
// allow instantiation without initializing for simple inheritance
// must use "new" keyword (the code above always passes args)
if (arguments.length) {
this._createWidget(options, element);
}
};
// extend with the existing constructor to carry over any static properties
$.extend(constructor, existingConstructor, {
version: prototype.version,
// copy the object used to create the prototype in case we need to
// redefine the widget later
_proto: $.extend({}, prototype),
// track widgets that inherit from this widget in case this widget is
// redefined after a widget inherits from it
_childConstructors: []
});
basePrototype = new base();
// we need to make the options hash a property directly on the new instance
// otherwise we'll modify the options hash on the prototype that we're
// inheriting from
basePrototype.options = $.widget.extend({}, basePrototype.options);
$.each(prototype, function (prop, value) {
if ($.isFunction(value)) {
prototype[ prop ] = (function () {
var _super = function () {
return base.prototype[ prop ].apply(this, arguments);
},
_superApply = function (args) {
return base.prototype[ prop ].apply(this, args);
};
return function () {
var __super = this._super,
__superApply = this._superApply,
returnValue;
this._super = _super;
this._superApply = _superApply;
returnValue = value.apply(this, arguments);
this._super = __super;
this._superApply = __superApply;
return returnValue;
};
})();
}
});
constructor.prototype = $.widget.extend(basePrototype, {
// TODO: remove support for widgetEventPrefix
// always use the name + a colon as the prefix, e.g., draggable:start
// don't prefix for widgets that aren't DOM-based
widgetEventPrefix: existingConstructor ? basePrototype.widgetEventPrefix : name
}, prototype, {
constructor: constructor,
namespace: namespace,
widgetName: name,
widgetFullName: fullName
});
// If this widget is being redefined then we need to find all widgets that
// are inheriting from it and redefine all of them so that they inherit from
// the new version of this widget. We're essentially trying to replace one
// level in the prototype chain.
if (existingConstructor) {
$.each(existingConstructor._childConstructors, function (i, child) {
var childPrototype = child.prototype;
// redefine the child widget using the same prototype that was
// originally used, but inherit from the new version of the base
$.widget(childPrototype.namespace + "." + childPrototype.widgetName, constructor, child._proto);
});
// remove the list of existing child constructors from the old constructor
// so the old child constructors can be garbage collected
delete existingConstructor._childConstructors;
} else {
base._childConstructors.push(constructor);
}
$.widget.bridge(name, constructor);
};
$.widget.extend = function (target) {
var input = slice.call(arguments, 1),
inputIndex = 0,
inputLength = input.length,
key,
value;
for (; inputIndex < inputLength; inputIndex++) {
for (key in input[ inputIndex ]) {
value = input[ inputIndex ][ key ];
if (input[ inputIndex ].hasOwnProperty(key) && value !== undefined) {
// Clone objects
if ($.isPlainObject(value)) {
target[ key ] = $.isPlainObject(target[ key ]) ?
$.widget.extend({}, target[ key ], value) :
// Don't extend strings, arrays, etc. with objects
$.widget.extend({}, value);
// Copy everything else by reference
} else {
target[ key ] = value;
}
}
}
}
return target;
};
$.widget.bridge = function (name, object) {
var fullName = object.prototype.widgetFullName || name;
$.fn[ name ] = function (options) {
var isMethodCall = typeof options === "string",
args = slice.call(arguments, 1),
returnValue = this;
// allow multiple hashes to be passed on init
options = !isMethodCall && args.length ?
$.widget.extend.apply(null, [ options ].concat(args)) :
options;
if (isMethodCall) {
this.each(function () {
var methodValue,
instance = $.data(this, fullName);
if (!instance) {
return $.error("cannot call methods on " + name + " prior to initialization; " +
"attempted to call method '" + options + "'");
}
if (!$.isFunction(instance[options]) || options.charAt(0) === "_") {
return $.error("no such method '" + options + "' for " + name + " widget instance");
}
methodValue = instance[ options ].apply(instance, args);
if (methodValue !== instance && methodValue !== undefined) {
returnValue = methodValue && methodValue.jquery ?
returnValue.pushStack(methodValue.get()) :
methodValue;
return false;
}
});
} else {
this.each(function () {
var instance = $.data(this, fullName);
if (instance) {
instance.option(options || {})._init();
} else {
$.data(this, fullName, new object(options, this));
}
});
}
return returnValue;
};
};
$.Widget = function (/* options, element */) {
};
$.Widget._childConstructors = [];
$.Widget.prototype = {
widgetName: "widget",
widgetEventPrefix: "",
defaultElement: "<div>",
options: {
disabled: false,
// callbacks
create: null
},
_createWidget: function (options, element) {
element = $(element || this.defaultElement || this)[ 0 ];
this.element = $(element);
this.uuid = uuid++;
this.eventNamespace = "." + this.widgetName + this.uuid;
this.options = $.widget.extend({},
this.options,
this._getCreateOptions(),
options);
this.bindings = $();
this.hoverable = $();
this.focusable = $();
if (element !== this) {
$.data(element, this.widgetFullName, this);
this._on(true, this.element, {
remove: function (event) {
if (event.target === element) {
this.destroy();
}
}
});
this.document = $(element.style ?
// element within the document
element.ownerDocument :
// element is window or document
element.document || element);
this.window = $(this.document[0].defaultView || this.document[0].parentWindow);
}
this._create();
this._trigger("create", null, this._getCreateEventData());
this._init();
},
_getCreateOptions: $.noop,
_getCreateEventData: $.noop,
_create: $.noop,
_init: $.noop,
destroy: function () {
this._destroy();
// we can probably remove the unbind calls in 2.0
// all event bindings should go through this._on()
this.element
.unbind(this.eventNamespace)
// 1.9 BC for #7810
// TODO remove dual storage
.removeData(this.widgetName)
.removeData(this.widgetFullName)
// support: jquery <1.6.3
// http://bugs.jquery.com/ticket/9413
.removeData($.camelCase(this.widgetFullName));
this.widget()
.unbind(this.eventNamespace)
.removeAttr("aria-disabled")
.removeClass(
this.widgetFullName + "-disabled " +
"ui-state-disabled");
// clean up events and states
this.bindings.unbind(this.eventNamespace);
this.hoverable.removeClass("ui-state-hover");
this.focusable.removeClass("ui-state-focus");
},
_destroy: $.noop,
widget: function () {
return this.element;
},
option: function (key, value) {
var options = key,
parts,
curOption,
i;
if (arguments.length === 0) {
// don't return a reference to the internal hash
return $.widget.extend({}, this.options);
}
if (typeof key === "string") {
// handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } }
options = {};
parts = key.split(".");
key = parts.shift();
if (parts.length) {
curOption = options[ key ] = $.widget.extend({}, this.options[ key ]);
for (i = 0; i < parts.length - 1; i++) {
curOption[ parts[ i ] ] = curOption[ parts[ i ] ] || {};
curOption = curOption[ parts[ i ] ];
}
key = parts.pop();
if (value === undefined) {
return curOption[ key ] === undefined ? null : curOption[ key ];
}
curOption[ key ] = value;
} else {
if (value === undefined) {
return this.options[ key ] === undefined ? null : this.options[ key ];
}
options[ key ] = value;
}
}
this._setOptions(options);
return this;
},
_setOptions: function (options) {
var key;
for (key in options) {
this._setOption(key, options[ key ]);
}
return this;
},
_setOption: function (key, value) {
this.options[ key ] = value;
if (key === "disabled") {
this.widget()
.toggleClass(this.widgetFullName + "-disabled ui-state-disabled", !!value)
.attr("aria-disabled", value);
this.hoverable.removeClass("ui-state-hover");
this.focusable.removeClass("ui-state-focus");
}
return this;
},
enable: function () {
return this._setOption("disabled", false);
},
disable: function () {
return this._setOption("disabled", true);
},
_on: function (suppressDisabledCheck, element, handlers) {
var delegateElement,
instance = this;
// no suppressDisabledCheck flag, shuffle arguments
if (typeof suppressDisabledCheck !== "boolean") {
handlers = element;
element = suppressDisabledCheck;
suppressDisabledCheck = false;
}
// no element argument, shuffle and use this.element
if (!handlers) {
handlers = element;
element = this.element;
delegateElement = this.widget();
} else {
// accept selectors, DOM elements
element = delegateElement = $(element);
this.bindings = this.bindings.add(element);
}
$.each(handlers, function (event, handler) {
function handlerProxy() {
// allow widgets to customize the disabled handling
// - disabled as an array instead of boolean
// - disabled class as method for disabling individual parts
if (!suppressDisabledCheck &&
( instance.options.disabled === true ||
$(this).hasClass("ui-state-disabled") )) {
return;
}
return ( typeof handler === "string" ? instance[ handler ] : handler )
.apply(instance, arguments);
}
// copy the guid so direct unbinding works
if (typeof handler !== "string") {
handlerProxy.guid = handler.guid =
handler.guid || handlerProxy.guid || $.guid++;
}
var match = event.match(/^(\w+)\s*(.*)$/),
eventName = match[1] + instance.eventNamespace,
selector = match[2];
if (selector) {
delegateElement.delegate(selector, eventName, handlerProxy);
} else {
element.bind(eventName, handlerProxy);
}
});
},
_off: function (element, eventName) {
eventName = (eventName || "").split(" ").join(this.eventNamespace + " ") + this.eventNamespace;
element.unbind(eventName).undelegate(eventName);
},
_delay: function (handler, delay) {
function handlerProxy() {
return ( typeof handler === "string" ? instance[ handler ] : handler )
.apply(instance, arguments);
}
var instance = this;
return setTimeout(handlerProxy, delay || 0);
},
_hoverable: function (element) {
this.hoverable = this.hoverable.add(element);
this._on(element, {
mouseenter: function (event) {
$(event.currentTarget).addClass("ui-state-hover");
},
mouseleave: function (event) {
$(event.currentTarget).removeClass("ui-state-hover");
}
});
},
_focusable: function (element) {
this.focusable = this.focusable.add(element);
this._on(element, {
focusin: function (event) {
$(event.currentTarget).addClass("ui-state-focus");
},
focusout: function (event) {
$(event.currentTarget).removeClass("ui-state-focus");
}
});
},
_trigger: function (type, event, data) {
var prop, orig,
callback = this.options[ type ];
data = data || {};
event = $.Event(event);
event.type = ( type === this.widgetEventPrefix ?
type :
this.widgetEventPrefix + type ).toLowerCase();
// the original event may come from any element
// so we need to reset the target on the new event
event.target = this.element[ 0 ];
// copy original event properties over to the new event
orig = event.originalEvent;
if (orig) {
for (prop in orig) {
if (!( prop in event )) {
event[ prop ] = orig[ prop ];
}
}
}
this.element.trigger(event, data);
return !( $.isFunction(callback) &&
callback.apply(this.element[0], [ event ].concat(data)) === false ||
event.isDefaultPrevented() );
}
};
$.each({ show: "fadeIn", hide: "fadeOut" }, function (method, defaultEffect) {
$.Widget.prototype[ "_" + method ] = function (element, options, callback) {
if (typeof options === "string") {
options = { effect: options };
}
var hasOptions,
effectName = !options ?
method :
options === true || typeof options === "number" ?
defaultEffect :
options.effect || defaultEffect;
options = options || {};
if (typeof options === "number") {
options = { duration: options };
}
hasOptions = !$.isEmptyObject(options);
options.complete = callback;
if (options.delay) {
element.delay(options.delay);
}
if (hasOptions && $.effects && $.effects.effect[ effectName ]) {
element[ method ](options);
} else if (effectName !== method && element[ effectName ]) {
element[ effectName ](options.duration, options.easing, callback);
} else {
element.queue(function (next) {
$(this)[ method ]();
if (callback) {
callback.call(element[ 0 ]);
}
next();
});
}
};
});
})(jQuery);
(function ($, undefined) {
$.widget("mobile.widget", {
// decorate the parent _createWidget to trigger `widgetinit` for users
// who wish to do post post `widgetcreate` alterations/additions
//
// TODO create a pull request for jquery ui to trigger this event
// in the original _createWidget
_createWidget: function () {
$.Widget.prototype._createWidget.apply(this, arguments);
this._trigger('init');
},
_getCreateOptions: function () {
var elem = this.element,
options = {};
$.each(this.options, function (option) {
var value = elem.jqmData(option.replace(/[A-Z]/g, function (c) {
return "-" + c.toLowerCase();
})
);
if (value !== undefined) {
options[ option ] = value;
}
});
return options;
},
enhanceWithin: function (target, useKeepNative) {
this.enhance($(this.options.initSelector, $(target)), useKeepNative);
},
enhance: function (targets, useKeepNative) {
var page, keepNative, $widgetElements = $(targets), self = this;
// if ignoreContentEnabled is set to true the framework should
// only enhance the selected elements when they do NOT have a
// parent with the data-namespace-ignore attribute
$widgetElements = $.mobile.enhanceable($widgetElements);
if (useKeepNative && $widgetElements.length) {
// TODO remove dependency on the page widget for the keepNative.
// Currently the keepNative value is defined on the page prototype so
// the method is as well
page = $.mobile.closestPageData($widgetElements);
keepNative = ( page && page.keepNativeSelector()) || "";
$widgetElements = $widgetElements.not(keepNative);
}
$widgetElements[ this.widgetName ]();
},
raise: function (msg) {
throw "Widget [" + this.widgetName + "]: " + msg;
}
});
})(jQuery);
(function ($, window) {
// DEPRECATED
// NOTE global mobile object settings
$.extend($.mobile, {
// DEPRECATED Should the text be visble in the loading message?
loadingMessageTextVisible: undefined,
// DEPRECATED When the text is visible, what theme does the loading box use?
loadingMessageTheme: undefined,
// DEPRECATED default message setting
loadingMessage: undefined,
// DEPRECATED
// Turn on/off page loading message. Theme doubles as an object argument
// with the following shape: { theme: '', text: '', html: '', textVisible: '' }
// NOTE that the $.mobile.loading* settings and params past the first are deprecated
showPageLoadingMsg: function (theme, msgText, textonly) {
$.mobile.loading('show', theme, msgText, textonly);
},
// DEPRECATED
hidePageLoadingMsg: function () {
$.mobile.loading('hide');
},
loading: function () {
this.loaderWidget.loader.apply(this.loaderWidget, arguments);
}
});
// TODO move loader class down into the widget settings
var loaderClass = "ui-loader", $html = $("html"), $window = $.mobile.window;
$.widget("mobile.loader", {
// NOTE if the global config settings are defined they will override these
// options
options: {
// the theme for the loading message
theme: "a",
// whether the text in the loading message is shown
textVisible: false,
// custom html for the inner content of the loading message
html: "",
// the text to be displayed when the popup is shown
text: "loading"
},
defaultHtml: "<div class='" + loaderClass + "'>" +
"<span class='ui-icon ui-icon-loading'></span>" +
"<h1></h1>" +
"</div>",
// For non-fixed supportin browsers. Position at y center (if scrollTop supported), above the activeBtn (if defined), or just 100px from top
fakeFixLoader: function () {
var activeBtn = $("." + $.mobile.activeBtnClass).first();
this.element
.css({
top: $.support.scrollTop && $window.scrollTop() + $window.height() / 2 ||
activeBtn.length && activeBtn.offset().top || 100
});
},
// check position of loader to see if it appears to be "fixed" to center
// if not, use abs positioning
checkLoaderPosition: function () {
var offset = this.element.offset(),
scrollTop = $window.scrollTop(),
screenHeight = $.mobile.getScreenHeight();
if (offset.top < scrollTop || ( offset.top - scrollTop ) > screenHeight) {
this.element.addClass("ui-loader-fakefix");
this.fakeFixLoader();
$window
.unbind("scroll", this.checkLoaderPosition)
.bind("scroll", $.proxy(this.fakeFixLoader, this));
}
},
resetHtml: function () {
this.element.html($(this.defaultHtml).html());
},
// Turn on/off page loading message. Theme doubles as an object argument
// with the following shape: { theme: '', text: '', html: '', textVisible: '' }
// NOTE that the $.mobile.loading* settings and params past the first are deprecated
// TODO sweet jesus we need to break some of this out
show: function (theme, msgText, textonly) {
var textVisible, message, $header, loadSettings;
this.resetHtml();
// use the prototype options so that people can set them globally at
// mobile init. Consistency, it's what's for dinner
if ($.type(theme) === "object") {
loadSettings = $.extend({}, this.options, theme);
// prefer object property from the param then the old theme setting
theme = loadSettings.theme || $.mobile.loadingMessageTheme;
} else {
loadSettings = this.options;
// here we prefer the them value passed as a string argument, then
// we prefer the global option because we can't use undefined default
// prototype options, then the prototype option
theme = theme || $.mobile.loadingMessageTheme || loadSettings.theme;
}
// set the message text, prefer the param, then the settings object
// then loading message
message = msgText || $.mobile.loadingMessage || loadSettings.text;
// prepare the dom
$html.addClass("ui-loading");
if ($.mobile.loadingMessage !== false || loadSettings.html) {
// boolean values require a bit more work :P, supports object properties
// and old settings
if ($.mobile.loadingMessageTextVisible !== undefined) {
textVisible = $.mobile.loadingMessageTextVisible;
} else {
textVisible = loadSettings.textVisible;
}
// add the proper css given the options (theme, text, etc)
// Force text visibility if the second argument was supplied, or
// if the text was explicitly set in the object args
this.element.attr("class", loaderClass +
" ui-corner-all ui-body-" + theme +
" ui-loader-" + ( textVisible || msgText || theme.text ? "verbose" : "default" ) +
( loadSettings.textonly || textonly ? " ui-loader-textonly" : "" ));
// TODO verify that jquery.fn.html is ok to use in both cases here
// this might be overly defensive in preventing unknowing xss
// if the html attribute is defined on the loading settings, use that
// otherwise use the fallbacks from above
if (loadSettings.html) {
this.element.html(loadSettings.html);
} else {
this.element.find("h1").text(message);
}
// attach the loader to the DOM
this.element.appendTo($.mobile.pageContainer);
// check that the loader is visible
this.checkLoaderPosition();
// on scroll check the loader position
$window.bind("scroll", $.proxy(this.checkLoaderPosition, this));
}
},
hide: function () {
$html.removeClass("ui-loading");
if ($.mobile.loadingMessage) {
this.element.removeClass("ui-loader-fakefix");
}
$.mobile.window.unbind("scroll", this.fakeFixLoader);
$.mobile.window.unbind("scroll", this.checkLoaderPosition);
}
});
$window.bind('pagecontainercreate', function () {
$.mobile.loaderWidget = $.mobile.loaderWidget || $($.mobile.loader.prototype.defaultHtml).loader();
});
})(jQuery, this);
// Script: jQuery hashchange event
//
// *Version: 1.3, Last updated: 7/21/2010*
//
// Project Home - http://benalman.com/projects/jquery-hashchange-plugin/
// GitHub - http://github.com/cowboy/jquery-hashchange/
// Source - http://github.com/cowboy/jquery-hashchange/raw/master/jquery.ba-hashchange.js
// (Minified) - http://github.com/cowboy/jquery-hashchange/raw/master/jquery.ba-hashchange.min.js (0.8kb gzipped)
//
// About: License
//
// Copyright (c) 2010 "Cowboy" Ben Alman,
// Dual licensed under the MIT and GPL licenses.
// http://benalman.com/about/license/
//
// About: Examples
//
// These working examples, complete with fully commented code, illustrate a few
// ways in which this plugin can be used.
//
// hashchange event - http://benalman.com/code/projects/jquery-hashchange/examples/hashchange/
// document.domain - http://benalman.com/code/projects/jquery-hashchange/examples/document_domain/
//
// About: Support and Testing
//
// Information about what version or versions of jQuery this plugin has been
// tested with, what browsers it has been tested in, and where the unit tests
// reside (so you can test it yourself).
//
// jQuery Versions - 1.2.6, 1.3.2, 1.4.1, 1.4.2
// Browsers Tested - Internet Explorer 6-8, Firefox 2-4, Chrome 5-6, Safari 3.2-5,
// Opera 9.6-10.60, iPhone 3.1, Android 1.6-2.2, BlackBerry 4.6-5.
// Unit Tests - http://benalman.com/code/projects/jquery-hashchange/unit/
//
// About: Known issues
//
// While this jQuery hashchange event implementation is quite stable and
// robust, there are a few unfortunate browser bugs surrounding expected
// hashchange event-based behaviors, independent of any JavaScript
// window.onhashchange abstraction. See the following examples for more
// information:
//
// Chrome: Back Button - http://benalman.com/code/projects/jquery-hashchange/examples/bug-chrome-back-button/
// Firefox: Remote XMLHttpRequest - http://benalman.com/code/projects/jquery-hashchange/examples/bug-firefox-remote-xhr/
// WebKit: Back Button in an Iframe - http://benalman.com/code/projects/jquery-hashchange/examples/bug-webkit-hash-iframe/
// Safari: Back Button from a different domain - http://benalman.com/code/projects/jquery-hashchange/examples/bug-safari-back-from-diff-domain/
//
// Also note that should a browser natively support the window.onhashchange
// event, but not report that it does, the fallback polling loop will be used.
//
// About: Release History
//
// 1.3 - (7/21/2010) Reorganized IE6/7 Iframe code to make it more
// "removable" for mobile-only development. Added IE6/7 document.title
// support. Attempted to make Iframe as hidden as possible by using
// techniques from http://www.paciellogroup.com/blog/?p=604. Added
// support for the "shortcut" format $(window).hashchange( fn ) and
// $(window).hashchange() like jQuery provides for built-in events.
// Renamed jQuery.hashchangeDelay to <jQuery.fn.hashchange.delay> and
// lowered its default value to 50. Added <jQuery.fn.hashchange.domain>
// and <jQuery.fn.hashchange.src> properties plus document-domain.html
// file to address access denied issues when setting document.domain in
// IE6/7.
// 1.2 - (2/11/2010) Fixed a bug where coming back to a page using this plugin
// from a page on another domain would cause an error in Safari 4. Also,
// IE6/7 Iframe is now inserted after the body (this actually works),
// which prevents the page from scrolling when the event is first bound.
// Event can also now be bound before DOM ready, but it won't be usable
// before then in IE6/7.
// 1.1 - (1/21/2010) Incorporated document.documentMode test to fix IE8 bug
// where browser version is incorrectly reported as 8.0, despite
// inclusion of the X-UA-Compatible IE=EmulateIE7 meta tag.
// 1.0 - (1/9/2010) Initial Release. Broke out the jQuery BBQ event.special
// window.onhashchange functionality into a separate plugin for users
// who want just the basic event & back button support, without all the
// extra awesomeness that BBQ provides. This plugin will be included as
// part of jQuery BBQ, but also be available separately.
(function ($, window, undefined) {
// Reused string.
var str_hashchange = 'hashchange',
// Method / object references.
doc = document,
fake_onhashchange,
special = $.event.special,
// Does the browser support window.onhashchange? Note that IE8 running in
// IE7 compatibility mode reports true for 'onhashchange' in window, even
// though the event isn't supported, so also test document.documentMode.
doc_mode = doc.documentMode,
supports_onhashchange = 'on' + str_hashchange in window && ( doc_mode === undefined || doc_mode > 7 );
// Get location.hash (or what you'd expect location.hash to be) sans any
// leading #. Thanks for making this necessary, Firefox!
function get_fragment(url) {
url = url || location.href;
return '#' + url.replace(/^[^#]*#?(.*)$/, '$1');
};
// Method: jQuery.fn.hashchange
//
// Bind a handler to the window.onhashchange event or trigger all bound
// window.onhashchange event handlers. This behavior is consistent with
// jQuery's built-in event handlers.
//
// Usage:
//
// > jQuery(window).hashchange( [ handler ] );
//
// Arguments:
//
// handler - (Function) Optional handler to be bound to the hashchange
// event. This is a "shortcut" for the more verbose form:
// jQuery(window).bind( 'hashchange', handler ). If handler is omitted,
// all bound window.onhashchange event handlers will be triggered. This
// is a shortcut for the more verbose
// jQuery(window).trigger( 'hashchange' ). These forms are described in
// the <hashchange event> section.
//
// Returns:
//
// (jQuery) The initial jQuery collection of elements.
// Allow the "shortcut" format $(elem).hashchange( fn ) for binding and
// $(elem).hashchange() for triggering, like jQuery does for built-in events.
$.fn[ str_hashchange ] = function (fn) {
return fn ? this.bind(str_hashchange, fn) : this.trigger(str_hashchange);
};
// Property: jQuery.fn.hashchange.delay
//
// The numeric interval (in milliseconds) at which the <hashchange event>
// polling loop executes. Defaults to 50.
// Property: jQuery.fn.hashchange.domain
//
// If you're setting document.domain in your JavaScript, and you want hash
// history to work in IE6/7, not only must this property be set, but you must
// also set document.domain BEFORE jQuery is loaded into the page. This
// property is only applicable if you are supporting IE6/7 (or IE8 operating
// in "IE7 compatibility" mode).
//
// In addition, the <jQuery.fn.hashchange.src> property must be set to the
// path of the included "document-domain.html" file, which can be renamed or
// modified if necessary (note that the document.domain specified must be the
// same in both your main JavaScript as well as in this file).
//
// Usage:
//
// jQuery.fn.hashchange.domain = document.domain;
// Property: jQuery.fn.hashchange.src
//
// If, for some reason, you need to specify an Iframe src file (for example,
// when setting document.domain as in <jQuery.fn.hashchange.domain>), you can
// do so using this property. Note that when using this property, history
// won't be recorded in IE6/7 until the Iframe src file loads. This property
// is only applicable if you are supporting IE6/7 (or IE8 operating in "IE7
// compatibility" mode).
//
// Usage:
//
// jQuery.fn.hashchange.src = 'path/to/file.html';
$.fn[ str_hashchange ].delay = 50;
/*
$.fn[ str_hashchange ].domain = null;
$.fn[ str_hashchange ].src = null;
*/
// Event: hashchange event
//
// Fired when location.hash changes. In browsers that support it, the native
// HTML5 window.onhashchange event is used, otherwise a polling loop is
// initialized, running every <jQuery.fn.hashchange.delay> milliseconds to
// see if the hash has changed. In IE6/7 (and IE8 operating in "IE7
// compatibility" mode), a hidden Iframe is created to allow the back button
// and hash-based history to work.
//
// Usage as described in <jQuery.fn.hashchange>:
//
// > // Bind an event handler.
// > jQuery(window).hashchange( function(e) {
// > var hash = location.hash;
// > ...
// > });
// >
// > // Manually trigger the event handler.
// > jQuery(window).hashchange();
//
// A more verbose usage that allows for event namespacing:
//
// > // Bind an event handler.
// > jQuery(window).bind( 'hashchange', function(e) {
// > var hash = location.hash;
// > ...
// > });
// >
// > // Manually trigger the event handler.
// > jQuery(window).trigger( 'hashchange' );
//
// Additional Notes:
//
// * The polling loop and Iframe are not created until at least one handler
// is actually bound to the 'hashchange' event.
// * If you need the bound handler(s) to execute immediately, in cases where
// a location.hash exists on page load, via bookmark or page refresh for
// example, use jQuery(window).hashchange() or the more verbose
// jQuery(window).trigger( 'hashchange' ).
// * The event can be bound before DOM ready, but since it won't be usable
// before then in IE6/7 (due to the necessary Iframe), recommended usage is
// to bind it inside a DOM ready handler.
// Override existing $.event.special.hashchange methods (allowing this plugin
// to be defined after jQuery BBQ in BBQ's source code).
special[ str_hashchange ] = $.extend(special[ str_hashchange ], {
// Called only when the first 'hashchange' event is bound to window.
setup: function () {
// If window.onhashchange is supported natively, there's nothing to do..
if (supports_onhashchange) {
return false;
}
// Otherwise, we need to create our own. And we don't want to call this
// until the user binds to the event, just in case they never do, since it
// will create a polling loop and possibly even a hidden Iframe.
$(fake_onhashchange.start);
},
// Called only when the last 'hashchange' event is unbound from window.
teardown: function () {
// If window.onhashchange is supported natively, there's nothing to do..
if (supports_onhashchange) {
return false;
}
// Otherwise, we need to stop ours (if possible).
$(fake_onhashchange.stop);
}
});
// fake_onhashchange does all the work of triggering the window.onhashchange
// event for browsers that don't natively support it, including creating a
// polling loop to watch for hash changes and in IE 6/7 creating a hidden
// Iframe to enable back and forward.
fake_onhashchange = (function () {
var self = {},
timeout_id,
// Remember the initial hash so it doesn't get triggered immediately.
last_hash = get_fragment(),
fn_retval = function (val) {
return val;
},
history_set = fn_retval,
history_get = fn_retval;
// Start the polling loop.
self.start = function () {
timeout_id || poll();
};
// Stop the polling loop.
self.stop = function () {
timeout_id && clearTimeout(timeout_id);
timeout_id = undefined;
};
// This polling loop checks every $.fn.hashchange.delay milliseconds to see
// if location.hash has changed, and triggers the 'hashchange' event on
// window when necessary.
function poll() {
var hash = get_fragment(),
history_hash = history_get(last_hash);
if (hash !== last_hash) {
history_set(last_hash = hash, history_hash);
$(window).trigger(str_hashchange);
} else if (history_hash !== last_hash) {
location.href = location.href.replace(/#.*/, '') + history_hash;
}
timeout_id = setTimeout(poll, $.fn[ str_hashchange ].delay);
};
// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
// vvvvvvvvvvvvvvvvvvv REMOVE IF NOT SUPPORTING IE6/7/8 vvvvvvvvvvvvvvvvvvv
// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
window.attachEvent && !window.addEventListener && !supports_onhashchange && (function () {
// Not only do IE6/7 need the "magical" Iframe treatment, but so does IE8
// when running in "IE7 compatibility" mode.
var iframe,
iframe_src;
// When the event is bound and polling starts in IE 6/7, create a hidden
// Iframe for history handling.
self.start = function () {
if (!iframe) {
iframe_src = $.fn[ str_hashchange ].src;
iframe_src = iframe_src && iframe_src + get_fragment();
// Create hidden Iframe. Attempt to make Iframe as hidden as possible
// by using techniques from http://www.paciellogroup.com/blog/?p=604.
iframe = $('<iframe tabindex="-1" title="empty"/>').hide()
// When Iframe has completely loaded, initialize the history and
// start polling.
.one('load', function () {
iframe_src || history_set(get_fragment());
poll();
})
// Load Iframe src if specified, otherwise nothing.
.attr('src', iframe_src || 'javascript:0')
// Append Iframe after the end of the body to prevent unnecessary
// initial page scrolling (yes, this works).
.insertAfter('body')[0].contentWindow;
// Whenever `document.title` changes, update the Iframe's title to
// prettify the back/next history menu entries. Since IE sometimes
// errors with "Unspecified error" the very first time this is set
// (yes, very useful) wrap this with a try/catch block.
doc.onpropertychange = function () {
try {
if (event.propertyName === 'title') {
iframe.document.title = doc.title;
}
} catch (e) {
}
};
}
};
// Override the "stop" method since an IE6/7 Iframe was created. Even
// if there are no longer any bound event handlers, the polling loop
// is still necessary for back/next to work at all!
self.stop = fn_retval;
// Get history by looking at the hidden Iframe's location.hash.
history_get = function () {
return get_fragment(iframe.location.href);
};
// Set a new history item by opening and then closing the Iframe
// document, *then* setting its location.hash. If document.domain has
// been set, update that as well.
history_set = function (hash, history_hash) {
var iframe_doc = iframe.document,
domain = $.fn[ str_hashchange ].domain;
if (hash !== history_hash) {
// Update Iframe with any initial `document.title` that might be set.
iframe_doc.title = doc.title;
// Opening the Iframe's document after it has been closed is what
// actually adds a history entry.
iframe_doc.open();
// Set document.domain for the Iframe document as well, if necessary.
domain && iframe_doc.write('<script>document.domain="' + domain + '"</script>');
iframe_doc.close();
// Update the Iframe's hash, for great justice.
iframe.location.hash = hash;
}
};
})();
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// ^^^^^^^^^^^^^^^^^^^ REMOVE IF NOT SUPPORTING IE6/7/8 ^^^^^^^^^^^^^^^^^^^
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
return self;
})();
})(jQuery, this);
(function ($, undefined) {
/*! matchMedia() polyfill - Test a CSS media type/query in JS. Authors & copyright (c) 2012: Scott Jehl, Paul Irish, Nicholas Zakas. Dual MIT/BSD license */
window.matchMedia = window.matchMedia || (function (doc, undefined) {
var bool,
docElem = doc.documentElement,
refNode = docElem.firstElementChild || docElem.firstChild,
// fakeBody required for <FF4 when executed in <head>
fakeBody = doc.createElement("body"),
div = doc.createElement("div");
div.id = "mq-test-1";
div.style.cssText = "position:absolute;top:-100em";
fakeBody.style.background = "none";
fakeBody.appendChild(div);
return function (q) {
div.innerHTML = "­<style media=\"" + q + "\"> #mq-test-1 { width: 42px; }</style>";
docElem.insertBefore(fakeBody, refNode);
bool = div.offsetWidth === 42;
docElem.removeChild(fakeBody);
return {
matches: bool,
media: q
};
};
}(document));
// $.mobile.media uses matchMedia to return a boolean.
$.mobile.media = function (q) {
return window.matchMedia(q).matches;
};
})(jQuery);
(function ($, undefined) {
var support = {
touch: "ontouchend" in document
};
$.mobile.support = $.mobile.support || {};
$.extend($.support, support);
$.extend($.mobile.support, support);
}(jQuery));
(function ($, undefined) {
$.extend($.support, {
orientation: "orientation" in window && "onorientationchange" in window
});
}(jQuery));
(function ($, undefined) {
// thx Modernizr
function propExists(prop) {
var uc_prop = prop.charAt(0).toUpperCase() + prop.substr(1),
props = ( prop + " " + vendors.join(uc_prop + " ") + uc_prop ).split(" ");
for (var v in props) {
if (fbCSS[ props[ v ] ] !== undefined) {
return true;
}
}
}
var fakeBody = $("<body>").prependTo("html"),
fbCSS = fakeBody[ 0 ].style,
vendors = [ "Webkit", "Moz", "O" ],
webos = "palmGetResource" in window, //only used to rule out scrollTop
opera = window.opera,
operamini = window.operamini && ({}).toString.call(window.operamini) === "[object OperaMini]",
bb = window.blackberry && !propExists("-webkit-transform"); //only used to rule out box shadow, as it's filled opaque on BB 5 and lower
function validStyle(prop, value, check_vend) {
var div = document.createElement('div'),
uc = function (txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1);
},
vend_pref = function (vend) {
if (vend === "") {
return "";
} else {
return "-" + vend.charAt(0).toLowerCase() + vend.substr(1) + "-";
}
},
check_style = function (vend) {
var vend_prop = vend_pref(vend) + prop + ": " + value + ";",
uc_vend = uc(vend),
propStyle = uc_vend + ( uc_vend === "" ? prop : uc(prop) );
div.setAttribute("style", vend_prop);
if (!!div.style[ propStyle ]) {
ret = true;
}
},
check_vends = check_vend ? check_vend : vendors,
ret;
for (var i = 0; i < check_vends.length; i++) {
check_style(check_vends[i]);
}
return !!ret;
}
function transform3dTest() {
var mqProp = "transform-3d",
// Because the `translate3d` test below throws false positives in Android:
ret = $.mobile.media("(-" + vendors.join("-" + mqProp + "),(-") + "-" + mqProp + "),(" + mqProp + ")");
if (ret) {
return !!ret;
}
var el = document.createElement("div"),
transforms = {
// We’re omitting Opera for the time being; MS uses unprefixed.
'MozTransform': '-moz-transform',
'transform': 'transform'
};
fakeBody.append(el);
for (var t in transforms) {
if (el.style[ t ] !== undefined) {
el.style[ t ] = 'translate3d( 100px, 1px, 1px )';
ret = window.getComputedStyle(el).getPropertyValue(transforms[ t ]);
}
}
return ( !!ret && ret !== "none" );
}
// Test for dynamic-updating base tag support ( allows us to avoid href,src attr rewriting )
function baseTagTest() {
var fauxBase = location.protocol + "//" + location.host + location.pathname + "ui-dir/",
base = $("head base"),
fauxEle = null,
href = "",
link, rebase;
if (!base.length) {
base = fauxEle = $("<base>", { "href": fauxBase }).appendTo("head");
} else {
href = base.attr("href");
}
link = $("<a href='testurl' />").prependTo(fakeBody);
rebase = link[ 0 ].href;
base[ 0 ].href = href || location.pathname;
if (fauxEle) {
fauxEle.remove();
}
return rebase.indexOf(fauxBase) === 0;
}
// Thanks Modernizr
function cssPointerEventsTest() {
var element = document.createElement('x'),
documentElement = document.documentElement,
getComputedStyle = window.getComputedStyle,
supports;
if (!( 'pointerEvents' in element.style )) {
return false;
}
element.style.pointerEvents = 'auto';
element.style.pointerEvents = 'x';
documentElement.appendChild(element);
supports = getComputedStyle &&
getComputedStyle(element, '').pointerEvents === 'auto';
documentElement.removeChild(element);
return !!supports;
}
function boundingRect() {
var div = document.createElement("div");
return typeof div.getBoundingClientRect !== "undefined";
}
// non-UA-based IE version check by James Padolsey, modified by jdalton - from http://gist.github.com/527683
// allows for inclusion of IE 6+, including Windows Mobile 7
$.extend($.mobile, { browser: {} });
$.mobile.browser.oldIE = (function () {
var v = 3,
div = document.createElement("div"),
a = div.all || [];
do {
div.innerHTML = "<!--[if gt IE " + ( ++v ) + "]><br><![endif]-->";
} while (a[0]);
return v > 4 ? v : !v;
})();
function fixedPosition() {
var w = window,
ua = navigator.userAgent,
platform = navigator.platform,
// Rendering engine is Webkit, and capture major version
wkmatch = ua.match(/AppleWebKit\/([0-9]+)/),
wkversion = !!wkmatch && wkmatch[ 1 ],
ffmatch = ua.match(/Fennec\/([0-9]+)/),
ffversion = !!ffmatch && ffmatch[ 1 ],
operammobilematch = ua.match(/Opera Mobi\/([0-9]+)/),
omversion = !!operammobilematch && operammobilematch[ 1 ];
if (
// iOS 4.3 and older : Platform is iPhone/Pad/Touch and Webkit version is less than 534 (ios5)
( ( platform.indexOf("iPhone") > -1 || platform.indexOf("iPad") > -1 || platform.indexOf("iPod") > -1 ) && wkversion && wkversion < 534 ) ||
// Opera Mini
( w.operamini && ({}).toString.call(w.operamini) === "[object OperaMini]" ) ||
( operammobilematch && omversion < 7458 ) ||
//Android lte 2.1: Platform is Android and Webkit version is less than 533 (Android 2.2)
( ua.indexOf("Android") > -1 && wkversion && wkversion < 533 ) ||
// Firefox Mobile before 6.0 -
( ffversion && ffversion < 6 ) ||
// WebOS less than 3
( "palmGetResource" in window && wkversion && wkversion < 534 ) ||
// MeeGo
( ua.indexOf("MeeGo") > -1 && ua.indexOf("NokiaBrowser/8.5.0") > -1 )) {
return false;
}
return true;
}
$.extend($.support, {
cssTransitions: "WebKitTransitionEvent" in window ||
validStyle('transition', 'height 100ms linear', [ "Webkit", "Moz", "" ]) && !$.mobile.browser.oldIE && !opera,
// Note, Chrome for iOS has an extremely quirky implementation of popstate.
// We've chosen to take the shortest path to a bug fix here for issue #5426
// See the following link for information about the regex chosen
// https://developers.google.com/chrome/mobile/docs/user-agent#chrome_for_ios_user-agent
pushState: "pushState" in history &&
"replaceState" in history &&
// When running inside a FF iframe, calling replaceState causes an error
!( window.navigator.userAgent.indexOf("Firefox") >= 0 && window.top !== window ) &&
( window.navigator.userAgent.search(/CriOS/) === -1 ),
mediaquery: $.mobile.media("only all"),
cssPseudoElement: !!propExists("content"),
touchOverflow: !!propExists("overflowScrolling"),
cssTransform3d: transform3dTest(),
boxShadow: !!propExists("boxShadow") && !bb,
fixedPosition: fixedPosition(),
scrollTop: ("pageXOffset" in window ||
"scrollTop" in document.documentElement ||
"scrollTop" in fakeBody[ 0 ]) && !webos && !operamini,
dynamicBaseTag: baseTagTest(),
cssPointerEvents: cssPointerEventsTest(),
boundingRect: boundingRect()
});
fakeBody.remove();
// $.mobile.ajaxBlacklist is used to override ajaxEnabled on platforms that have known conflicts with hash history updates (BB5, Symbian)
// or that generally work better browsing in regular http for full page refreshes (Opera Mini)
// Note: This detection below is used as a last resort.
// We recommend only using these detection methods when all other more reliable/forward-looking approaches are not possible
var nokiaLTE7_3 = (function () {
var ua = window.navigator.userAgent;
//The following is an attempt to match Nokia browsers that are running Symbian/s60, with webkit, version 7.3 or older
return ua.indexOf("Nokia") > -1 &&
( ua.indexOf("Symbian/3") > -1 || ua.indexOf("Series60/5") > -1 ) &&
ua.indexOf("AppleWebKit") > -1 &&
ua.match(/(BrowserNG|NokiaBrowser)\/7\.[0-3]/);
})();
// Support conditions that must be met in order to proceed
// default enhanced qualifications are media query support OR IE 7+
$.mobile.gradeA = function () {
return ( $.support.mediaquery || $.mobile.browser.oldIE && $.mobile.browser.oldIE >= 7 ) && ( $.support.boundingRect || $.fn.jquery.match(/1\.[0-7+]\.[0-9+]?/) !== null );
};
$.mobile.ajaxBlacklist =
// BlackBerry browsers, pre-webkit
window.blackberry && !window.WebKitPoint ||
// Opera Mini
operamini ||
// Symbian webkits pre 7.3
nokiaLTE7_3;
// Lastly, this workaround is the only way we've found so far to get pre 7.3 Symbian webkit devices
// to render the stylesheets when they're referenced before this script, as we'd recommend doing.
// This simply reappends the CSS in place, which for some reason makes it apply
if (nokiaLTE7_3) {
$(function () {
$("head link[rel='stylesheet']").attr("rel", "alternate stylesheet").attr("rel", "stylesheet");
});
}
// For ruling out shadows via css
if (!$.support.boxShadow) {
$("html").addClass("ui-mobile-nosupport-boxshadow");
}
})(jQuery);
(function ($, undefined) {
var $win = $.mobile.window, self, history;
$.event.special.navigate = self = {
bound: false,
pushStateEnabled: true,
originalEventName: undefined,
// If pushstate support is present and push state support is defined to
// be true on the mobile namespace.
isPushStateEnabled: function () {
return $.support.pushState &&
$.mobile.pushStateEnabled === true &&
this.isHashChangeEnabled();
},
// !! assumes mobile namespace is present
isHashChangeEnabled: function () {
return $.mobile.hashListeningEnabled === true;
},
// TODO a lot of duplication between popstate and hashchange
popstate: function (event) {
var newEvent = new $.Event("navigate"),
beforeNavigate = new $.Event("beforenavigate"),
state = event.originalEvent.state || {},
href = location.href;
$win.trigger(beforeNavigate);
if (beforeNavigate.isDefaultPrevented()) {
return;
}
if (event.historyState) {
$.extend(state, event.historyState);
}
// Make sure the original event is tracked for the end
// user to inspect incase they want to do something special
newEvent.originalEvent = event;
// NOTE we let the current stack unwind because any assignment to
// location.hash will stop the world and run this event handler. By
// doing this we create a similar behavior to hashchange on hash
// assignment
setTimeout(function () {
$win.trigger(newEvent, {
state: state
});
}, 0);
},
hashchange: function (event, data) {
var newEvent = new $.Event("navigate"),
beforeNavigate = new $.Event("beforenavigate");
$win.trigger(beforeNavigate);
if (beforeNavigate.isDefaultPrevented()) {
return;
}
// Make sure the original event is tracked for the end
// user to inspect incase they want to do something special
newEvent.originalEvent = event;
// Trigger the hashchange with state provided by the user
// that altered the hash
$win.trigger(newEvent, {
// Users that want to fully normalize the two events
// will need to do history management down the stack and
// add the state to the event before this binding is fired
// TODO consider allowing for the explicit addition of callbacks
// to be fired before this value is set to avoid event timing issues
state: event.hashchangeState || {}
});
},
// TODO We really only want to set this up once
// but I'm not clear if there's a beter way to achieve
// this with the jQuery special event structure
setup: function (data, namespaces) {
if (self.bound) {
return;
}
self.bound = true;
if (self.isPushStateEnabled()) {
self.originalEventName = "popstate";
$win.bind("popstate.navigate", self.popstate);
} else if (self.isHashChangeEnabled()) {
self.originalEventName = "hashchange";
$win.bind("hashchange.navigate", self.hashchange);
}
}
};
})(jQuery);
(function ($, undefined) {
var path, documentBase, $base, dialogHashKey = "&ui-state=dialog";
$.mobile.path = path = {
uiStateKey: "&ui-state",
// This scary looking regular expression parses an absolute URL or its relative
// variants (protocol, site, document, query, and hash), into the various
// components (protocol, host, path, query, fragment, etc that make up the
// URL as well as some other commonly used sub-parts. When used with RegExp.exec()
// or String.match, it parses the URL into a results array that looks like this:
//
// [0]: http://jblas:[email protected]:8080/mail/inbox?msg=1234&type=unread#msg-content
// [1]: http://jblas:[email protected]:8080/mail/inbox?msg=1234&type=unread
// [2]: http://jblas:[email protected]:8080/mail/inbox
// [3]: http://jblas:[email protected]:8080
// [4]: http:
// [5]: //
// [6]: jblas:[email protected]:8080
// [7]: jblas:password
// [8]: jblas
// [9]: password
// [10]: mycompany.com:8080
// [11]: mycompany.com
// [12]: 8080
// [13]: /mail/inbox
// [14]: /mail/
// [15]: inbox
// [16]: ?msg=1234&type=unread
// [17]: #msg-content
//
urlParseRE: /^\s*(((([^:\/#\?]+:)?(?:(\/\/)((?:(([^:@\/#\?]+)(?:\:([^:@\/#\?]+))?)@)?(([^:\/#\?\]\[]+|\[[^\/\]@#?]+\])(?:\:([0-9]+))?))?)?)?((\/?(?:[^\/\?#]+\/+)*)([^\?#]*)))?(\?[^#]+)?)(#.*)?/,
// Abstraction to address xss (Issue #4787) by removing the authority in
// browsers that auto decode it. All references to location.href should be
// replaced with a call to this method so that it can be dealt with properly here
getLocation: function (url) {
var uri = url ? this.parseUrl(url) : location,
hash = this.parseUrl(url || location.href).hash;
// mimic the browser with an empty string when the hash is empty
hash = hash === "#" ? "" : hash;
// Make sure to parse the url or the location object for the hash because using location.hash
// is autodecoded in firefox, the rest of the url should be from the object (location unless
// we're testing) to avoid the inclusion of the authority
return uri.protocol + "//" + uri.host + uri.pathname + uri.search + hash;
},
parseLocation: function () {
return this.parseUrl(this.getLocation());
},
//Parse a URL into a structure that allows easy access to
//all of the URL components by name.
parseUrl: function (url) {
// If we're passed an object, we'll assume that it is
// a parsed url object and just return it back to the caller.
if ($.type(url) === "object") {
return url;
}
var matches = path.urlParseRE.exec(url || "") || [];
// Create an object that allows the caller to access the sub-matches
// by name. Note that IE returns an empty string instead of undefined,
// like all other browsers do, so we normalize everything so its consistent
// no matter what browser we're running on.
return {
href: matches[ 0 ] || "",
hrefNoHash: matches[ 1 ] || "",
hrefNoSearch: matches[ 2 ] || "",
domain: matches[ 3 ] || "",
protocol: matches[ 4 ] || "",
doubleSlash: matches[ 5 ] || "",
authority: matches[ 6 ] || "",
username: matches[ 8 ] || "",
password: matches[ 9 ] || "",
host: matches[ 10 ] || "",
hostname: matches[ 11 ] || "",
port: matches[ 12 ] || "",
pathname: matches[ 13 ] || "",
directory: matches[ 14 ] || "",
filename: matches[ 15 ] || "",
search: matches[ 16 ] || "",
hash: matches[ 17 ] || ""
};
},
//Turn relPath into an asbolute path. absPath is
//an optional absolute path which describes what
//relPath is relative to.
makePathAbsolute: function (relPath, absPath) {
if (relPath && relPath.charAt(0) === "/") {
return relPath;
}
relPath = relPath || "";
absPath = absPath ? absPath.replace(/^\/|(\/[^\/]*|[^\/]+)$/g, "") : "";
var absStack = absPath ? absPath.split("/") : [],
relStack = relPath.split("/");
for (var i = 0; i < relStack.length; i++) {
var d = relStack[ i ];
switch (d) {
case ".":
break;
case "..":
if (absStack.length) {
absStack.pop();
}
break;
default:
absStack.push(d);
break;
}
}
return "/" + absStack.join("/");
},
//Returns true if both urls have the same domain.
isSameDomain: function (absUrl1, absUrl2) {
return path.parseUrl(absUrl1).domain === path.parseUrl(absUrl2).domain;
},
//Returns true for any relative variant.
isRelativeUrl: function (url) {
// All relative Url variants have one thing in common, no protocol.
return path.parseUrl(url).protocol === "";
},
//Returns true for an absolute url.
isAbsoluteUrl: function (url) {
return path.parseUrl(url).protocol !== "";
},
//Turn the specified realtive URL into an absolute one. This function
//can handle all relative variants (protocol, site, document, query, fragment).
makeUrlAbsolute: function (relUrl, absUrl) {
if (!path.isRelativeUrl(relUrl)) {
return relUrl;
}
if (absUrl === undefined) {
absUrl = this.documentBase;
}
var relObj = path.parseUrl(relUrl),
absObj = path.parseUrl(absUrl),
protocol = relObj.protocol || absObj.protocol,
doubleSlash = relObj.protocol ? relObj.doubleSlash : ( relObj.doubleSlash || absObj.doubleSlash ),
authority = relObj.authority || absObj.authority,
hasPath = relObj.pathname !== "",
pathname = path.makePathAbsolute(relObj.pathname || absObj.filename, absObj.pathname),
search = relObj.search || ( !hasPath && absObj.search ) || "",
hash = relObj.hash;
return protocol + doubleSlash + authority + pathname + search + hash;
},
//Add search (aka query) params to the specified url.
addSearchParams: function (url, params) {
var u = path.parseUrl(url),
p = ( typeof params === "object" ) ? $.param(params) : params,
s = u.search || "?";
return u.hrefNoSearch + s + ( s.charAt(s.length - 1) !== "?" ? "&" : "" ) + p + ( u.hash || "" );
},
convertUrlToDataUrl: function (absUrl) {
var u = path.parseUrl(absUrl);
if (path.isEmbeddedPage(u)) {
// For embedded pages, remove the dialog hash key as in getFilePath(),
// and remove otherwise the Data Url won't match the id of the embedded Page.
return u.hash
.split(dialogHashKey)[0]
.replace(/^#/, "")
.replace(/\?.*$/, "");
} else if (path.isSameDomain(u, this.documentBase)) {
return u.hrefNoHash.replace(this.documentBase.domain, "").split(dialogHashKey)[0];
}
return window.decodeURIComponent(absUrl);
},
//get path from current hash, or from a file path
get: function (newPath) {
if (newPath === undefined) {
newPath = path.parseLocation().hash;
}
return path.stripHash(newPath).replace(/[^\/]*\.[^\/*]+$/, '');
},
//set location hash to path
set: function (path) {
location.hash = path;
},
//test if a given url (string) is a path
//NOTE might be exceptionally naive
isPath: function (url) {
return ( /\// ).test(url);
},
//return a url path with the window's location protocol/hostname/pathname removed
clean: function (url) {
return url.replace(this.documentBase.domain, "");
},
//just return the url without an initial #
stripHash: function (url) {
return url.replace(/^#/, "");
},
stripQueryParams: function (url) {
return url.replace(/\?.*$/, "");
},
//remove the preceding hash, any query params, and dialog notations
cleanHash: function (hash) {
return path.stripHash(hash.replace(/\?.*$/, "").replace(dialogHashKey, ""));
},
isHashValid: function (hash) {
return ( /^#[^#]+$/ ).test(hash);
},
//check whether a url is referencing the same domain, or an external domain or different protocol
//could be mailto, etc
isExternal: function (url) {
var u = path.parseUrl(url);
return u.protocol && u.domain !== this.documentUrl.domain ? true : false;
},
hasProtocol: function (url) {
return ( /^(:?\w+:)/ ).test(url);
},
isEmbeddedPage: function (url) {
var u = path.parseUrl(url);
//if the path is absolute, then we need to compare the url against
//both the this.documentUrl and the documentBase. The main reason for this
//is that links embedded within external documents will refer to the
//application document, whereas links embedded within the application
//document will be resolved against the document base.
if (u.protocol !== "") {
return ( !this.isPath(u.hash) && u.hash && ( u.hrefNoHash === this.documentUrl.hrefNoHash || ( this.documentBaseDiffers && u.hrefNoHash === this.documentBase.hrefNoHash ) ) );
}
return ( /^#/ ).test(u.href);
},
squash: function (url, resolutionUrl) {
var state, href, cleanedUrl, search, stateIndex,
isPath = this.isPath(url),
uri = this.parseUrl(url),
preservedHash = uri.hash,
uiState = "";
// produce a url against which we can resole the provided path
resolutionUrl = resolutionUrl || (path.isPath(url) ? path.getLocation() : path.getDocumentUrl());
// If the url is anything but a simple string, remove any preceding hash
// eg #foo/bar -> foo/bar
// #foo -> #foo
cleanedUrl = isPath ? path.stripHash(url) : url;
// If the url is a full url with a hash check if the parsed hash is a path
// if it is, strip the #, and use it otherwise continue without change
cleanedUrl = path.isPath(uri.hash) ? path.stripHash(uri.hash) : cleanedUrl;
// Split the UI State keys off the href
stateIndex = cleanedUrl.indexOf(this.uiStateKey);
// store the ui state keys for use
if (stateIndex > -1) {
uiState = cleanedUrl.slice(stateIndex);
cleanedUrl = cleanedUrl.slice(0, stateIndex);
}
// make the cleanedUrl absolute relative to the resolution url
href = path.makeUrlAbsolute(cleanedUrl, resolutionUrl);
// grab the search from the resolved url since parsing from
// the passed url may not yield the correct result
search = this.parseUrl(href).search;
// TODO all this crap is terrible, clean it up
if (isPath) {
// reject the hash if it's a path or it's just a dialog key
if (path.isPath(preservedHash) || preservedHash.replace("#", "").indexOf(this.uiStateKey) === 0) {
preservedHash = "";
}
// Append the UI State keys where it exists and it's been removed
// from the url
if (uiState && preservedHash.indexOf(this.uiStateKey) === -1) {
preservedHash += uiState;
}
// make sure that pound is on the front of the hash
if (preservedHash.indexOf("#") === -1 && preservedHash !== "") {
preservedHash = "#" + preservedHash;
}
// reconstruct each of the pieces with the new search string and hash
href = path.parseUrl(href);
href = href.protocol + "//" + href.host + href.pathname + search + preservedHash;
} else {
href += href.indexOf("#") > -1 ? uiState : "#" + uiState;
}
return href;
},
isPreservableHash: function (hash) {
return hash.replace("#", "").indexOf(this.uiStateKey) === 0;
}
};
path.documentUrl = path.parseLocation();
$base = $("head").find("base");
path.documentBase = $base.length ?
path.parseUrl(path.makeUrlAbsolute($base.attr("href"), path.documentUrl.href)) :
path.documentUrl;
path.documentBaseDiffers = (path.documentUrl.hrefNoHash !== path.documentBase.hrefNoHash);
//return the original document url
path.getDocumentUrl = function (asParsedObject) {
return asParsedObject ? $.extend({}, path.documentUrl) : path.documentUrl.href;
};
//return the original document base url
path.getDocumentBase = function (asParsedObject) {
return asParsedObject ? $.extend({}, path.documentBase) : path.documentBase.href;
};
})(jQuery);
(function ($, undefined) {
var path = $.mobile.path;
$.mobile.History = function (stack, index) {
this.stack = stack || [];
this.activeIndex = index || 0;
};
$.extend($.mobile.History.prototype, {
getActive: function () {
return this.stack[ this.activeIndex ];
},
getLast: function () {
return this.stack[ this.previousIndex ];
},
getNext: function () {
return this.stack[ this.activeIndex + 1 ];
},
getPrev: function () {
return this.stack[ this.activeIndex - 1 ];
},
// addNew is used whenever a new page is added
add: function (url, data) {
data = data || {};
//if there's forward history, wipe it
if (this.getNext()) {
this.clearForward();
}
// if the hash is included in the data make sure the shape
// is consistent for comparison
if (data.hash && data.hash.indexOf("#") === -1) {
data.hash = "#" + data.hash;
}
data.url = url;
this.stack.push(data);
this.activeIndex = this.stack.length - 1;
},
//wipe urls ahead of active index
clearForward: function () {
this.stack = this.stack.slice(0, this.activeIndex + 1);
},
find: function (url, stack, earlyReturn) {
stack = stack || this.stack;
var entry, i, length = stack.length, index;
for (i = 0; i < length; i++) {
entry = stack[i];
if (decodeURIComponent(url) === decodeURIComponent(entry.url) ||
decodeURIComponent(url) === decodeURIComponent(entry.hash)) {
index = i;
if (earlyReturn) {
return index;
}
}
}
return index;
},
closest: function (url) {
var closest, a = this.activeIndex;
// First, take the slice of the history stack before the current index and search
// for a url match. If one is found, we'll avoid avoid looking through forward history
// NOTE the preference for backward history movement is driven by the fact that
// most mobile browsers only have a dedicated back button, and users rarely use
// the forward button in desktop browser anyhow
closest = this.find(url, this.stack.slice(0, a));
// If nothing was found in backward history check forward. The `true`
// value passed as the third parameter causes the find method to break
// on the first match in the forward history slice. The starting index
// of the slice must then be added to the result to get the element index
// in the original history stack :( :(
//
// TODO this is hyper confusing and should be cleaned up (ugh so bad)
if (closest === undefined) {
closest = this.find(url, this.stack.slice(a), true);
closest = closest === undefined ? closest : closest + a;
}
return closest;
},
direct: function (opts) {
var newActiveIndex = this.closest(opts.url), a = this.activeIndex;
// save new page index, null check to prevent falsey 0 result
// record the previous index for reference
if (newActiveIndex !== undefined) {
this.activeIndex = newActiveIndex;
this.previousIndex = a;
}
// invoke callbacks where appropriate
//
// TODO this is also convoluted and confusing
if (newActiveIndex < a) {
( opts.present || opts.back || $.noop )(this.getActive(), 'back');
} else if (newActiveIndex > a) {
( opts.present || opts.forward || $.noop )(this.getActive(), 'forward');
} else if (newActiveIndex === undefined && opts.missing) {
opts.missing(this.getActive());
}
}
});
})(jQuery);
(function ($, undefined) {
var path = $.mobile.path,
initialHref = location.href;
$.mobile.Navigator = function (history) {
this.history = history;
this.ignoreInitialHashChange = true;
$.mobile.window.bind({
"popstate.history": $.proxy(this.popstate, this),
"hashchange.history": $.proxy(this.hashchange, this)
});
};
$.extend($.mobile.Navigator.prototype, {
squash: function (url, data) {
var state, href, hash = path.isPath(url) ? path.stripHash(url) : url;
href = path.squash(url);
// make sure to provide this information when it isn't explicitly set in the
// data object that was passed to the squash method
state = $.extend({
hash: hash,
url: href
}, data);
// replace the current url with the new href and store the state
// Note that in some cases we might be replacing an url with the
// same url. We do this anyways because we need to make sure that
// all of our history entries have a state object associated with
// them. This allows us to work around the case where $.mobile.back()
// is called to transition from an external page to an embedded page.
// In that particular case, a hashchange event is *NOT* generated by the browser.
// Ensuring each history entry has a state object means that onPopState()
// will always trigger our hashchange callback even when a hashchange event
// is not fired.
window.history.replaceState(state, state.title || document.title, href);
return state;
},
hash: function (url, href) {
var parsed, loc, hash;
// Grab the hash for recording. If the passed url is a path
// we used the parsed version of the squashed url to reconstruct,
// otherwise we assume it's a hash and store it directly
parsed = path.parseUrl(url);
loc = path.parseLocation();
if (loc.pathname + loc.search === parsed.pathname + parsed.search) {
// If the pathname and search of the passed url is identical to the current loc
// then we must use the hash. Otherwise there will be no event
// eg, url = "/foo/bar?baz#bang", location.href = "http://example.com/foo/bar?baz"
hash = parsed.hash ? parsed.hash : parsed.pathname + parsed.search;
} else if (path.isPath(url)) {
var resolved = path.parseUrl(href);
// If the passed url is a path, make it domain relative and remove any trailing hash
hash = resolved.pathname + resolved.search + (path.isPreservableHash(resolved.hash) ? resolved.hash.replace("#", "") : "");
} else {
hash = url;
}
return hash;
},
// TODO reconsider name
go: function (url, data, noEvents) {
var state, href, hash, popstateEvent,
isPopStateEvent = $.event.special.navigate.isPushStateEnabled();
// Get the url as it would look squashed on to the current resolution url
href = path.squash(url);
// sort out what the hash sould be from the url
hash = this.hash(url, href);
// Here we prevent the next hash change or popstate event from doing any
// history management. In the case of hashchange we don't swallow it
// if there will be no hashchange fired (since that won't reset the value)
// and will swallow the following hashchange
if (noEvents && hash !== path.stripHash(path.parseLocation().hash)) {
this.preventNextHashChange = noEvents;
}
// IMPORTANT in the case where popstate is supported the event will be triggered
// directly, stopping further execution - ie, interupting the flow of this
// method call to fire bindings at this expression. Below the navigate method
// there is a binding to catch this event and stop its propagation.
//
// We then trigger a new popstate event on the window with a null state
// so that the navigate events can conclude their work properly
//
// if the url is a path we want to preserve the query params that are available on
// the current url.
this.preventHashAssignPopState = true;
window.location.hash = hash;
// If popstate is enabled and the browser triggers `popstate` events when the hash
// is set (this often happens immediately in browsers like Chrome), then the
// this flag will be set to false already. If it's a browser that does not trigger
// a `popstate` on hash assignement or `replaceState` then we need avoid the branch
// that swallows the event created by the popstate generated by the hash assignment
// At the time of this writing this happens with Opera 12 and some version of IE
this.preventHashAssignPopState = false;
state = $.extend({
url: href,
hash: hash,
title: document.title
}, data);
if (isPopStateEvent) {
popstateEvent = new $.Event("popstate");
popstateEvent.originalEvent = {
type: "popstate",
state: null
};
this.squash(url, state);
// Trigger a new faux popstate event to replace the one that we
// caught that was triggered by the hash setting above.
if (!noEvents) {
this.ignorePopState = true;
$.mobile.window.trigger(popstateEvent);
}
}
// record the history entry so that the information can be included
// in hashchange event driven navigate events in a similar fashion to
// the state that's provided by popstate
this.history.add(state.url, state);
},
// This binding is intended to catch the popstate events that are fired
// when execution of the `$.navigate` method stops at window.location.hash = url;
// and completely prevent them from propagating. The popstate event will then be
// retriggered after execution resumes
//
// TODO grab the original event here and use it for the synthetic event in the
// second half of the navigate execution that will follow this binding
popstate: function (event) {
var active, hash, state, closestIndex;
// Partly to support our test suite which manually alters the support
// value to test hashchange. Partly to prevent all around weirdness
if (!$.event.special.navigate.isPushStateEnabled()) {
return;
}
// If this is the popstate triggered by the actual alteration of the hash
// prevent it completely. History is tracked manually
if (this.preventHashAssignPopState) {
this.preventHashAssignPopState = false;
event.stopImmediatePropagation();
return;
}
// if this is the popstate triggered after the `replaceState` call in the go
// method, then simply ignore it. The history entry has already been captured
if (this.ignorePopState) {
this.ignorePopState = false;
return;
}
// If there is no state, and the history stack length is one were
// probably getting the page load popstate fired by browsers like chrome
// avoid it and set the one time flag to false.
// TODO: Do we really need all these conditions? Comparing location hrefs
// should be sufficient.
if (!event.originalEvent.state &&
this.history.stack.length === 1 &&
this.ignoreInitialHashChange) {
this.ignoreInitialHashChange = false;
if (location.href === initialHref) {
event.preventDefault();
return;
}
}
// account for direct manipulation of the hash. That is, we will receive a popstate
// when the hash is changed by assignment, and it won't have a state associated. We
// then need to squash the hash. See below for handling of hash assignment that
// matches an existing history entry
// TODO it might be better to only add to the history stack
// when the hash is adjacent to the active history entry
hash = path.parseLocation().hash;
if (!event.originalEvent.state && hash) {
// squash the hash that's been assigned on the URL with replaceState
// also grab the resulting state object for storage
state = this.squash(hash);
// record the new hash as an additional history entry
// to match the browser's treatment of hash assignment
this.history.add(state.url, state);
// pass the newly created state information
// along with the event
event.historyState = state;
// do not alter history, we've added a new history entry
// so we know where we are
return;
}
// If all else fails this is a popstate that comes from the back or forward buttons
// make sure to set the state of our history stack properly, and record the directionality
this.history.direct({
url: (event.originalEvent.state || {}).url || hash,
// When the url is either forward or backward in history include the entry
// as data on the event object for merging as data in the navigate event
present: function (historyEntry, direction) {
// make sure to create a new object to pass down as the navigate event data
event.historyState = $.extend({}, historyEntry);
event.historyState.direction = direction;
}
});
},
// NOTE must bind before `navigate` special event hashchange binding otherwise the
// navigation data won't be attached to the hashchange event in time for those
// bindings to attach it to the `navigate` special event
// TODO add a check here that `hashchange.navigate` is bound already otherwise it's
// broken (exception?)
hashchange: function (event) {
var history, hash;
// If hashchange listening is explicitly disabled or pushstate is supported
// avoid making use of the hashchange handler.
if (!$.event.special.navigate.isHashChangeEnabled() ||
$.event.special.navigate.isPushStateEnabled()) {
return;
}
// On occasion explicitly want to prevent the next hash from propogating because we only
// with to alter the url to represent the new state do so here
if (this.preventNextHashChange) {
this.preventNextHashChange = false;
event.stopImmediatePropagation();
return;
}
history = this.history;
hash = path.parseLocation().hash;
// If this is a hashchange caused by the back or forward button
// make sure to set the state of our history stack properly
this.history.direct({
url: hash,
// When the url is either forward or backward in history include the entry
// as data on the event object for merging as data in the navigate event
present: function (historyEntry, direction) {
// make sure to create a new object to pass down as the navigate event data
event.hashchangeState = $.extend({}, historyEntry);
event.hashchangeState.direction = direction;
},
// When we don't find a hash in our history clearly we're aiming to go there
// record the entry as new for future traversal
//
// NOTE it's not entirely clear that this is the right thing to do given that we
// can't know the users intention. It might be better to explicitly _not_
// support location.hash assignment in preference to $.navigate calls
// TODO first arg to add should be the href, but it causes issues in identifying
// embeded pages
missing: function () {
history.add(hash, {
hash: hash,
title: document.title
});
}
});
}
});
})(jQuery);
(function ($, undefined) {
// TODO consider queueing navigation activity until previous activities have completed
// so that end users don't have to think about it. Punting for now
// TODO !! move the event bindings into callbacks on the navigate event
$.mobile.navigate = function (url, data, noEvents) {
$.mobile.navigate.navigator.go(url, data, noEvents);
};
// expose the history on the navigate method in anticipation of full integration with
// existing navigation functionalty that is tightly coupled to the history information
$.mobile.navigate.history = new $.mobile.History();
// instantiate an instance of the navigator for use within the $.navigate method
$.mobile.navigate.navigator = new $.mobile.Navigator($.mobile.navigate.history);
var loc = $.mobile.path.parseLocation();
$.mobile.navigate.history.add(loc.href, {hash: loc.hash});
})(jQuery);
// This plugin is an experiment for abstracting away the touch and mouse
// events so that developers don't have to worry about which method of input
// the device their document is loaded on supports.
//
// The idea here is to allow the developer to register listeners for the
// basic mouse events, such as mousedown, mousemove, mouseup, and click,
// and the plugin will take care of registering the correct listeners
// behind the scenes to invoke the listener at the fastest possible time
// for that device, while still retaining the order of event firing in
// the traditional mouse environment, should multiple handlers be registered
// on the same element for different events.
//
// The current version exposes the following virtual events to jQuery bind methods:
// "vmouseover vmousedown vmousemove vmouseup vclick vmouseout vmousecancel"
(function ($, window, document, undefined) {
var dataPropertyName = "virtualMouseBindings",
touchTargetPropertyName = "virtualTouchID",
virtualEventNames = "vmouseover vmousedown vmousemove vmouseup vclick vmouseout vmousecancel".split(" "),
touchEventProps = "clientX clientY pageX pageY screenX screenY".split(" "),
mouseHookProps = $.event.mouseHooks ? $.event.mouseHooks.props : [],
mouseEventProps = $.event.props.concat(mouseHookProps),
activeDocHandlers = {},
resetTimerID = 0,
startX = 0,
startY = 0,
didScroll = false,
clickBlockList = [],
blockMouseTriggers = false,
blockTouchTriggers = false,
eventCaptureSupported = "addEventListener" in document,
$document = $(document),
nextTouchID = 1,
lastTouchID = 0, threshold;
$.vmouse = {
moveDistanceThreshold: 10,
clickDistanceThreshold: 10,
resetTimerDuration: 1500
};
function getNativeEvent(event) {
while (event && typeof event.originalEvent !== "undefined") {
event = event.originalEvent;
}
return event;
}
function createVirtualEvent(event, eventType) {
var t = event.type,
oe, props, ne, prop, ct, touch, i, j, len;
event = $.Event(event);
event.type = eventType;
oe = event.originalEvent;
props = $.event.props;
// addresses separation of $.event.props in to $.event.mouseHook.props and Issue 3280
// https://github.com/jquery/jquery-mobile/issues/3280
if (t.search(/^(mouse|click)/) > -1) {
props = mouseEventProps;
}
// copy original event properties over to the new event
// this would happen if we could call $.event.fix instead of $.Event
// but we don't have a way to force an event to be fixed multiple times
if (oe) {
for (i = props.length, prop; i;) {
prop = props[ --i ];
event[ prop ] = oe[ prop ];
}
}
// make sure that if the mouse and click virtual events are generated
// without a .which one is defined
if (t.search(/mouse(down|up)|click/) > -1 && !event.which) {
event.which = 1;
}
if (t.search(/^touch/) !== -1) {
ne = getNativeEvent(oe);
t = ne.touches;
ct = ne.changedTouches;
touch = ( t && t.length ) ? t[0] : ( ( ct && ct.length ) ? ct[ 0 ] : undefined );
if (touch) {
for (j = 0, len = touchEventProps.length; j < len; j++) {
prop = touchEventProps[ j ];
event[ prop ] = touch[ prop ];
}
}
}
return event;
}
function getVirtualBindingFlags(element) {
var flags = {},
b, k;
while (element) {
b = $.data(element, dataPropertyName);
for (k in b) {
if (b[ k ]) {
flags[ k ] = flags.hasVirtualBinding = true;
}
}
element = element.parentNode;
}
return flags;
}
function getClosestElementWithVirtualBinding(element, eventType) {
var b;
while (element) {
b = $.data(element, dataPropertyName);
if (b && ( !eventType || b[ eventType ] )) {
return element;
}
element = element.parentNode;
}
return null;
}
function enableTouchBindings() {
blockTouchTriggers = false;
}
function disableTouchBindings() {
blockTouchTriggers = true;
}
function enableMouseBindings() {
lastTouchID = 0;
clickBlockList.length = 0;
blockMouseTriggers = false;
// When mouse bindings are enabled, our
// touch bindings are disabled.
disableTouchBindings();
}
function disableMouseBindings() {
// When mouse bindings are disabled, our
// touch bindings are enabled.
enableTouchBindings();
}
function startResetTimer() {
clearResetTimer();
resetTimerID = setTimeout(function () {
resetTimerID = 0;
enableMouseBindings();
}, $.vmouse.resetTimerDuration);
}
function clearResetTimer() {
if (resetTimerID) {
clearTimeout(resetTimerID);
resetTimerID = 0;
}
}
function triggerVirtualEvent(eventType, event, flags) {
var ve;
if (( flags && flags[ eventType ] ) ||
( !flags && getClosestElementWithVirtualBinding(event.target, eventType) )) {
ve = createVirtualEvent(event, eventType);
$(event.target).trigger(ve);
}
return ve;
}
function mouseEventCallback(event) {
var touchID = $.data(event.target, touchTargetPropertyName);
if (!blockMouseTriggers && ( !lastTouchID || lastTouchID !== touchID )) {
var ve = triggerVirtualEvent("v" + event.type, event);
if (ve) {
if (ve.isDefaultPrevented()) {
event.preventDefault();
}
if (ve.isPropagationStopped()) {
event.stopPropagation();
}
if (ve.isImmediatePropagationStopped()) {
event.stopImmediatePropagation();
}
}
}
}
function handleTouchStart(event) {
var touches = getNativeEvent(event).touches,
target, flags;
if (touches && touches.length === 1) {
target = event.target;
flags = getVirtualBindingFlags(target);
if (flags.hasVirtualBinding) {
lastTouchID = nextTouchID++;
$.data(target, touchTargetPropertyName, lastTouchID);
clearResetTimer();
disableMouseBindings();
didScroll = false;
var t = getNativeEvent(event).touches[ 0 ];
startX = t.pageX;
startY = t.pageY;
triggerVirtualEvent("vmouseover", event, flags);
triggerVirtualEvent("vmousedown", event, flags);
}
}
}
function handleScroll(event) {
if (blockTouchTriggers) {
return;
}
if (!didScroll) {
triggerVirtualEvent("vmousecancel", event, getVirtualBindingFlags(event.target));
}
didScroll = true;
startResetTimer();
}
function handleTouchMove(event) {
if (blockTouchTriggers) {
return;
}
var t = getNativeEvent(event).touches[ 0 ],
didCancel = didScroll,
moveThreshold = $.vmouse.moveDistanceThreshold,
flags = getVirtualBindingFlags(event.target);
didScroll = didScroll ||
( Math.abs(t.pageX - startX) > moveThreshold ||
Math.abs(t.pageY - startY) > moveThreshold );
if (didScroll && !didCancel) {
triggerVirtualEvent("vmousecancel", event, flags);
}
triggerVirtualEvent("vmousemove", event, flags);
startResetTimer();
}
function handleTouchEnd(event) {
if (blockTouchTriggers) {
return;
}
disableTouchBindings();
var flags = getVirtualBindingFlags(event.target),
t;
triggerVirtualEvent("vmouseup", event, flags);
if (!didScroll) {
var ve = triggerVirtualEvent("vclick", event, flags);
if (ve && ve.isDefaultPrevented()) {
// The target of the mouse events that follow the touchend
// event don't necessarily match the target used during the
// touch. This means we need to rely on coordinates for blocking
// any click that is generated.
t = getNativeEvent(event).changedTouches[ 0 ];
clickBlockList.push({
touchID: lastTouchID,
x: t.clientX,
y: t.clientY
});
// Prevent any mouse events that follow from triggering
// virtual event notifications.
blockMouseTriggers = true;
}
}
triggerVirtualEvent("vmouseout", event, flags);
didScroll = false;
startResetTimer();
}
function hasVirtualBindings(ele) {
var bindings = $.data(ele, dataPropertyName),
k;
if (bindings) {
for (k in bindings) {
if (bindings[ k ]) {
return true;
}
}
}
return false;
}
function dummyMouseHandler() {
}
function getSpecialEventObject(eventType) {
var realType = eventType.substr(1);
return {
setup: function (data, namespace) {
// If this is the first virtual mouse binding for this element,
// add a bindings object to its data.
if (!hasVirtualBindings(this)) {
$.data(this, dataPropertyName, {});
}
// If setup is called, we know it is the first binding for this
// eventType, so initialize the count for the eventType to zero.
var bindings = $.data(this, dataPropertyName);
bindings[ eventType ] = true;
// If this is the first virtual mouse event for this type,
// register a global handler on the document.
activeDocHandlers[ eventType ] = ( activeDocHandlers[ eventType ] || 0 ) + 1;
if (activeDocHandlers[ eventType ] === 1) {
$document.bind(realType, mouseEventCallback);
}
// Some browsers, like Opera Mini, won't dispatch mouse/click events
// for elements unless they actually have handlers registered on them.
// To get around this, we register dummy handlers on the elements.
$(this).bind(realType, dummyMouseHandler);
// For now, if event capture is not supported, we rely on mouse handlers.
if (eventCaptureSupported) {
// If this is the first virtual mouse binding for the document,
// register our touchstart handler on the document.
activeDocHandlers[ "touchstart" ] = ( activeDocHandlers[ "touchstart" ] || 0) + 1;
if (activeDocHandlers[ "touchstart" ] === 1) {
$document.bind("touchstart", handleTouchStart)
.bind("touchend", handleTouchEnd)
// On touch platforms, touching the screen and then dragging your finger
// causes the window content to scroll after some distance threshold is
// exceeded. On these platforms, a scroll prevents a click event from being
// dispatched, and on some platforms, even the touchend is suppressed. To
// mimic the suppression of the click event, we need to watch for a scroll
// event. Unfortunately, some platforms like iOS don't dispatch scroll
// events until *AFTER* the user lifts their finger (touchend). This means
// we need to watch both scroll and touchmove events to figure out whether
// or not a scroll happenens before the touchend event is fired.
.bind("touchmove", handleTouchMove)
.bind("scroll", handleScroll);
}
}
},
teardown: function (data, namespace) {
// If this is the last virtual binding for this eventType,
// remove its global handler from the document.
--activeDocHandlers[ eventType ];
if (!activeDocHandlers[ eventType ]) {
$document.unbind(realType, mouseEventCallback);
}
if (eventCaptureSupported) {
// If this is the last virtual mouse binding in existence,
// remove our document touchstart listener.
--activeDocHandlers[ "touchstart" ];
if (!activeDocHandlers[ "touchstart" ]) {
$document.unbind("touchstart", handleTouchStart)
.unbind("touchmove", handleTouchMove)
.unbind("touchend", handleTouchEnd)
.unbind("scroll", handleScroll);
}
}
var $this = $(this),
bindings = $.data(this, dataPropertyName);
// teardown may be called when an element was
// removed from the DOM. If this is the case,
// jQuery core may have already stripped the element
// of any data bindings so we need to check it before
// using it.
if (bindings) {
bindings[ eventType ] = false;
}
// Unregister the dummy event handler.
$this.unbind(realType, dummyMouseHandler);
// If this is the last virtual mouse binding on the
// element, remove the binding data from the element.
if (!hasVirtualBindings(this)) {
$this.removeData(dataPropertyName);
}
}
};
}
// Expose our custom events to the jQuery bind/unbind mechanism.
for (var i = 0; i < virtualEventNames.length; i++) {
$.event.special[ virtualEventNames[ i ] ] = getSpecialEventObject(virtualEventNames[ i ]);
}
// Add a capture click handler to block clicks.
// Note that we require event capture support for this so if the device
// doesn't support it, we punt for now and rely solely on mouse events.
if (eventCaptureSupported) {
document.addEventListener("click", function (e) {
var cnt = clickBlockList.length,
target = e.target,
x, y, ele, i, o, touchID;
if (cnt) {
x = e.clientX;
y = e.clientY;
threshold = $.vmouse.clickDistanceThreshold;
// The idea here is to run through the clickBlockList to see if
// the current click event is in the proximity of one of our
// vclick events that had preventDefault() called on it. If we find
// one, then we block the click.
//
// Why do we have to rely on proximity?
//
// Because the target of the touch event that triggered the vclick
// can be different from the target of the click event synthesized
// by the browser. The target of a mouse/click event that is syntehsized
// from a touch event seems to be implementation specific. For example,
// some browsers will fire mouse/click events for a link that is near
// a touch event, even though the target of the touchstart/touchend event
// says the user touched outside the link. Also, it seems that with most
// browsers, the target of the mouse/click event is not calculated until the
// time it is dispatched, so if you replace an element that you touched
// with another element, the target of the mouse/click will be the new
// element underneath that point.
//
// Aside from proximity, we also check to see if the target and any
// of its ancestors were the ones that blocked a click. This is necessary
// because of the strange mouse/click target calculation done in the
// Android 2.1 browser, where if you click on an element, and there is a
// mouse/click handler on one of its ancestors, the target will be the
// innermost child of the touched element, even if that child is no where
// near the point of touch.
ele = target;
while (ele) {
for (i = 0; i < cnt; i++) {
o = clickBlockList[ i ];
touchID = 0;
if (( ele === target && Math.abs(o.x - x) < threshold && Math.abs(o.y - y) < threshold ) ||
$.data(ele, touchTargetPropertyName) === o.touchID) {
// XXX: We may want to consider removing matches from the block list
// instead of waiting for the reset timer to fire.
e.preventDefault();
e.stopPropagation();
return;
}
}
ele = ele.parentNode;
}
}
}, true);
}
})(jQuery, window, document);
(function ($, window, undefined) {
var $document = $(document);
// add new event shortcuts
$.each(( "touchstart touchmove touchend " +
"tap taphold " +
"swipe swipeleft swiperight " +
"scrollstart scrollstop" ).split(" "), function (i, name) {
$.fn[ name ] = function (fn) {
return fn ? this.bind(name, fn) : this.trigger(name);
};
// jQuery < 1.8
if ($.attrFn) {
$.attrFn[ name ] = true;
}
});
var supportTouch = $.mobile.support.touch,
scrollEvent = "touchmove scroll",
touchStartEvent = supportTouch ? "touchstart" : "mousedown",
touchStopEvent = supportTouch ? "touchend" : "mouseup",
touchMoveEvent = supportTouch ? "touchmove" : "mousemove";
function triggerCustomEvent(obj, eventType, event) {
var originalType = event.type;
event.type = eventType;
$.event.dispatch.call(obj, event);
event.type = originalType;
}
// also handles scrollstop
$.event.special.scrollstart = {
enabled: true,
setup: function () {
var thisObject = this,
$this = $(thisObject),
scrolling,
timer;
function trigger(event, state) {
scrolling = state;
triggerCustomEvent(thisObject, scrolling ? "scrollstart" : "scrollstop", event);
}
// iPhone triggers scroll after a small delay; use touchmove instead
$this.bind(scrollEvent, function (event) {
if (!$.event.special.scrollstart.enabled) {
return;
}
if (!scrolling) {
trigger(event, true);
}
clearTimeout(timer);
timer = setTimeout(function () {
trigger(event, false);
}, 50);
});
}
};
// also handles taphold
$.event.special.tap = {
tapholdThreshold: 750,
setup: function () {
var thisObject = this,
$this = $(thisObject);
$this.bind("vmousedown", function (event) {
if (event.which && event.which !== 1) {
return false;
}
var origTarget = event.target,
origEvent = event.originalEvent,
timer;
function clearTapTimer() {
clearTimeout(timer);
}
function clearTapHandlers() {
clearTapTimer();
$this.unbind("vclick", clickHandler)
.unbind("vmouseup", clearTapTimer);
$document.unbind("vmousecancel", clearTapHandlers);
}
function clickHandler(event) {
clearTapHandlers();
// ONLY trigger a 'tap' event if the start target is
// the same as the stop target.
if (origTarget === event.target) {
triggerCustomEvent(thisObject, "tap", event);
}
}
$this.bind("vmouseup", clearTapTimer)
.bind("vclick", clickHandler);
$document.bind("vmousecancel", clearTapHandlers);
timer = setTimeout(function () {
triggerCustomEvent(thisObject, "taphold", $.Event("taphold", { target: origTarget }));
}, $.event.special.tap.tapholdThreshold);
});
}
};
// also handles swipeleft, swiperight
$.event.special.swipe = {
scrollSupressionThreshold: 30, // More than this horizontal displacement, and we will suppress scrolling.
durationThreshold: 1000, // More time than this, and it isn't a swipe.
horizontalDistanceThreshold: 30, // Swipe horizontal displacement must be more than this.
verticalDistanceThreshold: 75, // Swipe vertical displacement must be less than this.
start: function (event) {
var data = event.originalEvent.touches ?
event.originalEvent.touches[ 0 ] : event;
return {
time: ( new Date() ).getTime(),
coords: [ data.pageX, data.pageY ],
origin: $(event.target)
};
},
stop: function (event) {
var data = event.originalEvent.touches ?
event.originalEvent.touches[ 0 ] : event;
return {
time: ( new Date() ).getTime(),
coords: [ data.pageX, data.pageY ]
};
},
handleSwipe: function (start, stop) {
if (stop.time - start.time < $.event.special.swipe.durationThreshold &&
Math.abs(start.coords[ 0 ] - stop.coords[ 0 ]) > $.event.special.swipe.horizontalDistanceThreshold &&
Math.abs(start.coords[ 1 ] - stop.coords[ 1 ]) < $.event.special.swipe.verticalDistanceThreshold) {
start.origin.trigger("swipe")
.trigger(start.coords[0] > stop.coords[ 0 ] ? "swipeleft" : "swiperight");
}
},
setup: function () {
var thisObject = this,
$this = $(thisObject);
$this.bind(touchStartEvent, function (event) {
var start = $.event.special.swipe.start(event),
stop;
function moveHandler(event) {
if (!start) {
return;
}
stop = $.event.special.swipe.stop(event);
// prevent scrolling
if (Math.abs(start.coords[ 0 ] - stop.coords[ 0 ]) > $.event.special.swipe.scrollSupressionThreshold) {
event.preventDefault();
}
}
$this.bind(touchMoveEvent, moveHandler)
.one(touchStopEvent, function () {
$this.unbind(touchMoveEvent, moveHandler);
if (start && stop) {
$.event.special.swipe.handleSwipe(start, stop);
}
start = stop = undefined;
});
});
}
};
$.each({
scrollstop: "scrollstart",
taphold: "tap",
swipeleft: "swipe",
swiperight: "swipe"
}, function (event, sourceEvent) {
$.event.special[ event ] = {
setup: function () {
$(this).bind(sourceEvent, $.noop);
}
};
});
})(jQuery, this);
// throttled resize event
(function ($) {
$.event.special.throttledresize = {
setup: function () {
$(this).bind("resize", handler);
},
teardown: function () {
$(this).unbind("resize", handler);
}
};
var throttle = 250,
handler = function () {
curr = ( new Date() ).getTime();
diff = curr - lastCall;
if (diff >= throttle) {
lastCall = curr;
$(this).trigger("throttledresize");
} else {
if (heldCall) {
clearTimeout(heldCall);
}
// Promise a held call will still execute
heldCall = setTimeout(handler, throttle - diff);
}
},
lastCall = 0,
heldCall,
curr,
diff;
})(jQuery);
(function ($, window) {
var win = $(window),
event_name = "orientationchange",
special_event,
get_orientation,
last_orientation,
initial_orientation_is_landscape,
initial_orientation_is_default,
portrait_map = { "0": true, "180": true };
// It seems that some device/browser vendors use window.orientation values 0 and 180 to
// denote the "default" orientation. For iOS devices, and most other smart-phones tested,
// the default orientation is always "portrait", but in some Android and RIM based tablets,
// the default orientation is "landscape". The following code attempts to use the window
// dimensions to figure out what the current orientation is, and then makes adjustments
// to the to the portrait_map if necessary, so that we can properly decode the
// window.orientation value whenever get_orientation() is called.
//
// Note that we used to use a media query to figure out what the orientation the browser
// thinks it is in:
//
// initial_orientation_is_landscape = $.mobile.media("all and (orientation: landscape)");
//
// but there was an iPhone/iPod Touch bug beginning with iOS 4.2, up through iOS 5.1,
// where the browser *ALWAYS* applied the landscape media query. This bug does not
// happen on iPad.
if ($.support.orientation) {
// Check the window width and height to figure out what the current orientation
// of the device is at this moment. Note that we've initialized the portrait map
// values to 0 and 180, *AND* we purposely check for landscape so that if we guess
// wrong, , we default to the assumption that portrait is the default orientation.
// We use a threshold check below because on some platforms like iOS, the iPhone
// form-factor can report a larger width than height if the user turns on the
// developer console. The actual threshold value is somewhat arbitrary, we just
// need to make sure it is large enough to exclude the developer console case.
var ww = window.innerWidth || win.width(),
wh = window.innerHeight || win.height(),
landscape_threshold = 50;
initial_orientation_is_landscape = ww > wh && ( ww - wh ) > landscape_threshold;
// Now check to see if the current window.orientation is 0 or 180.
initial_orientation_is_default = portrait_map[ window.orientation ];
// If the initial orientation is landscape, but window.orientation reports 0 or 180, *OR*
// if the initial orientation is portrait, but window.orientation reports 90 or -90, we
// need to flip our portrait_map values because landscape is the default orientation for
// this device/browser.
if (( initial_orientation_is_landscape && initial_orientation_is_default ) || ( !initial_orientation_is_landscape && !initial_orientation_is_default )) {
portrait_map = { "-90": true, "90": true };
}
}
$.event.special.orientationchange = $.extend({}, $.event.special.orientationchange, {
setup: function () {
// If the event is supported natively, return false so that jQuery
// will bind to the event using DOM methods.
if ($.support.orientation && !$.event.special.orientationchange.disabled) {
return false;
}
// Get the current orientation to avoid initial double-triggering.
last_orientation = get_orientation();
// Because the orientationchange event doesn't exist, simulate the
// event by testing window dimensions on resize.
win.bind("throttledresize", handler);
},
teardown: function () {
// If the event is not supported natively, return false so that
// jQuery will unbind the event using DOM methods.
if ($.support.orientation && !$.event.special.orientationchange.disabled) {
return false;
}
// Because the orientationchange event doesn't exist, unbind the
// resize event handler.
win.unbind("throttledresize", handler);
},
add: function (handleObj) {
// Save a reference to the bound event handler.
var old_handler = handleObj.handler;
handleObj.handler = function (event) {
// Modify event object, adding the .orientation property.
event.orientation = get_orientation();
// Call the originally-bound event handler and return its result.
return old_handler.apply(this, arguments);
};
}
});
// If the event is not supported natively, this handler will be bound to
// the window resize event to simulate the orientationchange event.
function handler() {
// Get the current orientation.
var orientation = get_orientation();
if (orientation !== last_orientation) {
// The orientation has changed, so trigger the orientationchange event.
last_orientation = orientation;
win.trigger(event_name);
}
}
// Get the current page orientation. This method is exposed publicly, should it
// be needed, as jQuery.event.special.orientationchange.orientation()
$.event.special.orientationchange.orientation = get_orientation = function () {
var isPortrait = true, elem = document.documentElement;
// prefer window orientation to the calculation based on screensize as
// the actual screen resize takes place before or after the orientation change event
// has been fired depending on implementation (eg android 2.3 is before, iphone after).
// More testing is required to determine if a more reliable method of determining the new screensize
// is possible when orientationchange is fired. (eg, use media queries + element + opacity)
if ($.support.orientation) {
// if the window orientation registers as 0 or 180 degrees report
// portrait, otherwise landscape
isPortrait = portrait_map[ window.orientation ];
} else {
isPortrait = elem && elem.clientWidth / elem.clientHeight < 1.1;
}
return isPortrait ? "portrait" : "landscape";
};
$.fn[ event_name ] = function (fn) {
return fn ? this.bind(event_name, fn) : this.trigger(event_name);
};
// jQuery < 1.8
if ($.attrFn) {
$.attrFn[ event_name ] = true;
}
}(jQuery, this));
(function ($, undefined) {
$.widget("mobile.page", $.mobile.widget, {
options: {
theme: "c",
domCache: false,
keepNativeDefault: ":jqmData(role='none'), :jqmData(role='nojs')"
},
_create: function () {
// if false is returned by the callbacks do not create the page
if (this._trigger("beforecreate") === false) {
return false;
}
this.element
.attr("tabindex", "0")
.addClass("ui-page ui-body-" + this.options.theme);
this._on(this.element, {
pagebeforehide: "removeContainerBackground",
pagebeforeshow: "_handlePageBeforeShow"
});
},
_handlePageBeforeShow: function (e) {
this.setContainerBackground();
},
removeContainerBackground: function () {
$.mobile.pageContainer.removeClass("ui-overlay-" + $.mobile.getInheritedTheme(this.element.parent()));
},
// set the page container background to the page theme
setContainerBackground: function (theme) {
if (this.options.theme) {
$.mobile.pageContainer.addClass("ui-overlay-" + ( theme || this.options.theme ));
}
},
keepNativeSelector: function () {
var options = this.options,
keepNativeDefined = options.keepNative && $.trim(options.keepNative);
if (keepNativeDefined && options.keepNative !== options.keepNativeDefault) {
return [options.keepNative, options.keepNativeDefault].join(", ");
}
return options.keepNativeDefault;
}
});
})(jQuery);
(function ($, window, undefined) {
var createHandler = function (sequential) {
// Default to sequential
if (sequential === undefined) {
sequential = true;
}
return function (name, reverse, $to, $from) {
var deferred = new $.Deferred(),
reverseClass = reverse ? " reverse" : "",
active = $.mobile.urlHistory.getActive(),
toScroll = active.lastScroll || $.mobile.defaultHomeScroll,
screenHeight = $.mobile.getScreenHeight(),
maxTransitionOverride = $.mobile.maxTransitionWidth !== false && $.mobile.window.width() > $.mobile.maxTransitionWidth,
none = !$.support.cssTransitions || maxTransitionOverride || !name || name === "none" || Math.max($.mobile.window.scrollTop(), toScroll) > $.mobile.getMaxScrollForTransition(),
toPreClass = " ui-page-pre-in",
toggleViewportClass = function () {
$.mobile.pageContainer.toggleClass("ui-mobile-viewport-transitioning viewport-" + name);
},
scrollPage = function () {
// By using scrollTo instead of silentScroll, we can keep things better in order
// Just to be precautios, disable scrollstart listening like silentScroll would
$.event.special.scrollstart.enabled = false;
window.scrollTo(0, toScroll);
// reenable scrollstart listening like silentScroll would
setTimeout(function () {
$.event.special.scrollstart.enabled = true;
}, 150);
},
cleanFrom = function () {
$from
.removeClass($.mobile.activePageClass + " out in reverse " + name)
.height("");
},
startOut = function () {
// if it's not sequential, call the doneOut transition to start the TO page animating in simultaneously
if (!sequential) {
doneOut();
}
else {
$from.animationComplete(doneOut);
}
// Set the from page's height and start it transitioning out
// Note: setting an explicit height helps eliminate tiling in the transitions
$from
.height(screenHeight + $.mobile.window.scrollTop())
.addClass(name + " out" + reverseClass);
},
doneOut = function () {
if ($from && sequential) {
cleanFrom();
}
startIn();
},
startIn = function () {
// Prevent flickering in phonegap container: see comments at #4024 regarding iOS
$to.css("z-index", -10);
$to.addClass($.mobile.activePageClass + toPreClass);
// Send focus to page as it is now display: block
$.mobile.focusPage($to);
// Set to page height
$to.height(screenHeight + toScroll);
scrollPage();
// Restores visibility of the new page: added together with $to.css( "z-index", -10 );
$to.css("z-index", "");
if (!none) {
$to.animationComplete(doneIn);
}
$to
.removeClass(toPreClass)
.addClass(name + " in" + reverseClass);
if (none) {
doneIn();
}
},
doneIn = function () {
if (!sequential) {
if ($from) {
cleanFrom();
}
}
$to
.removeClass("out in reverse " + name)
.height("");
toggleViewportClass();
// In some browsers (iOS5), 3D transitions block the ability to scroll to the desired location during transition
// This ensures we jump to that spot after the fact, if we aren't there already.
if ($.mobile.window.scrollTop() !== toScroll) {
scrollPage();
}
deferred.resolve(name, reverse, $to, $from, true);
};
toggleViewportClass();
if ($from && !none) {
startOut();
}
else {
doneOut();
}
return deferred.promise();
};
};
// generate the handlers from the above
var sequentialHandler = createHandler(),
simultaneousHandler = createHandler(false),
defaultGetMaxScrollForTransition = function () {
return $.mobile.getScreenHeight() * 3;
};
// Make our transition handler the public default.
$.mobile.defaultTransitionHandler = sequentialHandler;
//transition handler dictionary for 3rd party transitions
$.mobile.transitionHandlers = {
"default": $.mobile.defaultTransitionHandler,
"sequential": sequentialHandler,
"simultaneous": simultaneousHandler
};
$.mobile.transitionFallbacks = {};
// If transition is defined, check if css 3D transforms are supported, and if not, if a fallback is specified
$.mobile._maybeDegradeTransition = function (transition) {
if (transition && !$.support.cssTransform3d && $.mobile.transitionFallbacks[ transition ]) {
transition = $.mobile.transitionFallbacks[ transition ];
}
return transition;
};
// Set the getMaxScrollForTransition to default if no implementation was set by user
$.mobile.getMaxScrollForTransition = $.mobile.getMaxScrollForTransition || defaultGetMaxScrollForTransition;
})(jQuery, this);
(function ($, undefined) {
//define vars for interal use
var $window = $.mobile.window,
$html = $('html'),
$head = $('head'),
// NOTE: path extensions dependent on core attributes. Moved here to remove deps from
// $.mobile.path definition
path = $.extend($.mobile.path, {
//return the substring of a filepath before the sub-page key, for making a server request
getFilePath: function (path) {
var splitkey = '&' + $.mobile.subPageUrlKey;
return path && path.split(splitkey)[0].split(dialogHashKey)[0];
},
//check if the specified url refers to the first page in the main application document.
isFirstPageUrl: function (url) {
// We only deal with absolute paths.
var u = path.parseUrl(path.makeUrlAbsolute(url, this.documentBase)),
// Does the url have the same path as the document?
samePath = u.hrefNoHash === this.documentUrl.hrefNoHash || ( this.documentBaseDiffers && u.hrefNoHash === this.documentBase.hrefNoHash ),
// Get the first page element.
fp = $.mobile.firstPage,
// Get the id of the first page element if it has one.
fpId = fp && fp[0] ? fp[0].id : undefined;
// The url refers to the first page if the path matches the document and
// it either has no hash value, or the hash is exactly equal to the id of the
// first page element.
return samePath && ( !u.hash || u.hash === "#" || ( fpId && u.hash.replace(/^#/, "") === fpId ) );
},
// Some embedded browsers, like the web view in Phone Gap, allow cross-domain XHR
// requests if the document doing the request was loaded via the file:// protocol.
// This is usually to allow the application to "phone home" and fetch app specific
// data. We normally let the browser handle external/cross-domain urls, but if the
// allowCrossDomainPages option is true, we will allow cross-domain http/https
// requests to go through our page loading logic.
isPermittedCrossDomainRequest: function (docUrl, reqUrl) {
return $.mobile.allowCrossDomainPages &&
docUrl.protocol === "file:" &&
reqUrl.search(/^https?:/) !== -1;
}
}),
// used to track last vclicked element to make sure its value is added to form data
$lastVClicked = null,
//will be defined when a link is clicked and given an active class
$activeClickedLink = null,
// resolved on domready
domreadyDeferred = $.Deferred(),
//urlHistory is purely here to make guesses at whether the back or forward button was clicked
//and provide an appropriate transition
urlHistory = $.mobile.navigate.history,
//define first selector to receive focus when a page is shown
focusable = "[tabindex],a,button:visible,select:visible,input",
//queue to hold simultanious page transitions
pageTransitionQueue = [],
//indicates whether or not page is in process of transitioning
isPageTransitioning = false,
//nonsense hash change key for dialogs, so they create a history entry
dialogHashKey = "&ui-state=dialog",
//existing base tag?
$base = $head.children("base"),
//tuck away the original document URL minus any fragment.
documentUrl = path.documentUrl,
//if the document has an embedded base tag, documentBase is set to its
//initial value. If a base tag does not exist, then we default to the documentUrl.
documentBase = path.documentBase,
//cache the comparison once.
documentBaseDiffers = path.documentBaseDiffers,
getScreenHeight = $.mobile.getScreenHeight;
//base element management, defined depending on dynamic base tag support
var base = $.support.dynamicBaseTag ? {
//define base element, for use in routing asset urls that are referenced in Ajax-requested markup
element: ( $base.length ? $base : $("<base>", { href: documentBase.hrefNoHash }).prependTo($head) ),
//set the generated BASE element's href attribute to a new page's base path
set: function (href) {
href = path.parseUrl(href).hrefNoHash;
base.element.attr("href", path.makeUrlAbsolute(href, documentBase));
},
//set the generated BASE element's href attribute to a new page's base path
reset: function () {
base.element.attr("href", documentBase.hrefNoSearch);
}
} : undefined;
//return the original document url
$.mobile.getDocumentUrl = path.getDocumentUrl;
//return the original document base url
$.mobile.getDocumentBase = path.getDocumentBase;
/* internal utility functions */
// NOTE Issue #4950 Android phonegap doesn't navigate back properly
// when a full page refresh has taken place. It appears that hashchange
// and replacestate history alterations work fine but we need to support
// both forms of history traversal in our code that uses backward history
// movement
$.mobile.back = function () {
var nav = window.navigator;
// if the setting is on and the navigator object is
// available use the phonegap navigation capability
if (this.phonegapNavigationEnabled &&
nav &&
nav.app &&
nav.app.backHistory) {
nav.app.backHistory();
} else {
window.history.back();
}
};
//direct focus to the page title, or otherwise first focusable element
$.mobile.focusPage = function (page) {
var autofocus = page.find("[autofocus]"),
pageTitle = page.find(".ui-title:eq(0)");
if (autofocus.length) {
autofocus.focus();
return;
}
if (pageTitle.length) {
pageTitle.focus();
} else {
page.focus();
}
};
//remove active classes after page transition or error
function removeActiveLinkClass(forceRemoval) {
if (!!$activeClickedLink && ( !$activeClickedLink.closest("." + $.mobile.activePageClass).length || forceRemoval )) {
$activeClickedLink.removeClass($.mobile.activeBtnClass);
}
$activeClickedLink = null;
}
function releasePageTransitionLock() {
isPageTransitioning = false;
if (pageTransitionQueue.length > 0) {
$.mobile.changePage.apply(null, pageTransitionQueue.pop());
}
}
// Save the last scroll distance per page, before it is hidden
var setLastScrollEnabled = true,
setLastScroll, delayedSetLastScroll;
setLastScroll = function () {
// this barrier prevents setting the scroll value based on the browser
// scrolling the window based on a hashchange
if (!setLastScrollEnabled) {
return;
}
var active = $.mobile.urlHistory.getActive();
if (active) {
var lastScroll = $window.scrollTop();
// Set active page's lastScroll prop.
// If the location we're scrolling to is less than minScrollBack, let it go.
active.lastScroll = lastScroll < $.mobile.minScrollBack ? $.mobile.defaultHomeScroll : lastScroll;
}
};
// bind to scrollstop to gather scroll position. The delay allows for the hashchange
// event to fire and disable scroll recording in the case where the browser scrolls
// to the hash targets location (sometimes the top of the page). once pagechange fires
// getLastScroll is again permitted to operate
delayedSetLastScroll = function () {
setTimeout(setLastScroll, 100);
};
// disable an scroll setting when a hashchange has been fired, this only works
// because the recording of the scroll position is delayed for 100ms after
// the browser might have changed the position because of the hashchange
$window.bind($.support.pushState ? "popstate" : "hashchange", function () {
setLastScrollEnabled = false;
});
// handle initial hashchange from chrome :(
$window.one($.support.pushState ? "popstate" : "hashchange", function () {
setLastScrollEnabled = true;
});
// wait until the mobile page container has been determined to bind to pagechange
$window.one("pagecontainercreate", function () {
// once the page has changed, re-enable the scroll recording
$.mobile.pageContainer.bind("pagechange", function () {
setLastScrollEnabled = true;
// remove any binding that previously existed on the get scroll
// which may or may not be different than the scroll element determined for
// this page previously
$window.unbind("scrollstop", delayedSetLastScroll);
// determine and bind to the current scoll element which may be the window
// or in the case of touch overflow the element with touch overflow
$window.bind("scrollstop", delayedSetLastScroll);
});
});
// bind to scrollstop for the first page as "pagechange" won't be fired in that case
$window.bind("scrollstop", delayedSetLastScroll);
// No-op implementation of transition degradation
$.mobile._maybeDegradeTransition = $.mobile._maybeDegradeTransition || function (transition) {
return transition;
};
//function for transitioning between two existing pages
function transitionPages(toPage, fromPage, transition, reverse) {
if (fromPage) {
//trigger before show/hide events
fromPage.data("mobile-page")._trigger("beforehide", null, { nextPage: toPage });
}
toPage.data("mobile-page")._trigger("beforeshow", null, { prevPage: fromPage || $("") });
//clear page loader
$.mobile.hidePageLoadingMsg();
transition = $.mobile._maybeDegradeTransition(transition);
//find the transition handler for the specified transition. If there
//isn't one in our transitionHandlers dictionary, use the default one.
//call the handler immediately to kick-off the transition.
var th = $.mobile.transitionHandlers[ transition || "default" ] || $.mobile.defaultTransitionHandler,
promise = th(transition, reverse, toPage, fromPage);
promise.done(function () {
//trigger show/hide events
if (fromPage) {
fromPage.data("mobile-page")._trigger("hide", null, { nextPage: toPage });
}
//trigger pageshow, define prevPage as either fromPage or empty jQuery obj
toPage.data("mobile-page")._trigger("show", null, { prevPage: fromPage || $("") });
});
return promise;
}
//simply set the active page's minimum height to screen height, depending on orientation
$.mobile.resetActivePageHeight = function resetActivePageHeight(height) {
var aPage = $("." + $.mobile.activePageClass),
aPagePadT = parseFloat(aPage.css("padding-top")),
aPagePadB = parseFloat(aPage.css("padding-bottom")),
aPageBorderT = parseFloat(aPage.css("border-top-width")),
aPageBorderB = parseFloat(aPage.css("border-bottom-width"));
height = ( typeof height === "number" ) ? height : getScreenHeight();
aPage.css("min-height", height - aPagePadT - aPagePadB - aPageBorderT - aPageBorderB);
};
//shared page enhancements
function enhancePage($page, role) {
// If a role was specified, make sure the data-role attribute
// on the page element is in sync.
if (role) {
$page.attr("data-" + $.mobile.ns + "role", role);
}
//run page plugin
$page.page();
}
// determine the current base url
function findBaseWithDefault() {
var closestBase = ( $.mobile.activePage && getClosestBaseUrl($.mobile.activePage) );
return closestBase || documentBase.hrefNoHash;
}
/* exposed $.mobile methods */
//animation complete callback
$.fn.animationComplete = function (callback) {
if ($.support.cssTransitions) {
return $(this).one('webkitAnimationEnd animationend', callback);
}
else {
// defer execution for consistency between webkit/non webkit
setTimeout(callback, 0);
return $(this);
}
};
//expose path object on $.mobile
$.mobile.path = path;
//expose base object on $.mobile
$.mobile.base = base;
//history stack
$.mobile.urlHistory = urlHistory;
$.mobile.dialogHashKey = dialogHashKey;
//enable cross-domain page support
$.mobile.allowCrossDomainPages = false;
$.mobile._bindPageRemove = function () {
var page = $(this);
// when dom caching is not enabled or the page is embedded bind to remove the page on hide
if (!page.data("mobile-page").options.domCache &&
page.is(":jqmData(external-page='true')")) {
page.bind('pagehide.remove', function (e) {
var $this = $(this),
prEvent = new $.Event("pageremove");
$this.trigger(prEvent);
if (!prEvent.isDefaultPrevented()) {
$this.removeWithDependents();
}
});
}
};
// Load a page into the DOM.
$.mobile.loadPage = function (url, options) {
// This function uses deferred notifications to let callers
// know when the page is done loading, or if an error has occurred.
var deferred = $.Deferred(),
// The default loadPage options with overrides specified by
// the caller.
settings = $.extend({}, $.mobile.loadPage.defaults, options),
// The DOM element for the page after it has been loaded.
page = null,
// If the reloadPage option is true, and the page is already
// in the DOM, dupCachedPage will be set to the page element
// so that it can be removed after the new version of the
// page is loaded off the network.
dupCachedPage = null,
// The absolute version of the URL passed into the function. This
// version of the URL may contain dialog/subpage params in it.
absUrl = path.makeUrlAbsolute(url, findBaseWithDefault());
// If the caller provided data, and we're using "get" request,
// append the data to the URL.
if (settings.data && settings.type === "get") {
absUrl = path.addSearchParams(absUrl, settings.data);
settings.data = undefined;
}
// If the caller is using a "post" request, reloadPage must be true
if (settings.data && settings.type === "post") {
settings.reloadPage = true;
}
// The absolute version of the URL minus any dialog/subpage params.
// In otherwords the real URL of the page to be loaded.
var fileUrl = path.getFilePath(absUrl),
// The version of the Url actually stored in the data-url attribute of
// the page. For embedded pages, it is just the id of the page. For pages
// within the same domain as the document base, it is the site relative
// path. For cross-domain pages (Phone Gap only) the entire absolute Url
// used to load the page.
dataUrl = path.convertUrlToDataUrl(absUrl);
// Make sure we have a pageContainer to work with.
settings.pageContainer = settings.pageContainer || $.mobile.pageContainer;
// Check to see if the page already exists in the DOM.
// NOTE do _not_ use the :jqmData psuedo selector because parenthesis
// are a valid url char and it breaks on the first occurence
page = settings.pageContainer.children("[data-" + $.mobile.ns + "url='" + dataUrl + "']");
// If we failed to find the page, check to see if the url is a
// reference to an embedded page. If so, it may have been dynamically
// injected by a developer, in which case it would be lacking a data-url
// attribute and in need of enhancement.
if (page.length === 0 && dataUrl && !path.isPath(dataUrl)) {
page = settings.pageContainer.children("#" + dataUrl)
.attr("data-" + $.mobile.ns + "url", dataUrl)
.jqmData("url", dataUrl);
}
// If we failed to find a page in the DOM, check the URL to see if it
// refers to the first page in the application. If it isn't a reference
// to the first page and refers to non-existent embedded page, error out.
if (page.length === 0) {
if ($.mobile.firstPage && path.isFirstPageUrl(fileUrl)) {
// Check to make sure our cached-first-page is actually
// in the DOM. Some user deployed apps are pruning the first
// page from the DOM for various reasons, we check for this
// case here because we don't want a first-page with an id
// falling through to the non-existent embedded page error
// case. If the first-page is not in the DOM, then we let
// things fall through to the ajax loading code below so
// that it gets reloaded.
if ($.mobile.firstPage.parent().length) {
page = $($.mobile.firstPage);
}
} else if (path.isEmbeddedPage(fileUrl)) {
deferred.reject(absUrl, options);
return deferred.promise();
}
}
// If the page we are interested in is already in the DOM,
// and the caller did not indicate that we should force a
// reload of the file, we are done. Otherwise, track the
// existing page as a duplicated.
if (page.length) {
if (!settings.reloadPage) {
enhancePage(page, settings.role);
deferred.resolve(absUrl, options, page);
//if we are reloading the page make sure we update the base if its not a prefetch
if (base && !options.prefetch) {
base.set(url);
}
return deferred.promise();
}
dupCachedPage = page;
}
var mpc = settings.pageContainer,
pblEvent = new $.Event("pagebeforeload"),
triggerData = { url: url, absUrl: absUrl, dataUrl: dataUrl, deferred: deferred, options: settings };
// Let listeners know we're about to load a page.
mpc.trigger(pblEvent, triggerData);
// If the default behavior is prevented, stop here!
if (pblEvent.isDefaultPrevented()) {
return deferred.promise();
}
if (settings.showLoadMsg) {
// This configurable timeout allows cached pages a brief delay to load without showing a message
var loadMsgDelay = setTimeout(function () {
$.mobile.showPageLoadingMsg();
}, settings.loadMsgDelay),
// Shared logic for clearing timeout and removing message.
hideMsg = function () {
// Stop message show timer
clearTimeout(loadMsgDelay);
// Hide loading message
$.mobile.hidePageLoadingMsg();
};
}
// Reset base to the default document base.
// only reset if we are not prefetching
if (base && ( typeof options === "undefined" || typeof options.prefetch === "undefined" )) {
base.reset();
}
if (!( $.mobile.allowCrossDomainPages || path.isSameDomain(documentUrl, absUrl) )) {
deferred.reject(absUrl, options);
} else {
// Load the new page.
$.ajax({
url: fileUrl,
type: settings.type,
data: settings.data,
contentType: settings.contentType,
dataType: "html",
success: function (html, textStatus, xhr) {
//pre-parse html to check for a data-url,
//use it as the new fileUrl, base path, etc
var all = $("<div></div>"),
//page title regexp
newPageTitle = html.match(/<title[^>]*>([^<]*)/) && RegExp.$1,
// TODO handle dialogs again
pageElemRegex = new RegExp("(<[^>]+\\bdata-" + $.mobile.ns + "role=[\"']?page[\"']?[^>]*>)"),
dataUrlRegex = new RegExp("\\bdata-" + $.mobile.ns + "url=[\"']?([^\"'>]*)[\"']?");
// data-url must be provided for the base tag so resource requests can be directed to the
// correct url. loading into a temprorary element makes these requests immediately
if (pageElemRegex.test(html) &&
RegExp.$1 &&
dataUrlRegex.test(RegExp.$1) &&
RegExp.$1) {
url = fileUrl = path.getFilePath($("<div>" + RegExp.$1 + "</div>").text());
}
//dont update the base tag if we are prefetching
if (base && ( typeof options === "undefined" || typeof options.prefetch === "undefined" )) {
base.set(fileUrl);
}
//workaround to allow scripts to execute when included in page divs
all.get(0).innerHTML = html;
page = all.find(":jqmData(role='page'), :jqmData(role='dialog')").first();
//if page elem couldn't be found, create one and insert the body element's contents
if (!page.length) {
page = $("<div data-" + $.mobile.ns + "role='page'>" + ( html.split(/<\/?body[^>]*>/gmi)[1] || "" ) + "</div>");
}
if (newPageTitle && !page.jqmData("title")) {
if (~newPageTitle.indexOf("&")) {
newPageTitle = $("<div>" + newPageTitle + "</div>").text();
}
page.jqmData("title", newPageTitle);
}
//rewrite src and href attrs to use a base url
if (!$.support.dynamicBaseTag) {
var newPath = path.get(fileUrl);
page.find("[src], link[href], a[rel='external'], :jqmData(ajax='false'), a[target]").each(function () {
var thisAttr = $(this).is('[href]') ? 'href' :
$(this).is('[src]') ? 'src' : 'action',
thisUrl = $(this).attr(thisAttr);
// XXX_jblas: We need to fix this so that it removes the document
// base URL, and then prepends with the new page URL.
//if full path exists and is same, chop it - helps IE out
thisUrl = thisUrl.replace(location.protocol + '//' + location.host + location.pathname, '');
if (!/^(\w+:|#|\/)/.test(thisUrl)) {
$(this).attr(thisAttr, newPath + thisUrl);
}
});
}
//append to page and enhance
// TODO taging a page with external to make sure that embedded pages aren't removed
// by the various page handling code is bad. Having page handling code in many
// places is bad. Solutions post 1.0
page
.attr("data-" + $.mobile.ns + "url", path.convertUrlToDataUrl(fileUrl))
.attr("data-" + $.mobile.ns + "external-page", true)
.appendTo(settings.pageContainer);
// wait for page creation to leverage options defined on widget
page.one('pagecreate', $.mobile._bindPageRemove);
enhancePage(page, settings.role);
// Enhancing the page may result in new dialogs/sub pages being inserted
// into the DOM. If the original absUrl refers to a sub-page, that is the
// real page we are interested in.
if (absUrl.indexOf("&" + $.mobile.subPageUrlKey) > -1) {
page = settings.pageContainer.children("[data-" + $.mobile.ns + "url='" + dataUrl + "']");
}
// Remove loading message.
if (settings.showLoadMsg) {
hideMsg();
}
// Add the page reference and xhr to our triggerData.
triggerData.xhr = xhr;
triggerData.textStatus = textStatus;
triggerData.page = page;
// Let listeners know the page loaded successfully.
settings.pageContainer.trigger("pageload", triggerData);
deferred.resolve(absUrl, options, page, dupCachedPage);
},
error: function (xhr, textStatus, errorThrown) {
//set base back to current path
if (base) {
base.set(path.get());
}
// Add error info to our triggerData.
triggerData.xhr = xhr;
triggerData.textStatus = textStatus;
triggerData.errorThrown = errorThrown;
var plfEvent = new $.Event("pageloadfailed");
// Let listeners know the page load failed.
settings.pageContainer.trigger(plfEvent, triggerData);
// If the default behavior is prevented, stop here!
// Note that it is the responsibility of the listener/handler
// that called preventDefault(), to resolve/reject the
// deferred object within the triggerData.
if (plfEvent.isDefaultPrevented()) {
return;
}
// Remove loading message.
if (settings.showLoadMsg) {
// Remove loading message.
hideMsg();
// show error message
$.mobile.showPageLoadingMsg($.mobile.pageLoadErrorMessageTheme, $.mobile.pageLoadErrorMessage, true);
// hide after delay
setTimeout($.mobile.hidePageLoadingMsg, 1500);
}
deferred.reject(absUrl, options);
}
});
}
return deferred.promise();
};
$.mobile.loadPage.defaults = {
type: "get",
data: undefined,
reloadPage: false,
role: undefined, // By default we rely on the role defined by the @data-role attribute.
showLoadMsg: false,
pageContainer: undefined,
loadMsgDelay: 50 // This delay allows loads that pull from browser cache to occur without showing the loading message.
};
// Show a specific page in the page container.
$.mobile.changePage = function (toPage, options) {
// If we are in the midst of a transition, queue the current request.
// We'll call changePage() once we're done with the current transition to
// service the request.
if (isPageTransitioning) {
pageTransitionQueue.unshift(arguments);
return;
}
var settings = $.extend({}, $.mobile.changePage.defaults, options), isToPageString;
// Make sure we have a pageContainer to work with.
settings.pageContainer = settings.pageContainer || $.mobile.pageContainer;
// Make sure we have a fromPage.
settings.fromPage = settings.fromPage || $.mobile.activePage;
isToPageString = (typeof toPage === "string");
var mpc = settings.pageContainer,
pbcEvent = new $.Event("pagebeforechange"),
triggerData = { toPage: toPage, options: settings };
// NOTE: preserve the original target as the dataUrl value will be simplified
// eg, removing ui-state, and removing query params from the hash
// this is so that users who want to use query params have access to them
// in the event bindings for the page life cycle See issue #5085
if (isToPageString) {
// if the toPage is a string simply convert it
triggerData.absUrl = path.makeUrlAbsolute(toPage, findBaseWithDefault());
} else {
// if the toPage is a jQuery object grab the absolute url stored
// in the loadPage callback where it exists
triggerData.absUrl = toPage.data('absUrl');
}
// Let listeners know we're about to change the current page.
mpc.trigger(pbcEvent, triggerData);
// If the default behavior is prevented, stop here!
if (pbcEvent.isDefaultPrevented()) {
return;
}
// We allow "pagebeforechange" observers to modify the toPage in the trigger
// data to allow for redirects. Make sure our toPage is updated.
//
// We also need to re-evaluate whether it is a string, because an object can
// also be replaced by a string
toPage = triggerData.toPage;
isToPageString = (typeof toPage === "string");
// Set the isPageTransitioning flag to prevent any requests from
// entering this method while we are in the midst of loading a page
// or transitioning.
isPageTransitioning = true;
// If the caller passed us a url, call loadPage()
// to make sure it is loaded into the DOM. We'll listen
// to the promise object it returns so we know when
// it is done loading or if an error ocurred.
if (isToPageString) {
// preserve the original target as the dataUrl value will be simplified
// eg, removing ui-state, and removing query params from the hash
// this is so that users who want to use query params have access to them
// in the event bindings for the page life cycle See issue #5085
settings.target = toPage;
$.mobile.loadPage(toPage, settings)
.done(function (url, options, newPage, dupCachedPage) {
isPageTransitioning = false;
options.duplicateCachedPage = dupCachedPage;
// store the original absolute url so that it can be provided
// to events in the triggerData of the subsequent changePage call
newPage.data('absUrl', triggerData.absUrl);
$.mobile.changePage(newPage, options);
})
.fail(function (url, options) {
//clear out the active button state
removeActiveLinkClass(true);
//release transition lock so navigation is free again
releasePageTransitionLock();
settings.pageContainer.trigger("pagechangefailed", triggerData);
});
return;
}
// If we are going to the first-page of the application, we need to make
// sure settings.dataUrl is set to the application document url. This allows
// us to avoid generating a document url with an id hash in the case where the
// first-page of the document has an id attribute specified.
if (toPage[ 0 ] === $.mobile.firstPage[ 0 ] && !settings.dataUrl) {
settings.dataUrl = documentUrl.hrefNoHash;
}
// The caller passed us a real page DOM element. Update our
// internal state and then trigger a transition to the page.
var fromPage = settings.fromPage,
url = ( settings.dataUrl && path.convertUrlToDataUrl(settings.dataUrl) ) || toPage.jqmData("url"),
// The pageUrl var is usually the same as url, except when url is obscured as a dialog url. pageUrl always contains the file path
pageUrl = url,
fileUrl = path.getFilePath(url),
active = urlHistory.getActive(),
activeIsInitialPage = urlHistory.activeIndex === 0,
historyDir = 0,
pageTitle = document.title,
isDialog = settings.role === "dialog" || toPage.jqmData("role") === "dialog";
// By default, we prevent changePage requests when the fromPage and toPage
// are the same element, but folks that generate content manually/dynamically
// and reuse pages want to be able to transition to the same page. To allow
// this, they will need to change the default value of allowSamePageTransition
// to true, *OR*, pass it in as an option when they manually call changePage().
// It should be noted that our default transition animations assume that the
// formPage and toPage are different elements, so they may behave unexpectedly.
// It is up to the developer that turns on the allowSamePageTransitiona option
// to either turn off transition animations, or make sure that an appropriate
// animation transition is used.
if (fromPage && fromPage[0] === toPage[0] && !settings.allowSamePageTransition) {
isPageTransitioning = false;
mpc.trigger("pagechange", triggerData);
// Even if there is no page change to be done, we should keep the urlHistory in sync with the hash changes
if (settings.fromHashChange) {
urlHistory.direct({ url: url });
}
return;
}
// We need to make sure the page we are given has already been enhanced.
enhancePage(toPage, settings.role);
// If the changePage request was sent from a hashChange event, check to see if the
// page is already within the urlHistory stack. If so, we'll assume the user hit
// the forward/back button and will try to match the transition accordingly.
if (settings.fromHashChange) {
historyDir = options.direction === "back" ? -1 : 1;
}
// Kill the keyboard.
// XXX_jblas: We need to stop crawling the entire document to kill focus. Instead,
// we should be tracking focus with a delegate() handler so we already have
// the element in hand at this point.
// Wrap this in a try/catch block since IE9 throw "Unspecified error" if document.activeElement
// is undefined when we are in an IFrame.
try {
if (document.activeElement && document.activeElement.nodeName.toLowerCase() !== 'body') {
$(document.activeElement).blur();
} else {
$("input:focus, textarea:focus, select:focus").blur();
}
} catch (e) {
}
// Record whether we are at a place in history where a dialog used to be - if so, do not add a new history entry and do not change the hash either
var alreadyThere = false;
// If we're displaying the page as a dialog, we don't want the url
// for the dialog content to be used in the hash. Instead, we want
// to append the dialogHashKey to the url of the current page.
if (isDialog && active) {
// on the initial page load active.url is undefined and in that case should
// be an empty string. Moving the undefined -> empty string back into
// urlHistory.addNew seemed imprudent given undefined better represents
// the url state
// If we are at a place in history that once belonged to a dialog, reuse
// this state without adding to urlHistory and without modifying the hash.
// However, if a dialog is already displayed at this point, and we're
// about to display another dialog, then we must add another hash and
// history entry on top so that one may navigate back to the original dialog
if (active.url &&
active.url.indexOf(dialogHashKey) > -1 &&
$.mobile.activePage && !$.mobile.activePage.is(".ui-dialog") &&
urlHistory.activeIndex > 0) {
settings.changeHash = false;
alreadyThere = true;
}
// Normally, we tack on a dialog hash key, but if this is the location of a stale dialog,
// we reuse the URL from the entry
url = ( active.url || "" );
// account for absolute urls instead of just relative urls use as hashes
if (!alreadyThere && url.indexOf("#") > -1) {
url += dialogHashKey;
} else {
url += "#" + dialogHashKey;
}
// tack on another dialogHashKey if this is the same as the initial hash
// this makes sure that a history entry is created for this dialog
if (urlHistory.activeIndex === 0 && url === urlHistory.initialDst) {
url += dialogHashKey;
}
}
// if title element wasn't found, try the page div data attr too
// If this is a deep-link or a reload ( active === undefined ) then just use pageTitle
var newPageTitle = ( !active ) ? pageTitle : toPage.jqmData("title") || toPage.children(":jqmData(role='header')").find(".ui-title").text();
if (!!newPageTitle && pageTitle === document.title) {
pageTitle = newPageTitle;
}
if (!toPage.jqmData("title")) {
toPage.jqmData("title", pageTitle);
}
// Make sure we have a transition defined.
settings.transition = settings.transition ||
( ( historyDir && !activeIsInitialPage ) ? active.transition : undefined ) ||
( isDialog ? $.mobile.defaultDialogTransition : $.mobile.defaultPageTransition );
//add page to history stack if it's not back or forward
if (!historyDir && alreadyThere) {
urlHistory.getActive().pageUrl = pageUrl;
}
// Set the location hash.
if (url && !settings.fromHashChange) {
var params;
// rebuilding the hash here since we loose it earlier on
// TODO preserve the originally passed in path
if (!path.isPath(url) && url.indexOf("#") < 0) {
url = "#" + url;
}
// TODO the property names here are just silly
params = {
transition: settings.transition,
title: pageTitle,
pageUrl: pageUrl,
role: settings.role
};
if (settings.changeHash !== false && $.mobile.hashListeningEnabled) {
$.mobile.navigate(url, params, true);
} else if (toPage[ 0 ] !== $.mobile.firstPage[ 0 ]) {
$.mobile.navigate.history.add(url, params);
}
}
//set page title
document.title = pageTitle;
//set "toPage" as activePage
$.mobile.activePage = toPage;
// If we're navigating back in the URL history, set reverse accordingly.
settings.reverse = settings.reverse || historyDir < 0;
transitionPages(toPage, fromPage, settings.transition, settings.reverse)
.done(function (name, reverse, $to, $from, alreadyFocused) {
removeActiveLinkClass();
//if there's a duplicateCachedPage, remove it from the DOM now that it's hidden
if (settings.duplicateCachedPage) {
settings.duplicateCachedPage.remove();
}
// Send focus to the newly shown page. Moved from promise .done binding in transitionPages
// itself to avoid ie bug that reports offsetWidth as > 0 (core check for visibility)
// despite visibility: hidden addresses issue #2965
// https://github.com/jquery/jquery-mobile/issues/2965
if (!alreadyFocused) {
$.mobile.focusPage(toPage);
}
releasePageTransitionLock();
mpc.trigger("pagechange", triggerData);
});
};
$.mobile.changePage.defaults = {
transition: undefined,
reverse: false,
changeHash: true,
fromHashChange: false,
role: undefined, // By default we rely on the role defined by the @data-role attribute.
duplicateCachedPage: undefined,
pageContainer: undefined,
showLoadMsg: true, //loading message shows by default when pages are being fetched during changePage
dataUrl: undefined,
fromPage: undefined,
allowSamePageTransition: false
};
/* Event Bindings - hashchange, submit, and click */
function findClosestLink(ele) {
while (ele) {
// Look for the closest element with a nodeName of "a".
// Note that we are checking if we have a valid nodeName
// before attempting to access it. This is because the
// node we get called with could have originated from within
// an embedded SVG document where some symbol instance elements
// don't have nodeName defined on them, or strings are of type
// SVGAnimatedString.
if (( typeof ele.nodeName === "string" ) && ele.nodeName.toLowerCase() === "a") {
break;
}
ele = ele.parentNode;
}
return ele;
}
// The base URL for any given element depends on the page it resides in.
function getClosestBaseUrl(ele) {
// Find the closest page and extract out its url.
var url = $(ele).closest(".ui-page").jqmData("url"),
base = documentBase.hrefNoHash;
if (!url || !path.isPath(url)) {
url = base;
}
return path.makeUrlAbsolute(url, base);
}
//The following event bindings should be bound after mobileinit has been triggered
//the following deferred is resolved in the init file
$.mobile.navreadyDeferred = $.Deferred();
$.mobile._registerInternalEvents = function () {
var getAjaxFormData = function ($form, calculateOnly) {
var url, ret = true, formData, vclickedName, method;
if (!$.mobile.ajaxEnabled ||
// test that the form is, itself, ajax false
$form.is(":jqmData(ajax='false')") ||
// test that $.mobile.ignoreContentEnabled is set and
// the form or one of it's parents is ajax=false
!$form.jqmHijackable().length ||
$form.attr("target")) {
return false;
}
url = $form.attr("action");
method = ( $form.attr("method") || "get" ).toLowerCase();
// If no action is specified, browsers default to using the
// URL of the document containing the form. Since we dynamically
// pull in pages from external documents, the form should submit
// to the URL for the source document of the page containing
// the form.
if (!url) {
// Get the @data-url for the page containing the form.
url = getClosestBaseUrl($form);
// NOTE: If the method is "get", we need to strip off the query string
// because it will get replaced with the new form data. See issue #5710.
if (method === "get") {
url = path.parseUrl(url).hrefNoSearch;
}
if (url === documentBase.hrefNoHash) {
// The url we got back matches the document base,
// which means the page must be an internal/embedded page,
// so default to using the actual document url as a browser
// would.
url = documentUrl.hrefNoSearch;
}
}
url = path.makeUrlAbsolute(url, getClosestBaseUrl($form));
if (( path.isExternal(url) && !path.isPermittedCrossDomainRequest(documentUrl, url) )) {
return false;
}
if (!calculateOnly) {
formData = $form.serializeArray();
if ($lastVClicked && $lastVClicked[ 0 ].form === $form[ 0 ]) {
vclickedName = $lastVClicked.attr("name");
if (vclickedName) {
// Make sure the last clicked element is included in the form
$.each(formData, function (key, value) {
if (value.name === vclickedName) {
// Unset vclickedName - we've found it in the serialized data already
vclickedName = "";
return false;
}
});
if (vclickedName) {
formData.push({ name: vclickedName, value: $lastVClicked.attr("value") });
}
}
}
ret = {
url: url,
options: {
type: method,
data: $.param(formData),
transition: $form.jqmData("transition"),
reverse: $form.jqmData("direction") === "reverse",
reloadPage: true
}
};
}
return ret;
};
//bind to form submit events, handle with Ajax
$.mobile.document.delegate("form", "submit", function (event) {
var formData = getAjaxFormData($(this));
if (formData) {
$.mobile.changePage(formData.url, formData.options);
event.preventDefault();
}
});
//add active state on vclick
$.mobile.document.bind("vclick", function (event) {
var $btn, btnEls, target = event.target, needClosest = false;
// if this isn't a left click we don't care. Its important to note
// that when the virtual event is generated it will create the which attr
if (event.which > 1 || !$.mobile.linkBindingEnabled) {
return;
}
// Record that this element was clicked, in case we need it for correct
// form submission during the "submit" handler above
$lastVClicked = $(target);
// Try to find a target element to which the active class will be applied
if ($.data(target, "mobile-button")) {
// If the form will not be submitted via AJAX, do not add active class
if (!getAjaxFormData($(target).closest("form"), true)) {
return;
}
// We will apply the active state to this button widget - the parent
// of the input that was clicked will have the associated data
if (target.parentNode) {
target = target.parentNode;
}
} else {
target = findClosestLink(target);
if (!( target && path.parseUrl(target.getAttribute("href") || "#").hash !== "#" )) {
return;
}
// TODO teach $.mobile.hijackable to operate on raw dom elements so the
// link wrapping can be avoided
if (!$(target).jqmHijackable().length) {
return;
}
}
// Avoid calling .closest by using the data set during .buttonMarkup()
// List items have the button data in the parent of the element clicked
if (!!~target.className.indexOf("ui-link-inherit")) {
if (target.parentNode) {
btnEls = $.data(target.parentNode, "buttonElements");
}
// Otherwise, look for the data on the target itself
} else {
btnEls = $.data(target, "buttonElements");
}
// If found, grab the button's outer element
if (btnEls) {
target = btnEls.outer;
} else {
needClosest = true;
}
$btn = $(target);
// If the outer element wasn't found by the our heuristics, use .closest()
if (needClosest) {
$btn = $btn.closest(".ui-btn");
}
if ($btn.length > 0 && !$btn.hasClass("ui-disabled")) {
removeActiveLinkClass(true);
$activeClickedLink = $btn;
$activeClickedLink.addClass($.mobile.activeBtnClass);
}
});
// click routing - direct to HTTP or Ajax, accordingly
$.mobile.document.bind("click", function (event) {
if (!$.mobile.linkBindingEnabled || event.isDefaultPrevented()) {
return;
}
var link = findClosestLink(event.target), $link = $(link), httpCleanup;
// If there is no link associated with the click or its not a left
// click we want to ignore the click
// TODO teach $.mobile.hijackable to operate on raw dom elements so the link wrapping
// can be avoided
if (!link || event.which > 1 || !$link.jqmHijackable().length) {
return;
}
//remove active link class if external (then it won't be there if you come back)
httpCleanup = function () {
window.setTimeout(function () {
removeActiveLinkClass(true);
}, 200);
};
//if there's a data-rel=back attr, go back in history
if ($link.is(":jqmData(rel='back')")) {
$.mobile.back();
return false;
}
var baseUrl = getClosestBaseUrl($link),
//get href, if defined, otherwise default to empty hash
href = path.makeUrlAbsolute($link.attr("href") || "#", baseUrl);
//if ajax is disabled, exit early
if (!$.mobile.ajaxEnabled && !path.isEmbeddedPage(href)) {
httpCleanup();
//use default click handling
return;
}
// XXX_jblas: Ideally links to application pages should be specified as
// an url to the application document with a hash that is either
// the site relative path or id to the page. But some of the
// internal code that dynamically generates sub-pages for nested
// lists and select dialogs, just write a hash in the link they
// create. This means the actual URL path is based on whatever
// the current value of the base tag is at the time this code
// is called. For now we are just assuming that any url with a
// hash in it is an application page reference.
if (href.search("#") !== -1) {
href = href.replace(/[^#]*#/, "");
if (!href) {
//link was an empty hash meant purely
//for interaction, so we ignore it.
event.preventDefault();
return;
} else if (path.isPath(href)) {
//we have apath so make it the href we want to load.
href = path.makeUrlAbsolute(href, baseUrl);
} else {
//we have a simple id so use the documentUrl as its base.
href = path.makeUrlAbsolute("#" + href, documentUrl.hrefNoHash);
}
}
// Should we handle this link, or let the browser deal with it?
var useDefaultUrlHandling = $link.is("[rel='external']") || $link.is(":jqmData(ajax='false')") || $link.is("[target]"),
// Some embedded browsers, like the web view in Phone Gap, allow cross-domain XHR
// requests if the document doing the request was loaded via the file:// protocol.
// This is usually to allow the application to "phone home" and fetch app specific
// data. We normally let the browser handle external/cross-domain urls, but if the
// allowCrossDomainPages option is true, we will allow cross-domain http/https
// requests to go through our page loading logic.
//check for protocol or rel and its not an embedded page
//TODO overlap in logic from isExternal, rel=external check should be
// moved into more comprehensive isExternalLink
isExternal = useDefaultUrlHandling || ( path.isExternal(href) && !path.isPermittedCrossDomainRequest(documentUrl, href) );
if (isExternal) {
httpCleanup();
//use default click handling
return;
}
//use ajax
var transition = $link.jqmData("transition"),
reverse = $link.jqmData("direction") === "reverse" ||
// deprecated - remove by 1.0
$link.jqmData("back"),
//this may need to be more specific as we use data-rel more
role = $link.attr("data-" + $.mobile.ns + "rel") || undefined;
$.mobile.changePage(href, { transition: transition, reverse: reverse, role: role, link: $link });
event.preventDefault();
});
//prefetch pages when anchors with data-prefetch are encountered
$.mobile.document.delegate(".ui-page", "pageshow.prefetch", function () {
var urls = [];
$(this).find("a:jqmData(prefetch)").each(function () {
var $link = $(this),
url = $link.attr("href");
if (url && $.inArray(url, urls) === -1) {
urls.push(url);
$.mobile.loadPage(url, { role: $link.attr("data-" + $.mobile.ns + "rel"), prefetch: true });
}
});
});
$.mobile._handleHashChange = function (url, data) {
//find first page via hash
var to = path.stripHash(url),
//transition is false if it's the first page, undefined otherwise (and may be overridden by default)
transition = $.mobile.urlHistory.stack.length === 0 ? "none" : undefined,
// default options for the changPage calls made after examining the current state
// of the page and the hash, NOTE that the transition is derived from the previous
// history entry
changePageOptions = {
changeHash: false,
fromHashChange: true,
reverse: data.direction === "back"
};
$.extend(changePageOptions, data, {
transition: (urlHistory.getLast() || {}).transition || transition
});
// special case for dialogs
if (urlHistory.activeIndex > 0 && to.indexOf(dialogHashKey) > -1 && urlHistory.initialDst !== to) {
// If current active page is not a dialog skip the dialog and continue
// in the same direction
if ($.mobile.activePage && !$.mobile.activePage.is(".ui-dialog")) {
//determine if we're heading forward or backward and continue accordingly past
//the current dialog
if (data.direction === "back") {
$.mobile.back();
} else {
window.history.forward();
}
// prevent changePage call
return;
} else {
// if the current active page is a dialog and we're navigating
// to a dialog use the dialog objected saved in the stack
to = data.pageUrl;
var active = $.mobile.urlHistory.getActive();
// make sure to set the role, transition and reversal
// as most of this is lost by the domCache cleaning
$.extend(changePageOptions, {
role: active.role,
transition: active.transition,
reverse: data.direction === "back"
});
}
}
//if to is defined, load it
if (to) {
// At this point, 'to' can be one of 3 things, a cached page element from
// a history stack entry, an id, or site-relative/absolute URL. If 'to' is
// an id, we need to resolve it against the documentBase, not the location.href,
// since the hashchange could've been the result of a forward/backward navigation
// that crosses from an external page/dialog to an internal page/dialog.
to = !path.isPath(to) ? ( path.makeUrlAbsolute('#' + to, documentBase) ) : to;
// If we're about to go to an initial URL that contains a reference to a non-existent
// internal page, go to the first page instead. We know that the initial hash refers to a
// non-existent page, because the initial hash did not end up in the initial urlHistory entry
if (to === path.makeUrlAbsolute('#' + urlHistory.initialDst, documentBase) &&
urlHistory.stack.length && urlHistory.stack[0].url !== urlHistory.initialDst.replace(dialogHashKey, "")) {
to = $.mobile.firstPage;
}
$.mobile.changePage(to, changePageOptions);
} else {
//there's no hash, go to the first page in the dom
$.mobile.changePage($.mobile.firstPage, changePageOptions);
}
};
// TODO roll the logic here into the handleHashChange method
$window.bind("navigate", function (e, data) {
var url;
if (e.originalEvent && e.originalEvent.isDefaultPrevented()) {
return;
}
url = $.event.special.navigate.originalEventName.indexOf("hashchange") > -1 ? data.state.hash : data.state.url;
if (!url) {
url = $.mobile.path.parseLocation().hash;
}
if (!url || url === "#" || url.indexOf("#" + $.mobile.path.uiStateKey) === 0) {
url = location.href;
}
$.mobile._handleHashChange(url, data.state);
});
//set page min-heights to be device specific
$.mobile.document.bind("pageshow", $.mobile.resetActivePageHeight);
$.mobile.window.bind("throttledresize", $.mobile.resetActivePageHeight);
};//navreadyDeferred done callback
$(function () {
domreadyDeferred.resolve();
});
$.when(domreadyDeferred, $.mobile.navreadyDeferred).done(function () {
$.mobile._registerInternalEvents();
});
})(jQuery);
/*
* fallback transition for flip in non-3D supporting browsers (which tend to handle complex transitions poorly in general
*/
(function ($, window, undefined) {
$.mobile.transitionFallbacks.flip = "fade";
})(jQuery, this);
/*
* fallback transition for flow in non-3D supporting browsers (which tend to handle complex transitions poorly in general
*/
(function ($, window, undefined) {
$.mobile.transitionFallbacks.flow = "fade";
})(jQuery, this);
/*
* fallback transition for pop in non-3D supporting browsers (which tend to handle complex transitions poorly in general
*/
(function ($, window, undefined) {
$.mobile.transitionFallbacks.pop = "fade";
})(jQuery, this);
/*
* fallback transition for slide in non-3D supporting browsers (which tend to handle complex transitions poorly in general
*/
(function ($, window, undefined) {
// Use the simultaneous transitions handler for slide transitions
$.mobile.transitionHandlers.slide = $.mobile.transitionHandlers.simultaneous;
// Set the slide transitions's fallback to "fade"
$.mobile.transitionFallbacks.slide = "fade";
})(jQuery, this);
/*
* fallback transition for slidedown in non-3D supporting browsers (which tend to handle complex transitions poorly in general
*/
(function ($, window, undefined) {
$.mobile.transitionFallbacks.slidedown = "fade";
})(jQuery, this);
/*
* fallback transition for slidefade in non-3D supporting browsers (which tend to handle complex transitions poorly in general
*/
(function ($, window, undefined) {
// Set the slide transitions's fallback to "fade"
$.mobile.transitionFallbacks.slidefade = "fade";
})(jQuery, this);
/*
* fallback transition for slideup in non-3D supporting browsers (which tend to handle complex transitions poorly in general
*/
(function ($, window, undefined) {
$.mobile.transitionFallbacks.slideup = "fade";
})(jQuery, this);
/*
* fallback transition for turn in non-3D supporting browsers (which tend to handle complex transitions poorly in general
*/
(function ($, window, undefined) {
$.mobile.transitionFallbacks.turn = "fade";
})(jQuery, this);
(function ($, undefined) {
$.mobile.page.prototype.options.degradeInputs = {
color: false,
date: false,
datetime: false,
"datetime-local": false,
email: false,
month: false,
number: false,
range: "number",
search: "text",
tel: false,
time: false,
url: false,
week: false
};
//auto self-init widgets
$.mobile.document.bind("pagecreate create", function (e) {
var page = $.mobile.closestPageData($(e.target)), options;
if (!page) {
return;
}
options = page.options;
// degrade inputs to avoid poorly implemented native functionality
$(e.target).find("input").not(page.keepNativeSelector()).each(function () {
var $this = $(this),
type = this.getAttribute("type"),
optType = options.degradeInputs[ type ] || "text";
if (options.degradeInputs[ type ]) {
var html = $("<div>").html($this.clone()).html(),
// In IE browsers, the type sometimes doesn't exist in the cloned markup, so we replace the closing tag instead
hasType = html.indexOf(" type=") > -1,
findstr = hasType ? /\s+type=["']?\w+['"]?/ : /\/?>/,
repstr = " type=\"" + optType + "\" data-" + $.mobile.ns + "type=\"" + type + "\"" + ( hasType ? "" : ">" );
$this.replaceWith(html.replace(findstr, repstr));
}
});
});
})(jQuery);
(function ($, window, undefined) {
$.widget("mobile.dialog", $.mobile.widget, {
options: {
closeBtn: "left",
closeBtnText: "Close",
overlayTheme: "a",
corners: true,
initSelector: ":jqmData(role='dialog')"
},
// Override the theme set by the page plugin on pageshow
_handlePageBeforeShow: function () {
this._isCloseable = true;
if (this.options.overlayTheme) {
this.element
.page("removeContainerBackground")
.page("setContainerBackground", this.options.overlayTheme);
}
},
_handlePageBeforeHide: function () {
this._isCloseable = false;
},
_create: function () {
var self = this,
$el = this.element,
cornerClass = !!this.options.corners ? " ui-corner-all" : "",
dialogWrap = $("<div/>", {
"role": "dialog",
"class": "ui-dialog-contain ui-overlay-shadow" + cornerClass
});
$el.addClass("ui-dialog ui-overlay-" + this.options.overlayTheme);
// Class the markup for dialog styling
// Set aria role
$el.wrapInner(dialogWrap);
/* bind events
- clicks and submits should use the closing transition that the dialog opened with
unless a data-transition is specified on the link/form
- if the click was on the close button, or the link has a data-rel="back" it'll go back in history naturally
*/
$el.bind("vclick submit", function (event) {
var $target = $(event.target).closest(event.type === "vclick" ? "a" : "form"),
active;
if ($target.length && !$target.jqmData("transition")) {
active = $.mobile.urlHistory.getActive() || {};
$target.attr("data-" + $.mobile.ns + "transition", ( active.transition || $.mobile.defaultDialogTransition ))
.attr("data-" + $.mobile.ns + "direction", "reverse");
}
});
this._on($el, {
pagebeforeshow: "_handlePageBeforeShow",
pagebeforehide: "_handlePageBeforeHide"
});
$.extend(this, {
_createComplete: false
});
this._setCloseBtn(this.options.closeBtn);
},
_setCloseBtn: function (value) {
var self = this, btn, location;
if (this._headerCloseButton) {
this._headerCloseButton.remove();
this._headerCloseButton = null;
}
if (value !== "none") {
// Sanitize value
location = ( value === "left" ? "left" : "right" );
btn = $("<a href='#' class='ui-btn-" + location + "' data-" + $.mobile.ns + "icon='delete' data-" + $.mobile.ns + "iconpos='notext'>" + this.options.closeBtnText + "</a>");
this.element.children().find(":jqmData(role='header')").first().prepend(btn);
if (this._createComplete && $.fn.buttonMarkup) {
btn.buttonMarkup();
}
this._createComplete = true;
// this must be an anonymous function so that select menu dialogs can replace
// the close method. This is a change from previously just defining data-rel=back
// on the button and letting nav handle it
//
// Use click rather than vclick in order to prevent the possibility of unintentionally
// reopening the dialog if the dialog opening item was directly under the close button.
btn.bind("click", function () {
self.close();
});
this._headerCloseButton = btn;
}
},
_setOption: function (key, value) {
if (key === "closeBtn") {
this._setCloseBtn(value);
}
this._super(key, value);
},
// Close method goes back in history
close: function () {
var idx, dst, hist = $.mobile.navigate.history;
if (this._isCloseable) {
this._isCloseable = false;
// If the hash listening is enabled and there is at least one preceding history
// entry it's ok to go back. Initial pages with the dialog hash state are an example
// where the stack check is necessary
if ($.mobile.hashListeningEnabled && hist.activeIndex > 0) {
$.mobile.back();
} else {
idx = Math.max(0, hist.activeIndex - 1);
dst = hist.stack[ idx ].pageUrl || hist.stack[ idx ].url;
hist.previousIndex = hist.activeIndex;
hist.activeIndex = idx;
if (!$.mobile.path.isPath(dst)) {
dst = $.mobile.path.makeUrlAbsolute("#" + dst);
}
$.mobile.changePage(dst, { direction: "back", changeHash: false, fromHashChange: true });
}
}
}
});
//auto self-init widgets
$.mobile.document.delegate($.mobile.dialog.prototype.options.initSelector, "pagecreate", function () {
$.mobile.dialog.prototype.enhance(this);
});
})(jQuery, this);
(function ($, undefined) {
$.mobile.page.prototype.options.backBtnText = "Back";
$.mobile.page.prototype.options.addBackBtn = false;
$.mobile.page.prototype.options.backBtnTheme = null;
$.mobile.page.prototype.options.headerTheme = "a";
$.mobile.page.prototype.options.footerTheme = "a";
$.mobile.page.prototype.options.contentTheme = null;
// NOTE bind used to force this binding to run before the buttonMarkup binding
// which expects .ui-footer top be applied in its gigantic selector
// TODO remove the buttonMarkup giant selector and move it to the various modules
// on which it depends
$.mobile.document.bind("pagecreate", function (e) {
var $page = $(e.target),
o = $page.data("mobile-page").options,
pageRole = $page.jqmData("role"),
pageTheme = o.theme;
$(":jqmData(role='header'), :jqmData(role='footer'), :jqmData(role='content')", $page)
.jqmEnhanceable()
.each(function () {
var $this = $(this),
role = $this.jqmData("role"),
theme = $this.jqmData("theme"),
contentTheme = theme || o.contentTheme || ( pageRole === "dialog" && pageTheme ),
$headeranchors,
leftbtn,
rightbtn,
backBtn;
$this.addClass("ui-" + role);
//apply theming and markup modifications to page,header,content,footer
if (role === "header" || role === "footer") {
var thisTheme = theme || ( role === "header" ? o.headerTheme : o.footerTheme ) || pageTheme;
$this
//add theme class
.addClass("ui-bar-" + thisTheme)
// Add ARIA role
.attr("role", role === "header" ? "banner" : "contentinfo");
if (role === "header") {
// Right,left buttons
$headeranchors = $this.children("a, button");
leftbtn = $headeranchors.hasClass("ui-btn-left");
rightbtn = $headeranchors.hasClass("ui-btn-right");
leftbtn = leftbtn || $headeranchors.eq(0).not(".ui-btn-right").addClass("ui-btn-left").length;
rightbtn = rightbtn || $headeranchors.eq(1).addClass("ui-btn-right").length;
}
// Auto-add back btn on pages beyond first view
if (o.addBackBtn &&
role === "header" &&
$(".ui-page").length > 1 &&
$page.jqmData("url") !== $.mobile.path.stripHash(location.hash) && !leftbtn) {
backBtn = $("<a href='javascript:void(0);' class='ui-btn-left' data-" + $.mobile.ns + "rel='back' data-" + $.mobile.ns + "icon='arrow-l'>" + o.backBtnText + "</a>")
// If theme is provided, override default inheritance
.attr("data-" + $.mobile.ns + "theme", o.backBtnTheme || thisTheme)
.prependTo($this);
}
// Page title
$this.children("h1, h2, h3, h4, h5, h6")
.addClass("ui-title")
// Regardless of h element number in src, it becomes h1 for the enhanced page
.attr({
"role": "heading",
"aria-level": "1"
});
} else if (role === "content") {
if (contentTheme) {
$this.addClass("ui-body-" + ( contentTheme ));
}
// Add ARIA role
$this.attr("role", "main");
}
});
});
})(jQuery);
(function ($, undefined) {
// This function calls getAttribute, which should be safe for data-* attributes
var getAttrFixed = function (e, key) {
var value = e.getAttribute(key);
return value === "true" ? true :
value === "false" ? false :
value === null ? undefined : value;
};
$.fn.buttonMarkup = function (options) {
var $workingSet = this,
nsKey = "data-" + $.mobile.ns,
key;
// Enforce options to be of type string
options = ( options && ( $.type(options) === "object" ) ) ? options : {};
for (var i = 0; i < $workingSet.length; i++) {
var el = $workingSet.eq(i),
e = el[ 0 ],
o = $.extend({}, $.fn.buttonMarkup.defaults, {
icon: options.icon !== undefined ? options.icon : getAttrFixed(e, nsKey + "icon"),
iconpos: options.iconpos !== undefined ? options.iconpos : getAttrFixed(e, nsKey + "iconpos"),
theme: options.theme !== undefined ? options.theme : getAttrFixed(e, nsKey + "theme") || $.mobile.getInheritedTheme(el, "c"),
inline: options.inline !== undefined ? options.inline : getAttrFixed(e, nsKey + "inline"),
shadow: options.shadow !== undefined ? options.shadow : getAttrFixed(e, nsKey + "shadow"),
corners: options.corners !== undefined ? options.corners : getAttrFixed(e, nsKey + "corners"),
iconshadow: options.iconshadow !== undefined ? options.iconshadow : getAttrFixed(e, nsKey + "iconshadow"),
mini: options.mini !== undefined ? options.mini : getAttrFixed(e, nsKey + "mini")
}, options),
// Classes Defined
innerClass = "ui-btn-inner",
textClass = "ui-btn-text",
buttonClass, iconClass,
hover = false,
state = "up",
// Button inner markup
buttonInner,
buttonText,
buttonIcon,
buttonElements;
for (key in o) {
if (o[ key ] === undefined || o[ key ] === null) {
el.removeAttr(nsKey + key);
} else {
e.setAttribute(nsKey + key, o[ key ]);
}
}
// Check if this element is already enhanced
buttonElements = $.data(( ( e.tagName === "INPUT" || e.tagName === "BUTTON" ) ? e.parentNode : e ), "buttonElements");
if (buttonElements) {
e = buttonElements.outer;
el = $(e);
buttonInner = buttonElements.inner;
buttonText = buttonElements.text;
// We will recreate this icon below
$(buttonElements.icon).remove();
buttonElements.icon = null;
hover = buttonElements.hover;
state = buttonElements.state;
}
else {
buttonInner = document.createElement(o.wrapperEls);
buttonText = document.createElement(o.wrapperEls);
}
buttonIcon = o.icon ? document.createElement("span") : null;
if (attachEvents && !buttonElements) {
attachEvents();
}
// if not, try to find closest theme container
if (!o.theme) {
o.theme = $.mobile.getInheritedTheme(el, "c");
}
buttonClass = "ui-btn ";
buttonClass += ( hover ? "ui-btn-hover-" + o.theme : "" );
buttonClass += ( state ? " ui-btn-" + state + "-" + o.theme : "" );
buttonClass += o.shadow ? " ui-shadow" : "";
buttonClass += o.corners ? " ui-btn-corner-all" : "";
if (o.mini !== undefined) {
// Used to control styling in headers/footers, where buttons default to `mini` style.
buttonClass += o.mini === true ? " ui-mini" : " ui-fullsize";
}
if (o.inline !== undefined) {
// Used to control styling in headers/footers, where buttons default to `inline` style.
buttonClass += o.inline === true ? " ui-btn-inline" : " ui-btn-block";
}
if (o.icon) {
o.icon = "ui-icon-" + o.icon;
o.iconpos = o.iconpos || "left";
iconClass = "ui-icon " + o.icon;
if (o.iconshadow) {
iconClass += " ui-icon-shadow";
}
}
if (o.iconpos) {
buttonClass += " ui-btn-icon-" + o.iconpos;
if (o.iconpos === "notext" && !el.attr("title")) {
el.attr("title", el.getEncodedText());
}
}
if (buttonElements) {
el.removeClass(buttonElements.bcls || "");
}
el.removeClass("ui-link").addClass(buttonClass);
buttonInner.className = innerClass;
buttonText.className = textClass;
if (!buttonElements) {
buttonInner.appendChild(buttonText);
}
if (buttonIcon) {
buttonIcon.className = iconClass;
if (!( buttonElements && buttonElements.icon )) {
buttonIcon.innerHTML = " ";
buttonInner.appendChild(buttonIcon);
}
}
while (e.firstChild && !buttonElements) {
buttonText.appendChild(e.firstChild);
}
if (!buttonElements) {
e.appendChild(buttonInner);
}
// Assign a structure containing the elements of this button to the elements of this button. This
// will allow us to recognize this as an already-enhanced button in future calls to buttonMarkup().
buttonElements = {
hover: hover,
state: state,
bcls: buttonClass,
outer: e,
inner: buttonInner,
text: buttonText,
icon: buttonIcon
};
$.data(e, 'buttonElements', buttonElements);
$.data(buttonInner, 'buttonElements', buttonElements);
$.data(buttonText, 'buttonElements', buttonElements);
if (buttonIcon) {
$.data(buttonIcon, 'buttonElements', buttonElements);
}
}
return this;
};
$.fn.buttonMarkup.defaults = {
corners: true,
shadow: true,
iconshadow: true,
wrapperEls: "span"
};
function closestEnabledButton(element) {
var cname;
while (element) {
// Note that we check for typeof className below because the element we
// handed could be in an SVG DOM where className on SVG elements is defined to
// be of a different type (SVGAnimatedString). We only operate on HTML DOM
// elements, so we look for plain "string".
cname = ( typeof element.className === 'string' ) && ( element.className + ' ' );
if (cname && cname.indexOf("ui-btn ") > -1 && cname.indexOf("ui-disabled ") < 0) {
break;
}
element = element.parentNode;
}
return element;
}
function updateButtonClass($btn, classToRemove, classToAdd, hover, state) {
var buttonElements = $.data($btn[ 0 ], "buttonElements");
$btn.removeClass(classToRemove).addClass(classToAdd);
if (buttonElements) {
buttonElements.bcls = $(document.createElement("div"))
.addClass(buttonElements.bcls + " " + classToAdd)
.removeClass(classToRemove)
.attr("class");
if (hover !== undefined) {
buttonElements.hover = hover;
}
buttonElements.state = state;
}
}
var attachEvents = function () {
var hoverDelay = $.mobile.buttonMarkup.hoverDelay, hov, foc;
$.mobile.document.bind({
"vmousedown vmousecancel vmouseup vmouseover vmouseout focus blur scrollstart": function (event) {
var theme,
$btn = $(closestEnabledButton(event.target)),
isTouchEvent = event.originalEvent && /^touch/.test(event.originalEvent.type),
evt = event.type;
if ($btn.length) {
theme = $btn.attr("data-" + $.mobile.ns + "theme");
if (evt === "vmousedown") {
if (isTouchEvent) {
// Use a short delay to determine if the user is scrolling before highlighting
hov = setTimeout(function () {
updateButtonClass($btn, "ui-btn-up-" + theme, "ui-btn-down-" + theme, undefined, "down");
}, hoverDelay);
} else {
updateButtonClass($btn, "ui-btn-up-" + theme, "ui-btn-down-" + theme, undefined, "down");
}
} else if (evt === "vmousecancel" || evt === "vmouseup") {
updateButtonClass($btn, "ui-btn-down-" + theme, "ui-btn-up-" + theme, undefined, "up");
} else if (evt === "vmouseover" || evt === "focus") {
if (isTouchEvent) {
// Use a short delay to determine if the user is scrolling before highlighting
foc = setTimeout(function () {
updateButtonClass($btn, "ui-btn-up-" + theme, "ui-btn-hover-" + theme, true, "");
}, hoverDelay);
} else {
updateButtonClass($btn, "ui-btn-up-" + theme, "ui-btn-hover-" + theme, true, "");
}
} else if (evt === "vmouseout" || evt === "blur" || evt === "scrollstart") {
updateButtonClass($btn, "ui-btn-hover-" + theme + " ui-btn-down-" + theme, "ui-btn-up-" + theme, false, "up");
if (hov) {
clearTimeout(hov);
}
if (foc) {
clearTimeout(foc);
}
}
}
},
"focusin focus": function (event) {
$(closestEnabledButton(event.target)).addClass($.mobile.focusClass);
},
"focusout blur": function (event) {
$(closestEnabledButton(event.target)).removeClass($.mobile.focusClass);
}
});
attachEvents = null;
};
//links in bars, or those with data-role become buttons
//auto self-init widgets
$.mobile.document.bind("pagecreate create", function (e) {
$(":jqmData(role='button'), .ui-bar > a, .ui-header > a, .ui-footer > a, .ui-bar > :jqmData(role='controlgroup') > a", e.target)
.jqmEnhanceable()
.not("button, input, .ui-btn, :jqmData(role='none'), :jqmData(role='nojs')")
.buttonMarkup();
});
})(jQuery);
(function ($, undefined) {
$.widget("mobile.collapsible", $.mobile.widget, {
options: {
expandCueText: " click to expand contents",
collapseCueText: " click to collapse contents",
collapsed: true,
heading: "h1,h2,h3,h4,h5,h6,legend",
collapsedIcon: "plus",
expandedIcon: "minus",
iconpos: "left",
theme: null,
contentTheme: null,
inset: true,
corners: true,
mini: false,
initSelector: ":jqmData(role='collapsible')"
},
_create: function () {
var $el = this.element,
o = this.options,
collapsible = $el.addClass("ui-collapsible"),
collapsibleHeading = $el.children(o.heading).first(),
collapsibleContent = collapsible.wrapInner("<div class='ui-collapsible-content'></div>").children(".ui-collapsible-content"),
collapsibleSet = $el.closest(":jqmData(role='collapsible-set')").addClass("ui-collapsible-set"),
collapsibleClasses = "";
// Replace collapsibleHeading if it's a legend
if (collapsibleHeading.is("legend")) {
collapsibleHeading = $("<div role='heading'>" + collapsibleHeading.html() + "</div>").insertBefore(collapsibleHeading);
collapsibleHeading.next().remove();
}
// If we are in a collapsible set
if (collapsibleSet.length) {
// Inherit the theme from collapsible-set
if (!o.theme) {
o.theme = collapsibleSet.jqmData("theme") || $.mobile.getInheritedTheme(collapsibleSet, "c");
}
// Inherit the content-theme from collapsible-set
if (!o.contentTheme) {
o.contentTheme = collapsibleSet.jqmData("content-theme");
}
// Get the preference for collapsed icon in the set, but override with data- attribute on the individual collapsible
o.collapsedIcon = $el.jqmData("collapsed-icon") || collapsibleSet.jqmData("collapsed-icon") || o.collapsedIcon;
// Get the preference for expanded icon in the set, but override with data- attribute on the individual collapsible
o.expandedIcon = $el.jqmData("expanded-icon") || collapsibleSet.jqmData("expanded-icon") || o.expandedIcon;
// Gets the preference icon position in the set, but override with data- attribute on the individual collapsible
o.iconpos = $el.jqmData("iconpos") || collapsibleSet.jqmData("iconpos") || o.iconpos;
// Inherit the preference for inset from collapsible-set or set the default value to ensure equalty within a set
if (collapsibleSet.jqmData("inset") !== undefined) {
o.inset = collapsibleSet.jqmData("inset");
} else {
o.inset = true;
}
// Set corners for individual collapsibles to false when in a collapsible-set
o.corners = false;
// Gets the preference for mini in the set
if (!o.mini) {
o.mini = collapsibleSet.jqmData("mini");
}
} else {
// get inherited theme if not a set and no theme has been set
if (!o.theme) {
o.theme = $.mobile.getInheritedTheme($el, "c");
}
}
if (!!o.inset) {
collapsibleClasses += " ui-collapsible-inset";
if (!!o.corners) {
collapsibleClasses += " ui-corner-all";
}
}
if (o.contentTheme) {
collapsibleClasses += " ui-collapsible-themed-content";
collapsibleContent.addClass("ui-body-" + o.contentTheme);
}
if (collapsibleClasses !== "") {
collapsible.addClass(collapsibleClasses);
}
collapsibleHeading
//drop heading in before content
.insertBefore(collapsibleContent)
//modify markup & attributes
.addClass("ui-collapsible-heading")
.append("<span class='ui-collapsible-heading-status'></span>")
.wrapInner("<a href='#' class='ui-collapsible-heading-toggle'></a>")
.find("a")
.first()
.buttonMarkup({
shadow: false,
corners: false,
iconpos: o.iconpos,
icon: o.collapsedIcon,
mini: o.mini,
theme: o.theme
});
//events
collapsible
.bind("expand collapse", function (event) {
if (!event.isDefaultPrevented()) {
var $this = $(this),
isCollapse = ( event.type === "collapse" );
event.preventDefault();
collapsibleHeading
.toggleClass("ui-collapsible-heading-collapsed", isCollapse)
.find(".ui-collapsible-heading-status")
.text(isCollapse ? o.expandCueText : o.collapseCueText)
.end()
.find(".ui-icon")
.toggleClass("ui-icon-" + o.expandedIcon, !isCollapse)
// logic or cause same icon for expanded/collapsed state would remove the ui-icon-class
.toggleClass("ui-icon-" + o.collapsedIcon, ( isCollapse || o.expandedIcon === o.collapsedIcon ))
.end()
.find("a").first().removeClass($.mobile.activeBtnClass);
$this.toggleClass("ui-collapsible-collapsed", isCollapse);
collapsibleContent.toggleClass("ui-collapsible-content-collapsed", isCollapse).attr("aria-hidden", isCollapse);
collapsibleContent.trigger("updatelayout");
}
})
.trigger(o.collapsed ? "collapse" : "expand");
collapsibleHeading
.bind("tap", function (event) {
collapsibleHeading.find("a").first().addClass($.mobile.activeBtnClass);
})
.bind("click", function (event) {
var type = collapsibleHeading.is(".ui-collapsible-heading-collapsed") ? "expand" : "collapse";
collapsible.trigger(type);
event.preventDefault();
event.stopPropagation();
});
}
});
//auto self-init widgets
$.mobile.document.bind("pagecreate create", function (e) {
$.mobile.collapsible.prototype.enhanceWithin(e.target);
});
})(jQuery);
(function ($, undefined) {
$.mobile.behaviors.addFirstLastClasses = {
_getVisibles: function ($els, create) {
var visibles;
if (create) {
visibles = $els.not(".ui-screen-hidden");
} else {
visibles = $els.filter(":visible");
if (visibles.length === 0) {
visibles = $els.not(".ui-screen-hidden");
}
}
return visibles;
},
_addFirstLastClasses: function ($els, $visibles, create) {
$els.removeClass("ui-first-child ui-last-child");
$visibles.eq(0).addClass("ui-first-child").end().last().addClass("ui-last-child");
if (!create) {
this.element.trigger("updatelayout");
}
}
};
})(jQuery);
(function ($, undefined) {
$.widget("mobile.collapsibleset", $.mobile.widget, $.extend({
options: {
initSelector: ":jqmData(role='collapsible-set')"
},
_create: function () {
var $el = this.element.addClass("ui-collapsible-set"),
o = this.options;
// Inherit the theme from collapsible-set
if (!o.theme) {
o.theme = $.mobile.getInheritedTheme($el, "c");
}
// Inherit the content-theme from collapsible-set
if (!o.contentTheme) {
o.contentTheme = $el.jqmData("content-theme");
}
// Inherit the corner styling from collapsible-set
if (!o.corners) {
o.corners = $el.jqmData("corners");
}
if ($el.jqmData("inset") !== undefined) {
o.inset = $el.jqmData("inset");
}
o.inset = o.inset !== undefined ? o.inset : true;
o.corners = o.corners !== undefined ? o.corners : true;
if (!!o.corners && !!o.inset) {
$el.addClass("ui-corner-all");
}
// Initialize the collapsible set if it's not already initialized
if (!$el.jqmData("collapsiblebound")) {
$el
.jqmData("collapsiblebound", true)
.bind("expand", function (event) {
var closestCollapsible = $(event.target)
.closest(".ui-collapsible");
if (closestCollapsible.parent().is(":jqmData(role='collapsible-set')")) {
closestCollapsible
.siblings(".ui-collapsible")
.trigger("collapse");
}
});
}
},
_init: function () {
var $el = this.element,
collapsiblesInSet = $el.children(":jqmData(role='collapsible')"),
expanded = collapsiblesInSet.filter(":jqmData(collapsed='false')");
this._refresh("true");
// Because the corners are handled by the collapsible itself and the default state is collapsed
// That was causing https://github.com/jquery/jquery-mobile/issues/4116
expanded.trigger("expand");
},
_refresh: function (create) {
var collapsiblesInSet = this.element.children(":jqmData(role='collapsible')");
$.mobile.collapsible.prototype.enhance(collapsiblesInSet.not(".ui-collapsible"));
this._addFirstLastClasses(collapsiblesInSet, this._getVisibles(collapsiblesInSet, create), create);
},
refresh: function () {
this._refresh(false);
}
}, $.mobile.behaviors.addFirstLastClasses));
//auto self-init widgets
$.mobile.document.bind("pagecreate create", function (e) {
$.mobile.collapsibleset.prototype.enhanceWithin(e.target);
});
})(jQuery);
(function ($, undefined) {
// filter function removes whitespace between label and form element so we can use inline-block (nodeType 3 = text)
$.fn.fieldcontain = function (options) {
return this
.addClass("ui-field-contain ui-body ui-br")
.contents().filter(function () {
return ( this.nodeType === 3 && !/\S/.test(this.nodeValue) );
}).remove();
};
//auto self-init widgets
$(document).bind("pagecreate create", function (e) {
$(":jqmData(role='fieldcontain')", e.target).jqmEnhanceable().fieldcontain();
});
})(jQuery);
(function ($, undefined) {
$.fn.grid = function (options) {
return this.each(function () {
var $this = $(this),
o = $.extend({
grid: null
}, options),
$kids = $this.children(),
gridCols = { solo: 1, a: 2, b: 3, c: 4, d: 5 },
grid = o.grid,
iterator;
if (!grid) {
if ($kids.length <= 5) {
for (var letter in gridCols) {
if (gridCols[ letter ] === $kids.length) {
grid = letter;
}
}
} else {
grid = "a";
$this.addClass("ui-grid-duo");
}
}
iterator = gridCols[grid];
$this.addClass("ui-grid-" + grid);
$kids.filter(":nth-child(" + iterator + "n+1)").addClass("ui-block-a");
if (iterator > 1) {
$kids.filter(":nth-child(" + iterator + "n+2)").addClass("ui-block-b");
}
if (iterator > 2) {
$kids.filter(":nth-child(" + iterator + "n+3)").addClass("ui-block-c");
}
if (iterator > 3) {
$kids.filter(":nth-child(" + iterator + "n+4)").addClass("ui-block-d");
}
if (iterator > 4) {
$kids.filter(":nth-child(" + iterator + "n+5)").addClass("ui-block-e");
}
});
};
})(jQuery);
(function ($, undefined) {
$.widget("mobile.navbar", $.mobile.widget, {
options: {
iconpos: "top",
grid: null,
initSelector: ":jqmData(role='navbar')"
},
_create: function () {
var $navbar = this.element,
$navbtns = $navbar.find("a"),
iconpos = $navbtns.filter(":jqmData(icon)").length ?
this.options.iconpos : undefined;
$navbar.addClass("ui-navbar ui-mini")
.attr("role", "navigation")
.find("ul")
.jqmEnhanceable()
.grid({ grid: this.options.grid });
$navbtns.buttonMarkup({
corners: false,
shadow: false,
inline: true,
iconpos: iconpos
});
$navbar.delegate("a", "vclick", function (event) {
// ui-btn-inner is returned as target
var target = $(event.target).is("a") ? $(this) : $(this).parent("a");
if (!target.is(".ui-disabled, .ui-btn-active")) {
$navbtns.removeClass($.mobile.activeBtnClass);
$(this).addClass($.mobile.activeBtnClass);
// The code below is a workaround to fix #1181
var activeBtn = $(this);
$(document).one("pagehide", function () {
activeBtn.removeClass($.mobile.activeBtnClass);
});
}
});
// Buttons in the navbar with ui-state-persist class should regain their active state before page show
$navbar.closest(".ui-page").bind("pagebeforeshow", function () {
$navbtns.filter(".ui-state-persist").addClass($.mobile.activeBtnClass);
});
}
});
//auto self-init widgets
$.mobile.document.bind("pagecreate create", function (e) {
$.mobile.navbar.prototype.enhanceWithin(e.target);
});
})(jQuery);
(function ($, undefined) {
//Keeps track of the number of lists per page UID
//This allows support for multiple nested list in the same page
//https://github.com/jquery/jquery-mobile/issues/1617
var listCountPerPage = {};
$.widget("mobile.listview", $.mobile.widget, $.extend({
options: {
theme: null,
countTheme: "c",
headerTheme: "b",
dividerTheme: "b",
icon: "arrow-r",
splitIcon: "arrow-r",
splitTheme: "b",
corners: true,
shadow: true,
inset: false,
initSelector: ":jqmData(role='listview')"
},
_create: function () {
var t = this,
listviewClasses = "";
listviewClasses += t.options.inset ? " ui-listview-inset" : "";
if (!!t.options.inset) {
listviewClasses += t.options.corners ? " ui-corner-all" : "";
listviewClasses += t.options.shadow ? " ui-shadow" : "";
}
// create listview markup
t.element.addClass(function (i, orig) {
return orig + " ui-listview" + listviewClasses;
});
t.refresh(true);
},
// This is a generic utility method for finding the first
// node with a given nodeName. It uses basic DOM traversal
// to be fast and is meant to be a substitute for simple
// $.fn.closest() and $.fn.children() calls on a single
// element. Note that callers must pass both the lowerCase
// and upperCase version of the nodeName they are looking for.
// The main reason for this is that this function will be
// called many times and we want to avoid having to lowercase
// the nodeName from the element every time to ensure we have
// a match. Note that this function lives here for now, but may
// be moved into $.mobile if other components need a similar method.
_findFirstElementByTagName: function (ele, nextProp, lcName, ucName) {
var dict = {};
dict[ lcName ] = dict[ ucName ] = true;
while (ele) {
if (dict[ ele.nodeName ]) {
return ele;
}
ele = ele[ nextProp ];
}
return null;
},
_getChildrenByTagName: function (ele, lcName, ucName) {
var results = [],
dict = {};
dict[ lcName ] = dict[ ucName ] = true;
ele = ele.firstChild;
while (ele) {
if (dict[ ele.nodeName ]) {
results.push(ele);
}
ele = ele.nextSibling;
}
return $(results);
},
_addThumbClasses: function (containers) {
var i, img, len = containers.length;
for (i = 0; i < len; i++) {
img = $(this._findFirstElementByTagName(containers[ i ].firstChild, "nextSibling", "img", "IMG"));
if (img.length) {
img.addClass("ui-li-thumb");
$(this._findFirstElementByTagName(img[ 0 ].parentNode, "parentNode", "li", "LI")).addClass(img.is(".ui-li-icon") ? "ui-li-has-icon" : "ui-li-has-thumb");
}
}
},
refresh: function (create) {
this.parentPage = this.element.closest(".ui-page");
this._createSubPages();
var o = this.options,
$list = this.element,
self = this,
dividertheme = $list.jqmData("dividertheme") || o.dividerTheme,
listsplittheme = $list.jqmData("splittheme"),
listspliticon = $list.jqmData("spliticon"),
listicon = $list.jqmData("icon"),
li = this._getChildrenByTagName($list[ 0 ], "li", "LI"),
ol = !!$.nodeName($list[ 0 ], "ol"),
jsCount = !$.support.cssPseudoElement,
start = $list.attr("start"),
itemClassDict = {},
item, itemClass, itemTheme,
a, last, splittheme, counter, startCount, newStartCount, countParent, icon, imgParents, img, linkIcon;
if (ol && jsCount) {
$list.find(".ui-li-dec").remove();
}
if (ol) {
// Check if a start attribute has been set while taking a value of 0 into account
if (start || start === 0) {
if (!jsCount) {
startCount = parseInt(start, 10) - 1;
$list.css("counter-reset", "listnumbering " + startCount);
} else {
counter = parseInt(start, 10);
}
} else if (jsCount) {
counter = 1;
}
}
if (!o.theme) {
o.theme = $.mobile.getInheritedTheme(this.element, "c");
}
for (var pos = 0, numli = li.length; pos < numli; pos++) {
item = li.eq(pos);
itemClass = "ui-li";
// If we're creating the element, we update it regardless
if (create || !item.hasClass("ui-li")) {
itemTheme = item.jqmData("theme") || o.theme;
a = this._getChildrenByTagName(item[ 0 ], "a", "A");
var isDivider = ( item.jqmData("role") === "list-divider" );
if (a.length && !isDivider) {
icon = item.jqmData("icon");
item.buttonMarkup({
wrapperEls: "div",
shadow: false,
corners: false,
iconpos: "right",
icon: a.length > 1 || icon === false ? false : icon || listicon || o.icon,
theme: itemTheme
});
if (( icon !== false ) && ( a.length === 1 )) {
item.addClass("ui-li-has-arrow");
}
a.first().removeClass("ui-link").addClass("ui-link-inherit");
if (a.length > 1) {
itemClass += " ui-li-has-alt";
last = a.last();
splittheme = listsplittheme || last.jqmData("theme") || o.splitTheme;
linkIcon = last.jqmData("icon");
last.appendTo(item)
.attr("title", $.trim(last.getEncodedText()))
.addClass("ui-li-link-alt")
.empty()
.buttonMarkup({
shadow: false,
corners: false,
theme: itemTheme,
icon: false,
iconpos: "notext"
})
.find(".ui-btn-inner")
.append(
$(document.createElement("span")).buttonMarkup({
shadow: true,
corners: true,
theme: splittheme,
iconpos: "notext",
// link icon overrides list item icon overrides ul element overrides options
icon: linkIcon || icon || listspliticon || o.splitIcon
})
);
}
} else if (isDivider) {
itemClass += " ui-li-divider ui-bar-" + ( item.jqmData("theme") || dividertheme );
item.attr("role", "heading");
if (ol) {
//reset counter when a divider heading is encountered
if (start || start === 0) {
if (!jsCount) {
newStartCount = parseInt(start, 10) - 1;
item.css("counter-reset", "listnumbering " + newStartCount);
} else {
counter = parseInt(start, 10);
}
} else if (jsCount) {
counter = 1;
}
}
} else {
itemClass += " ui-li-static ui-btn-up-" + itemTheme;
}
}
if (ol && jsCount && itemClass.indexOf("ui-li-divider") < 0) {
countParent = itemClass.indexOf("ui-li-static") > 0 ? item : item.find(".ui-link-inherit");
countParent.addClass("ui-li-jsnumbering")
.prepend("<span class='ui-li-dec'>" + ( counter++ ) + ". </span>");
}
// Instead of setting item class directly on the list item and its
// btn-inner at this point in time, push the item into a dictionary
// that tells us what class to set on it so we can do this after this
// processing loop is finished.
if (!itemClassDict[ itemClass ]) {
itemClassDict[ itemClass ] = [];
}
itemClassDict[ itemClass ].push(item[ 0 ]);
}
// Set the appropriate listview item classes on each list item
// and their btn-inner elements. The main reason we didn't do this
// in the for-loop above is because we can eliminate per-item function overhead
// by calling addClass() and children() once or twice afterwards. This
// can give us a significant boost on platforms like WP7.5.
for (itemClass in itemClassDict) {
$(itemClassDict[ itemClass ]).addClass(itemClass).children(".ui-btn-inner").addClass(itemClass);
}
$list.find("h1, h2, h3, h4, h5, h6").addClass("ui-li-heading")
.end()
.find("p, dl").addClass("ui-li-desc")
.end()
.find(".ui-li-aside").each(function () {
var $this = $(this);
$this.prependTo($this.parent()); //shift aside to front for css float
})
.end()
.find(".ui-li-count").each(function () {
$(this).closest("li").addClass("ui-li-has-count");
}).addClass("ui-btn-up-" + ( $list.jqmData("counttheme") || this.options.countTheme) + " ui-btn-corner-all");
// The idea here is to look at the first image in the list item
// itself, and any .ui-link-inherit element it may contain, so we
// can place the appropriate classes on the image and list item.
// Note that we used to use something like:
//
// li.find(">img:eq(0), .ui-link-inherit>img:eq(0)").each( ... );
//
// But executing a find() like that on Windows Phone 7.5 took a
// really long time. Walking things manually with the code below
// allows the 400 listview item page to load in about 3 seconds as
// opposed to 30 seconds.
this._addThumbClasses(li);
this._addThumbClasses($list.find(".ui-link-inherit"));
this._addFirstLastClasses(li, this._getVisibles(li, create), create);
// autodividers binds to this to redraw dividers after the listview refresh
this._trigger("afterrefresh");
},
//create a string for ID/subpage url creation
_idStringEscape: function (str) {
return str.replace(/[^a-zA-Z0-9]/g, '-');
},
_createSubPages: function () {
var parentList = this.element,
parentPage = parentList.closest(".ui-page"),
parentUrl = parentPage.jqmData("url"),
parentId = parentUrl || parentPage[ 0 ][ $.expando ],
parentListId = parentList.attr("id"),
o = this.options,
dns = "data-" + $.mobile.ns,
self = this,
persistentFooterID = parentPage.find(":jqmData(role='footer')").jqmData("id"),
hasSubPages;
if (typeof listCountPerPage[ parentId ] === "undefined") {
listCountPerPage[ parentId ] = -1;
}
parentListId = parentListId || ++listCountPerPage[ parentId ];
$(parentList.find("li>ul, li>ol").toArray().reverse()).each(function (i) {
var self = this,
list = $(this),
listId = list.attr("id") || parentListId + "-" + i,
parent = list.parent(),
nodeElsFull = $(list.prevAll().toArray().reverse()),
nodeEls = nodeElsFull.length ? nodeElsFull : $("<span>" + $.trim(parent.contents()[ 0 ].nodeValue) + "</span>"),
title = nodeEls.first().getEncodedText(),//url limits to first 30 chars of text
id = ( parentUrl || "" ) + "&" + $.mobile.subPageUrlKey + "=" + listId,
theme = list.jqmData("theme") || o.theme,
countTheme = list.jqmData("counttheme") || parentList.jqmData("counttheme") || o.countTheme,
newPage, anchor;
//define hasSubPages for use in later removal
hasSubPages = true;
newPage = list.detach()
.wrap("<div " + dns + "role='page' " + dns + "url='" + id + "' " + dns + "theme='" + theme + "' " + dns + "count-theme='" + countTheme + "'><div " + dns + "role='content'></div></div>")
.parent()
.before("<div " + dns + "role='header' " + dns + "theme='" + o.headerTheme + "'><div class='ui-title'>" + title + "</div></div>")
.after(persistentFooterID ? $("<div " + dns + "role='footer' " + dns + "id='" + persistentFooterID + "'>") : "")
.parent()
.appendTo($.mobile.pageContainer);
newPage.page();
anchor = parent.find('a:first');
if (!anchor.length) {
anchor = $("<a/>").html(nodeEls || title).prependTo(parent.empty());
}
anchor.attr("href", "#" + id);
}).listview();
// on pagehide, remove any nested pages along with the parent page, as long as they aren't active
// and aren't embedded
if (hasSubPages &&
parentPage.is(":jqmData(external-page='true')") &&
parentPage.data("mobile-page").options.domCache === false) {
var newRemove = function (e, ui) {
var nextPage = ui.nextPage, npURL,
prEvent = new $.Event("pageremove");
if (ui.nextPage) {
npURL = nextPage.jqmData("url");
if (npURL.indexOf(parentUrl + "&" + $.mobile.subPageUrlKey) !== 0) {
self.childPages().remove();
parentPage.trigger(prEvent);
if (!prEvent.isDefaultPrevented()) {
parentPage.removeWithDependents();
}
}
}
};
// unbind the original page remove and replace with our specialized version
parentPage
.unbind("pagehide.remove")
.bind("pagehide.remove", newRemove);
}
},
// TODO sort out a better way to track sub pages of the listview this is brittle
childPages: function () {
var parentUrl = this.parentPage.jqmData("url");
return $(":jqmData(url^='" + parentUrl + "&" + $.mobile.subPageUrlKey + "')");
}
}, $.mobile.behaviors.addFirstLastClasses));
//auto self-init widgets
$.mobile.document.bind("pagecreate create", function (e) {
$.mobile.listview.prototype.enhanceWithin(e.target);
});
})(jQuery);
(function ($) {
var meta = $("meta[name=viewport]"),
initialContent = meta.attr("content"),
disabledZoom = initialContent + ",maximum-scale=1, user-scalable=no",
enabledZoom = initialContent + ",maximum-scale=10, user-scalable=yes",
disabledInitially = /(user-scalable[\s]*=[\s]*no)|(maximum-scale[\s]*=[\s]*1)[$,\s]/.test(initialContent);
$.mobile.zoom = $.extend({}, {
enabled: !disabledInitially,
locked: false,
disable: function (lock) {
if (!disabledInitially && !$.mobile.zoom.locked) {
meta.attr("content", disabledZoom);
$.mobile.zoom.enabled = false;
$.mobile.zoom.locked = lock || false;
}
},
enable: function (unlock) {
if (!disabledInitially && ( !$.mobile.zoom.locked || unlock === true )) {
meta.attr("content", enabledZoom);
$.mobile.zoom.enabled = true;
$.mobile.zoom.locked = false;
}
},
restore: function () {
if (!disabledInitially) {
meta.attr("content", initialContent);
$.mobile.zoom.enabled = true;
}
}
});
}(jQuery));
(function ($, undefined) {
$.widget("mobile.textinput", $.mobile.widget, {
options: {
theme: null,
mini: false,
// This option defaults to true on iOS devices.
preventFocusZoom: /iPhone|iPad|iPod/.test(navigator.platform) && navigator.userAgent.indexOf("AppleWebKit") > -1,
initSelector: "input[type='text'], input[type='search'], :jqmData(type='search'), input[type='number'], :jqmData(type='number'), input[type='password'], input[type='email'], input[type='url'], input[type='tel'], textarea, input[type='time'], input[type='date'], input[type='month'], input[type='week'], input[type='datetime'], input[type='datetime-local'], input[type='color'], input:not([type]), input[type='file']",
clearBtn: false,
clearSearchButtonText: null, //deprecating for 1.3...
clearBtnText: "clear text",
disabled: false
},
_create: function () {
var self = this,
input = this.element,
o = this.options,
theme = o.theme || $.mobile.getInheritedTheme(this.element, "c"),
themeclass = " ui-body-" + theme,
miniclass = o.mini ? " ui-mini" : "",
isSearch = input.is("[type='search'], :jqmData(type='search')"),
focusedEl,
clearbtn,
clearBtnText = o.clearSearchButtonText || o.clearBtnText,
clearBtnBlacklist = input.is("textarea, :jqmData(type='range')"),
inputNeedsClearBtn = !!o.clearBtn && !clearBtnBlacklist,
inputNeedsWrap = input.is("input") && !input.is(":jqmData(type='range')");
function toggleClear() {
setTimeout(function () {
clearbtn.toggleClass("ui-input-clear-hidden", !input.val());
}, 0);
}
$("label[for='" + input.attr("id") + "']").addClass("ui-input-text");
focusedEl = input.addClass("ui-input-text ui-body-" + theme);
// XXX: Temporary workaround for issue 785 (Apple bug 8910589).
// Turn off autocorrect and autocomplete on non-iOS 5 devices
// since the popup they use can't be dismissed by the user. Note
// that we test for the presence of the feature by looking for
// the autocorrect property on the input element. We currently
// have no test for iOS 5 or newer so we're temporarily using
// the touchOverflow support flag for jQM 1.0. Yes, I feel dirty. - jblas
if (typeof input[0].autocorrect !== "undefined" && !$.support.touchOverflow) {
// Set the attribute instead of the property just in case there
// is code that attempts to make modifications via HTML.
input[0].setAttribute("autocorrect", "off");
input[0].setAttribute("autocomplete", "off");
}
//"search" and "text" input widgets
if (isSearch) {
focusedEl = input.wrap("<div class='ui-input-search ui-shadow-inset ui-btn-corner-all ui-btn-shadow ui-icon-searchfield" + themeclass + miniclass + "'></div>").parent();
} else if (inputNeedsWrap) {
focusedEl = input.wrap("<div class='ui-input-text ui-shadow-inset ui-corner-all ui-btn-shadow" + themeclass + miniclass + "'></div>").parent();
}
if (inputNeedsClearBtn || isSearch) {
clearbtn = $("<a href='#' class='ui-input-clear' title='" + clearBtnText + "'>" + clearBtnText + "</a>")
.bind("click", function (event) {
input
.val("")
.focus()
.trigger("change");
clearbtn.addClass("ui-input-clear-hidden");
event.preventDefault();
})
.appendTo(focusedEl)
.buttonMarkup({
icon: "delete",
iconpos: "notext",
corners: true,
shadow: true,
mini: o.mini
});
if (!isSearch) {
focusedEl.addClass("ui-input-has-clear");
}
toggleClear();
input.bind("paste cut keyup input focus change blur", toggleClear);
}
else if (!inputNeedsWrap && !isSearch) {
input.addClass("ui-corner-all ui-shadow-inset" + themeclass + miniclass);
}
input.focus(function () {
// In many situations, iOS will zoom into the input upon tap, this prevents that from happening
if (o.preventFocusZoom) {
$.mobile.zoom.disable(true);
}
focusedEl.addClass($.mobile.focusClass);
})
.blur(function () {
focusedEl.removeClass($.mobile.focusClass);
if (o.preventFocusZoom) {
$.mobile.zoom.enable(true);
}
});
// Autogrow
if (input.is("textarea")) {
var extraLineHeight = 15,
keyupTimeoutBuffer = 100,
keyupTimeout;
this._keyup = function () {
var scrollHeight = input[ 0 ].scrollHeight,
clientHeight = input[ 0 ].clientHeight;
if (clientHeight < scrollHeight) {
var paddingTop = parseFloat(input.css("padding-top")),
paddingBottom = parseFloat(input.css("padding-bottom")),
paddingHeight = paddingTop + paddingBottom;
input.height(scrollHeight - paddingHeight + extraLineHeight);
}
};
input.on("keyup change input paste", function () {
clearTimeout(keyupTimeout);
keyupTimeout = setTimeout(self._keyup, keyupTimeoutBuffer);
});
// binding to pagechange here ensures that for pages loaded via
// ajax the height is recalculated without user input
this._on(true, $.mobile.document, { "pagechange": "_keyup" });
// Issue 509: the browser is not providing scrollHeight properly until the styles load
if ($.trim(input.val())) {
// bind to the window load to make sure the height is calculated based on BOTH
// the DOM and CSS
this._on(true, $.mobile.window, {"load": "_keyup"});
}
}
if (input.attr("disabled")) {
this.disable();
}
},
disable: function () {
var $el,
isSearch = this.element.is("[type='search'], :jqmData(type='search')"),
inputNeedsWrap = this.element.is("input") && !this.element.is(":jqmData(type='range')"),
parentNeedsDisabled = this.element.attr("disabled", true) && ( inputNeedsWrap || isSearch );
if (parentNeedsDisabled) {
$el = this.element.parent();
} else {
$el = this.element;
}
$el.addClass("ui-disabled");
return this._setOption("disabled", true);
},
enable: function () {
var $el,
isSearch = this.element.is("[type='search'], :jqmData(type='search')"),
inputNeedsWrap = this.element.is("input") && !this.element.is(":jqmData(type='range')"),
parentNeedsEnabled = this.element.attr("disabled", false) && ( inputNeedsWrap || isSearch );
if (parentNeedsEnabled) {
$el = this.element.parent();
} else {
$el = this.element;
}
$el.removeClass("ui-disabled");
return this._setOption("disabled", false);
}
});
//auto self-init widgets
$.mobile.document.bind("pagecreate create", function (e) {
$.mobile.textinput.prototype.enhanceWithin(e.target, true);
});
})(jQuery);
(function ($, undefined) {
$.mobile.listview.prototype.options.filter = false;
$.mobile.listview.prototype.options.filterPlaceholder = "Filter items...";
$.mobile.listview.prototype.options.filterTheme = "c";
$.mobile.listview.prototype.options.filterReveal = false;
// TODO rename callback/deprecate and default to the item itself as the first argument
var defaultFilterCallback = function (text, searchValue, item) {
return text.toString().toLowerCase().indexOf(searchValue) === -1;
};
$.mobile.listview.prototype.options.filterCallback = defaultFilterCallback;
$.mobile.document.delegate("ul, ol", "listviewcreate", function () {
var list = $(this),
listview = list.data("mobile-listview");
if (!listview || !listview.options.filter) {
return;
}
if (listview.options.filterReveal) {
list.children().addClass("ui-screen-hidden");
}
var wrapper = $("<form>", {
"class": "ui-listview-filter ui-bar-" + listview.options.filterTheme,
"role": "search"
}).submit(function (e) {
e.preventDefault();
search.blur();
}),
onKeyUp = function (e) {
var $this = $(this),
val = this.value.toLowerCase(),
listItems = null,
li = list.children(),
lastval = $this.jqmData("lastval") + "",
childItems = false,
itemtext = "",
item,
// Check if a custom filter callback applies
isCustomFilterCallback = listview.options.filterCallback !== defaultFilterCallback;
if (lastval && lastval === val) {
// Execute the handler only once per value change
return;
}
listview._trigger("beforefilter", "beforefilter", { input: this });
// Change val as lastval for next execution
$this.jqmData("lastval", val);
if (isCustomFilterCallback || val.length < lastval.length || val.indexOf(lastval) !== 0) {
// Custom filter callback applies or removed chars or pasted something totally different, check all items
listItems = list.children();
} else {
// Only chars added, not removed, only use visible subset
listItems = list.children(":not(.ui-screen-hidden)");
if (!listItems.length && listview.options.filterReveal) {
listItems = list.children(".ui-screen-hidden");
}
}
if (val) {
// This handles hiding regular rows without the text we search for
// and any list dividers without regular rows shown under it
for (var i = listItems.length - 1; i >= 0; i--) {
item = $(listItems[ i ]);
itemtext = item.jqmData("filtertext") || item.text();
if (item.is("li:jqmData(role=list-divider)")) {
item.toggleClass("ui-filter-hidequeue", !childItems);
// New bucket!
childItems = false;
} else if (listview.options.filterCallback(itemtext, val, item)) {
//mark to be hidden
item.toggleClass("ui-filter-hidequeue", true);
} else {
// There's a shown item in the bucket
childItems = true;
}
}
// Show items, not marked to be hidden
listItems
.filter(":not(.ui-filter-hidequeue)")
.toggleClass("ui-screen-hidden", false);
// Hide items, marked to be hidden
listItems
.filter(".ui-filter-hidequeue")
.toggleClass("ui-screen-hidden", true)
.toggleClass("ui-filter-hidequeue", false);
} else {
//filtervalue is empty => show all
listItems.toggleClass("ui-screen-hidden", !!listview.options.filterReveal);
}
listview._addFirstLastClasses(li, listview._getVisibles(li, false), false);
},
search = $("<input>", {
placeholder: listview.options.filterPlaceholder
})
.attr("data-" + $.mobile.ns + "type", "search")
.jqmData("lastval", "")
.bind("keyup change input", onKeyUp)
.appendTo(wrapper)
.textinput();
if (listview.options.inset) {
wrapper.addClass("ui-listview-filter-inset");
}
wrapper.bind("submit", function () {
return false;
})
.insertBefore(list);
});
})(jQuery);
(function ($, undefined) {
$.mobile.listview.prototype.options.autodividers = false;
$.mobile.listview.prototype.options.autodividersSelector = function (elt) {
// look for the text in the given element
var text = $.trim(elt.text()) || null;
if (!text) {
return null;
}
// create the text for the divider (first uppercased letter)
text = text.slice(0, 1).toUpperCase();
return text;
};
$.mobile.document.delegate("ul,ol", "listviewcreate", function () {
var list = $(this),
listview = list.data("mobile-listview");
if (!listview || !listview.options.autodividers) {
return;
}
var replaceDividers = function () {
list.find("li:jqmData(role='list-divider')").remove();
var lis = list.find('li'),
lastDividerText = null, li, dividerText;
for (var i = 0; i < lis.length; i++) {
li = lis[i];
dividerText = listview.options.autodividersSelector($(li));
if (dividerText && lastDividerText !== dividerText) {
var divider = document.createElement('li');
divider.appendChild(document.createTextNode(dividerText));
divider.setAttribute('data-' + $.mobile.ns + 'role', 'list-divider');
li.parentNode.insertBefore(divider, li);
}
lastDividerText = dividerText;
}
};
var afterListviewRefresh = function () {
list.unbind('listviewafterrefresh', afterListviewRefresh);
replaceDividers();
listview.refresh();
list.bind('listviewafterrefresh', afterListviewRefresh);
};
afterListviewRefresh();
});
})(jQuery);
(function ($, undefined) {
$(document).bind("pagecreate create", function (e) {
$(":jqmData(role='nojs')", e.target).addClass("ui-nojs");
});
})(jQuery);
(function ($, undefined) {
$.mobile.behaviors.formReset = {
_handleFormReset: function () {
this._on(this.element.closest("form"), {
reset: function () {
this._delay("_reset");
}
});
}
};
})(jQuery);
/*
* "checkboxradio" plugin
*/
(function ($, undefined) {
$.widget("mobile.checkboxradio", $.mobile.widget, $.extend({
options: {
theme: null,
mini: false,
initSelector: "input[type='checkbox'],input[type='radio']"
},
_create: function () {
var self = this,
input = this.element,
o = this.options,
inheritAttr = function (input, dataAttr) {
return input.jqmData(dataAttr) || input.closest("form, fieldset").jqmData(dataAttr);
},
// NOTE: Windows Phone could not find the label through a selector
// filter works though.
parentLabel = $(input).closest("label"),
label = parentLabel.length ? parentLabel : $(input).closest("form, fieldset, :jqmData(role='page'), :jqmData(role='dialog')").find("label").filter("[for='" + input[0].id + "']").first(),
inputtype = input[0].type,
mini = inheritAttr(input, "mini") || o.mini,
checkedState = inputtype + "-on",
uncheckedState = inputtype + "-off",
iconpos = inheritAttr(input, "iconpos"),
checkedClass = "ui-" + checkedState,
uncheckedClass = "ui-" + uncheckedState;
if (inputtype !== "checkbox" && inputtype !== "radio") {
return;
}
// Expose for other methods
$.extend(this, {
label: label,
inputtype: inputtype,
checkedClass: checkedClass,
uncheckedClass: uncheckedClass,
checkedicon: checkedState,
uncheckedicon: uncheckedState
});
// If there's no selected theme check the data attr
if (!o.theme) {
o.theme = $.mobile.getInheritedTheme(this.element, "c");
}
label.buttonMarkup({
theme: o.theme,
icon: uncheckedState,
shadow: false,
mini: mini,
iconpos: iconpos
});
// Wrap the input + label in a div
var wrapper = document.createElement('div');
wrapper.className = 'ui-' + inputtype;
input.add(label).wrapAll(wrapper);
label.bind({
vmouseover: function (event) {
if ($(this).parent().is(".ui-disabled")) {
event.stopPropagation();
}
},
vclick: function (event) {
if (input.is(":disabled")) {
event.preventDefault();
return;
}
self._cacheVals();
input.prop("checked", inputtype === "radio" && true || !input.prop("checked"));
// trigger click handler's bound directly to the input as a substitute for
// how label clicks behave normally in the browsers
// TODO: it would be nice to let the browser's handle the clicks and pass them
// through to the associate input. we can swallow that click at the parent
// wrapper element level
input.triggerHandler('click');
// Input set for common radio buttons will contain all the radio
// buttons, but will not for checkboxes. clearing the checked status
// of other radios ensures the active button state is applied properly
self._getInputSet().not(input).prop("checked", false);
self._updateAll();
return false;
}
});
input
.bind({
vmousedown: function () {
self._cacheVals();
},
vclick: function () {
var $this = $(this);
// Adds checked attribute to checked input when keyboard is used
if ($this.is(":checked")) {
$this.prop("checked", true);
self._getInputSet().not($this).prop("checked", false);
} else {
$this.prop("checked", false);
}
self._updateAll();
},
focus: function () {
label.addClass($.mobile.focusClass);
},
blur: function () {
label.removeClass($.mobile.focusClass);
}
});
this._handleFormReset();
this.refresh();
},
_cacheVals: function () {
this._getInputSet().each(function () {
$(this).jqmData("cacheVal", this.checked);
});
},
//returns either a set of radios with the same name attribute, or a single checkbox
_getInputSet: function () {
if (this.inputtype === "checkbox") {
return this.element;
}
return this.element.closest("form, :jqmData(role='page'), :jqmData(role='dialog')")
.find("input[name='" + this.element[0].name + "'][type='" + this.inputtype + "']");
},
_updateAll: function () {
var self = this;
this._getInputSet().each(function () {
var $this = $(this);
if (this.checked || self.inputtype === "checkbox") {
$this.trigger("change");
}
})
.checkboxradio("refresh");
},
_reset: function () {
this.refresh();
},
refresh: function () {
var input = this.element[ 0 ],
active = " " + $.mobile.activeBtnClass,
checkedClass = this.checkedClass + ( this.element.parents(".ui-controlgroup-horizontal").length ? active : "" ),
label = this.label;
if (input.checked) {
label.removeClass(this.uncheckedClass + active).addClass(checkedClass).buttonMarkup({ icon: this.checkedicon });
} else {
label.removeClass(checkedClass).addClass(this.uncheckedClass).buttonMarkup({ icon: this.uncheckedicon });
}
if (input.disabled) {
this.disable();
} else {
this.enable();
}
},
disable: function () {
this.element.prop("disabled", true).parent().addClass("ui-disabled");
},
enable: function () {
this.element.prop("disabled", false).parent().removeClass("ui-disabled");
}
}, $.mobile.behaviors.formReset));
//auto self-init widgets
$.mobile.document.bind("pagecreate create", function (e) {
$.mobile.checkboxradio.prototype.enhanceWithin(e.target, true);
});
})(jQuery);
(function ($, undefined) {
$.widget("mobile.button", $.mobile.widget, {
options: {
theme: null,
icon: null,
iconpos: null,
corners: true,
shadow: true,
iconshadow: true,
inline: null,
mini: null,
initSelector: "button, [type='button'], [type='submit'], [type='reset']"
},
_create: function () {
var $el = this.element,
$button,
// create a copy of this.options we can pass to buttonMarkup
o = (function (tdo) {
var key, ret = {};
for (key in tdo) {
if (tdo[ key ] !== null && key !== "initSelector") {
ret[ key ] = tdo[ key ];
}
}
return ret;
})(this.options),
classes = "",
$buttonPlaceholder;
// if this is a link, check if it's been enhanced and, if not, use the right function
if ($el[ 0 ].tagName === "A") {
if (!$el.hasClass("ui-btn")) {
$el.buttonMarkup();
}
return;
}
// get the inherited theme
// TODO centralize for all widgets
if (!this.options.theme) {
this.options.theme = $.mobile.getInheritedTheme(this.element, "c");
}
// TODO: Post 1.1--once we have time to test thoroughly--any classes manually applied to the original element should be carried over to the enhanced element, with an `-enhanced` suffix. See https://github.com/jquery/jquery-mobile/issues/3577
/* if ( $el[0].className.length ) {
classes = $el[0].className;
} */
if (!!~$el[0].className.indexOf("ui-btn-left")) {
classes = "ui-btn-left";
}
if (!!~$el[0].className.indexOf("ui-btn-right")) {
classes = "ui-btn-right";
}
if ($el.attr("type") === "submit" || $el.attr("type") === "reset") {
if (classes) {
classes += " ui-submit";
} else {
classes = "ui-submit";
}
}
$("label[for='" + $el.attr("id") + "']").addClass("ui-submit");
// Add ARIA role
this.button = $("<div></div>")
[ $el.html() ? "html" : "text" ]($el.html() || $el.val())
.insertBefore($el)
.buttonMarkup(o)
.addClass(classes)
.append($el.addClass("ui-btn-hidden"));
$button = this.button;
$el.bind({
focus: function () {
$button.addClass($.mobile.focusClass);
},
blur: function () {
$button.removeClass($.mobile.focusClass);
}
});
this.refresh();
},
_setOption: function (key, value) {
var op = {};
op[ key ] = value;
if (key !== "initSelector") {
this.button.buttonMarkup(op);
// Record the option change in the options and in the DOM data-* attributes
this.element.attr("data-" + ( $.mobile.ns || "" ) + ( key.replace(/([A-Z])/, "-$1").toLowerCase() ), value);
}
this._super("_setOption", key, value);
},
enable: function () {
this.element.attr("disabled", false);
this.button.removeClass("ui-disabled").attr("aria-disabled", false);
return this._setOption("disabled", false);
},
disable: function () {
this.element.attr("disabled", true);
this.button.addClass("ui-disabled").attr("aria-disabled", true);
return this._setOption("disabled", true);
},
refresh: function () {
var $el = this.element;
if ($el.prop("disabled")) {
this.disable();
} else {
this.enable();
}
// Grab the button's text element from its implementation-independent data item
$(this.button.data('buttonElements').text)[ $el.html() ? "html" : "text" ]($el.html() || $el.val());
}
});
//auto self-init widgets
$.mobile.document.bind("pagecreate create", function (e) {
$.mobile.button.prototype.enhanceWithin(e.target, true);
});
})(jQuery);
(function ($, undefined) {
$.widget("mobile.slider", $.mobile.widget, $.extend({
widgetEventPrefix: "slide",
options: {
theme: null,
trackTheme: null,
disabled: false,
initSelector: "input[type='range'], :jqmData(type='range'), :jqmData(role='slider')",
mini: false,
highlight: false
},
_create: function () {
// TODO: Each of these should have comments explain what they're for
var self = this,
control = this.element,
parentTheme = $.mobile.getInheritedTheme(control, "c"),
theme = this.options.theme || parentTheme,
trackTheme = this.options.trackTheme || parentTheme,
cType = control[ 0 ].nodeName.toLowerCase(),
isSelect = this.isToggleSwitch = cType === "select",
isRangeslider = control.parent().is(":jqmData(role='rangeslider')"),
selectClass = ( this.isToggleSwitch ) ? "ui-slider-switch" : "",
controlID = control.attr("id"),
$label = $("[for='" + controlID + "']"),
labelID = $label.attr("id") || controlID + "-label",
label = $label.attr("id", labelID),
min = !this.isToggleSwitch ? parseFloat(control.attr("min")) : 0,
max = !this.isToggleSwitch ? parseFloat(control.attr("max")) : control.find("option").length - 1,
step = window.parseFloat(control.attr("step") || 1),
miniClass = ( this.options.mini || control.jqmData("mini") ) ? " ui-mini" : "",
domHandle = document.createElement("a"),
handle = $(domHandle),
domSlider = document.createElement("div"),
slider = $(domSlider),
valuebg = this.options.highlight && !this.isToggleSwitch ? (function () {
var bg = document.createElement("div");
bg.className = "ui-slider-bg " + $.mobile.activeBtnClass + " ui-btn-corner-all";
return $(bg).prependTo(slider);
})() : false,
options,
wrapper;
domHandle.setAttribute("href", "#");
domSlider.setAttribute("role", "application");
domSlider.className = [this.isToggleSwitch ? "ui-slider " : "ui-slider-track ", selectClass, " ui-btn-down-", trackTheme, " ui-btn-corner-all", miniClass].join("");
domHandle.className = "ui-slider-handle";
domSlider.appendChild(domHandle);
handle.buttonMarkup({ corners: true, theme: theme, shadow: true })
.attr({
"role": "slider",
"aria-valuemin": min,
"aria-valuemax": max,
"aria-valuenow": this._value(),
"aria-valuetext": this._value(),
"title": this._value(),
"aria-labelledby": labelID
});
$.extend(this, {
slider: slider,
handle: handle,
type: cType,
step: step,
max: max,
min: min,
valuebg: valuebg,
isRangeslider: isRangeslider,
dragging: false,
beforeStart: null,
userModified: false,
mouseMoved: false
});
if (this.isToggleSwitch) {
wrapper = document.createElement("div");
wrapper.className = "ui-slider-inneroffset";
for (var j = 0, length = domSlider.childNodes.length; j < length; j++) {
wrapper.appendChild(domSlider.childNodes[j]);
}
domSlider.appendChild(wrapper);
// slider.wrapInner( "<div class='ui-slider-inneroffset'></div>" );
// make the handle move with a smooth transition
handle.addClass("ui-slider-handle-snapping");
options = control.find("option");
for (var i = 0, optionsCount = options.length; i < optionsCount; i++) {
var side = !i ? "b" : "a",
sliderTheme = !i ? " ui-btn-down-" + trackTheme : ( " " + $.mobile.activeBtnClass ),
sliderLabel = document.createElement("div"),
sliderImg = document.createElement("span");
sliderImg.className = ["ui-slider-label ui-slider-label-", side, sliderTheme, " ui-btn-corner-all"].join("");
sliderImg.setAttribute("role", "img");
sliderImg.appendChild(document.createTextNode(options[i].innerHTML));
$(sliderImg).prependTo(slider);
}
self._labels = $(".ui-slider-label", slider);
}
label.addClass("ui-slider");
// monitor the input for updated values
control.addClass(this.isToggleSwitch ? "ui-slider-switch" : "ui-slider-input");
this._on(control, {
"change": "_controlChange",
"keyup": "_controlKeyup",
"blur": "_controlBlur",
"vmouseup": "_controlVMouseUp"
});
slider.bind("vmousedown", $.proxy(this._sliderVMouseDown, this))
.bind("vclick", false);
// We have to instantiate a new function object for the unbind to work properly
// since the method itself is defined in the prototype (causing it to unbind everything)
this._on(document, { "vmousemove": "_preventDocumentDrag" });
this._on(slider.add(document), { "vmouseup": "_sliderVMouseUp" });
slider.insertAfter(control);
// wrap in a div for styling purposes
if (!this.isToggleSwitch && !isRangeslider) {
wrapper = this.options.mini ? "<div class='ui-slider ui-mini'>" : "<div class='ui-slider'>";
control.add(slider).wrapAll(wrapper);
}
// Only add focus class to toggle switch, sliders get it automatically from ui-btn
if (this.isToggleSwitch) {
this.handle.bind({
focus: function () {
slider.addClass($.mobile.focusClass);
},
blur: function () {
slider.removeClass($.mobile.focusClass);
}
});
}
// bind the handle event callbacks and set the context to the widget instance
this._on(this.handle, {
"vmousedown": "_handleVMouseDown",
"keydown": "_handleKeydown",
"keyup": "_handleKeyup"
});
this.handle.bind("vclick", false);
this._handleFormReset();
this.refresh(undefined, undefined, true);
},
_controlChange: function (event) {
// if the user dragged the handle, the "change" event was triggered from inside refresh(); don't call refresh() again
if (this._trigger("controlchange", event) === false) {
return false;
}
if (!this.mouseMoved) {
this.refresh(this._value(), true);
}
},
_controlKeyup: function (event) { // necessary?
this.refresh(this._value(), true, true);
},
_controlBlur: function (event) {
this.refresh(this._value(), true);
},
// it appears the clicking the up and down buttons in chrome on
// range/number inputs doesn't trigger a change until the field is
// blurred. Here we check thif the value has changed and refresh
_controlVMouseUp: function (event) {
this._checkedRefresh();
},
// NOTE force focus on handle
_handleVMouseDown: function (event) {
this.handle.focus();
},
_handleKeydown: function (event) {
var index = this._value();
if (this.options.disabled) {
return;
}
// In all cases prevent the default and mark the handle as active
switch (event.keyCode) {
case $.mobile.keyCode.HOME:
case $.mobile.keyCode.END:
case $.mobile.keyCode.PAGE_UP:
case $.mobile.keyCode.PAGE_DOWN:
case $.mobile.keyCode.UP:
case $.mobile.keyCode.RIGHT:
case $.mobile.keyCode.DOWN:
case $.mobile.keyCode.LEFT:
event.preventDefault();
if (!this._keySliding) {
this._keySliding = true;
this.handle.addClass("ui-state-active");
}
break;
}
// move the slider according to the keypress
switch (event.keyCode) {
case $.mobile.keyCode.HOME:
this.refresh(this.min);
break;
case $.mobile.keyCode.END:
this.refresh(this.max);
break;
case $.mobile.keyCode.PAGE_UP:
case $.mobile.keyCode.UP:
case $.mobile.keyCode.RIGHT:
this.refresh(index + this.step);
break;
case $.mobile.keyCode.PAGE_DOWN:
case $.mobile.keyCode.DOWN:
case $.mobile.keyCode.LEFT:
this.refresh(index - this.step);
break;
}
}, // remove active mark
_handleKeyup: function (event) {
if (this._keySliding) {
this._keySliding = false;
this.handle.removeClass("ui-state-active");
}
},
_sliderVMouseDown: function (event) {
// NOTE: we don't do this in refresh because we still want to
// support programmatic alteration of disabled inputs
if (this.options.disabled || !( event.which === 1 || event.which === 0 || event.which === undefined )) {
return false;
}
if (this._trigger("beforestart", event) === false) {
return false;
}
this.dragging = true;
this.userModified = false;
this.mouseMoved = false;
if (this.isToggleSwitch) {
this.beforeStart = this.element[0].selectedIndex;
}
this.refresh(event);
this._trigger("start");
return false;
},
_sliderVMouseUp: function () {
if (this.dragging) {
this.dragging = false;
if (this.isToggleSwitch) {
// make the handle move with a smooth transition
this.handle.addClass("ui-slider-handle-snapping");
if (this.mouseMoved) {
// this is a drag, change the value only if user dragged enough
if (this.userModified) {
this.refresh(this.beforeStart === 0 ? 1 : 0);
} else {
this.refresh(this.beforeStart);
}
} else {
// this is just a click, change the value
this.refresh(this.beforeStart === 0 ? 1 : 0);
}
}
this.mouseMoved = false;
this._trigger("stop");
return false;
}
},
_preventDocumentDrag: function (event) {
// NOTE: we don't do this in refresh because we still want to
// support programmatic alteration of disabled inputs
if (this._trigger("drag", event) === false) {
return false;
}
if (this.dragging && !this.options.disabled) {
// this.mouseMoved must be updated before refresh() because it will be used in the control "change" event
this.mouseMoved = true;
if (this.isToggleSwitch) {
// make the handle move in sync with the mouse
this.handle.removeClass("ui-slider-handle-snapping");
}
this.refresh(event);
// only after refresh() you can calculate this.userModified
this.userModified = this.beforeStart !== this.element[0].selectedIndex;
return false;
}
},
_checkedRefresh: function () {
if (this.value !== this._value()) {
this.refresh(this._value());
}
},
_value: function () {
return this.isToggleSwitch ? this.element[0].selectedIndex : parseFloat(this.element.val());
},
_reset: function () {
this.refresh(undefined, false, true);
},
refresh: function (val, isfromControl, preventInputUpdate) {
// NOTE: we don't return here because we want to support programmatic
// alteration of the input value, which should still update the slider
var self = this,
parentTheme = $.mobile.getInheritedTheme(this.element, "c"),
theme = this.options.theme || parentTheme,
trackTheme = this.options.trackTheme || parentTheme,
left, width, data, tol;
self.slider[0].className = [ this.isToggleSwitch ? "ui-slider ui-slider-switch" : "ui-slider-track", " ui-btn-down-" + trackTheme, ' ui-btn-corner-all', ( this.options.mini ) ? " ui-mini" : ""].join("");
if (this.options.disabled || this.element.attr("disabled")) {
this.disable();
}
// set the stored value for comparison later
this.value = this._value();
if (this.options.highlight && !this.isToggleSwitch && this.slider.find(".ui-slider-bg").length === 0) {
this.valuebg = (function () {
var bg = document.createElement("div");
bg.className = "ui-slider-bg " + $.mobile.activeBtnClass + " ui-btn-corner-all";
return $(bg).prependTo(self.slider);
})();
}
this.handle.buttonMarkup({ corners: true, theme: theme, shadow: true });
var pxStep, percent,
control = this.element,
isInput = !this.isToggleSwitch,
optionElements = isInput ? [] : control.find("option"),
min = isInput ? parseFloat(control.attr("min")) : 0,
max = isInput ? parseFloat(control.attr("max")) : optionElements.length - 1,
step = ( isInput && parseFloat(control.attr("step")) > 0 ) ? parseFloat(control.attr("step")) : 1;
if (typeof val === "object") {
data = val;
// a slight tolerance helped get to the ends of the slider
tol = 8;
left = this.slider.offset().left;
width = this.slider.width();
pxStep = width / ((max - min) / step);
if (!this.dragging ||
data.pageX < left - tol ||
data.pageX > left + width + tol) {
return;
}
if (pxStep > 1) {
percent = ( ( data.pageX - left ) / width ) * 100;
} else {
percent = Math.round(( ( data.pageX - left ) / width ) * 100);
}
} else {
if (val == null) {
val = isInput ? parseFloat(control.val() || 0) : control[0].selectedIndex;
}
percent = ( parseFloat(val) - min ) / ( max - min ) * 100;
}
if (isNaN(percent)) {
return;
}
var newval = ( percent / 100 ) * ( max - min ) + min;
//from jQuery UI slider, the following source will round to the nearest step
var valModStep = ( newval - min ) % step;
var alignValue = newval - valModStep;
if (Math.abs(valModStep) * 2 >= step) {
alignValue += ( valModStep > 0 ) ? step : ( -step );
}
var percentPerStep = 100 / ((max - min) / step);
// Since JavaScript has problems with large floats, round
// the final value to 5 digits after the decimal point (see jQueryUI: #4124)
newval = parseFloat(alignValue.toFixed(5));
if (typeof pxStep === "undefined") {
pxStep = width / ( (max - min) / step );
}
if (pxStep > 1 && isInput) {
percent = ( newval - min ) * percentPerStep * ( 1 / step );
}
if (percent < 0) {
percent = 0;
}
if (percent > 100) {
percent = 100;
}
if (newval < min) {
newval = min;
}
if (newval > max) {
newval = max;
}
this.handle.css("left", percent + "%");
this.handle[0].setAttribute("aria-valuenow", isInput ? newval : optionElements.eq(newval).attr("value"));
this.handle[0].setAttribute("aria-valuetext", isInput ? newval : optionElements.eq(newval).getEncodedText());
this.handle[0].setAttribute("title", isInput ? newval : optionElements.eq(newval).getEncodedText());
if (this.valuebg) {
this.valuebg.css("width", percent + "%");
}
// drag the label widths
if (this._labels) {
var handlePercent = this.handle.width() / this.slider.width() * 100,
aPercent = percent && handlePercent + ( 100 - handlePercent ) * percent / 100,
bPercent = percent === 100 ? 0 : Math.min(handlePercent + 100 - aPercent, 100);
this._labels.each(function () {
var ab = $(this).is(".ui-slider-label-a");
$(this).width(( ab ? aPercent : bPercent ) + "%");
});
}
if (!preventInputUpdate) {
var valueChanged = false;
// update control"s value
if (isInput) {
valueChanged = control.val() !== newval;
control.val(newval);
} else {
valueChanged = control[ 0 ].selectedIndex !== newval;
control[ 0 ].selectedIndex = newval;
}
if (this._trigger("beforechange", val) === false) {
return false;
}
if (!isfromControl && valueChanged) {
control.trigger("change");
}
}
},
enable: function () {
this.element.attr("disabled", false);
this.slider.removeClass("ui-disabled").attr("aria-disabled", false);
return this._setOption("disabled", false);
},
disable: function () {
this.element.attr("disabled", true);
this.slider.addClass("ui-disabled").attr("aria-disabled", true);
return this._setOption("disabled", true);
}
}, $.mobile.behaviors.formReset));
//auto self-init widgets
$.mobile.document.bind("pagecreate create", function (e) {
$.mobile.slider.prototype.enhanceWithin(e.target, true);
});
})(jQuery);
(function ($, undefined) {
$.widget("mobile.rangeslider", $.mobile.widget, {
options: {
theme: null,
trackTheme: null,
disabled: false,
initSelector: ":jqmData(role='rangeslider')",
mini: false,
highlight: true
},
_create: function () {
var secondLabel,
$el = this.element,
elClass = this.options.mini ? "ui-rangeslider ui-mini" : "ui-rangeslider",
_inputFirst = $el.find("input").first(),
_inputLast = $el.find("input").last(),
label = $el.find("label").first(),
_sliderFirst = $.data(_inputFirst.get(0), "mobileSlider").slider,
_sliderLast = $.data(_inputLast.get(0), "mobileSlider").slider,
firstHandle = $.data(_inputFirst.get(0), "mobileSlider").handle,
_sliders = $("<div class=\"ui-rangeslider-sliders\" />").appendTo($el);
if ($el.find("label").length > 1) {
secondLabel = $el.find("label").last().hide();
}
_inputFirst.addClass("ui-rangeslider-first");
_inputLast.addClass("ui-rangeslider-last");
$el.addClass(elClass);
_sliderFirst.appendTo(_sliders);
_sliderLast.appendTo(_sliders);
label.prependTo($el);
firstHandle.prependTo(_sliderLast);
$.extend(this, {
_inputFirst: _inputFirst,
_inputLast: _inputLast,
_sliderFirst: _sliderFirst,
_sliderLast: _sliderLast,
_targetVal: null,
_sliderTarget: false,
_sliders: _sliders,
_proxy: false
});
this.refresh();
this._on(this.element.find("input.ui-slider-input"), {
"slidebeforestart": "_slidebeforestart",
"slidestop": "_slidestop",
"slidedrag": "_slidedrag",
"slidebeforechange": "_change",
"blur": "_change",
"keyup": "_change"
});
this._on({
"mousedown": "_change"
});
this._on(this.element.closest("form"), {
"reset": "_handleReset"
});
this._on(firstHandle, {
"vmousedown": "_dragFirstHandle"
});
},
_handleReset: function () {
var self = this;
//we must wait for the stack to unwind before updateing other wise sliders will not have updated yet
setTimeout(function () {
self._updateHighlight();
}, 0);
},
_dragFirstHandle: function (event) {
//if the first handle is dragged send the event to the first slider
$.data(this._inputFirst.get(0), "mobileSlider").dragging = true;
$.data(this._inputFirst.get(0), "mobileSlider").refresh(event);
return false;
},
_slidedrag: function (event) {
var first = $(event.target).is(this._inputFirst),
otherSlider = ( first ) ? this._inputLast : this._inputFirst;
this._sliderTarget = false;
//if the drag was initiated on an extreme and the other handle is focused send the events to
//the closest handle
if (( this._proxy === "first" && first ) || ( this._proxy === "last" && !first )) {
$.data(otherSlider.get(0), "mobileSlider").dragging = true;
$.data(otherSlider.get(0), "mobileSlider").refresh(event);
return false;
}
},
_slidestop: function (event) {
var first = $(event.target).is(this._inputFirst);
this._proxy = false;
//this stops dragging of the handle and brings the active track to the front
//this makes clicks on the track go the the last handle used
this.element.find("input").trigger("vmouseup");
this._sliderFirst.css("z-index", first ? 1 : "");
},
_slidebeforestart: function (event) {
this._sliderTarget = false;
//if the track is the target remember this and the original value
if ($(event.originalEvent.target).hasClass("ui-slider-track")) {
this._sliderTarget = true;
this._targetVal = $(event.target).val();
}
},
_setOption: function (options) {
this._superApply(options);
this.refresh();
},
refresh: function () {
var $el = this.element,
o = this.options;
$el.find("input").slider({
theme: o.theme,
trackTheme: o.trackTheme,
disabled: o.disabled,
mini: o.mini,
highlight: o.highlight
}).slider("refresh");
this._updateHighlight();
},
_change: function (event) {
if (event.type === "keyup") {
this._updateHighlight();
return false;
}
var self = this,
min = parseFloat(this._inputFirst.val(), 10),
max = parseFloat(this._inputLast.val(), 10),
first = $(event.target).hasClass("ui-rangeslider-first"),
thisSlider = first ? this._inputFirst : this._inputLast,
otherSlider = first ? this._inputLast : this._inputFirst;
if (( this._inputFirst.val() > this._inputLast.val() && event.type === "mousedown" && !$(event.target).hasClass("ui-slider-handle"))) {
thisSlider.blur();
} else if (event.type === "mousedown") {
return;
}
if (min > max && !this._sliderTarget) {
//this prevents min from being greater then max
thisSlider.val(first ? max : min).slider("refresh");
this._trigger("normalize");
} else if (min > max) {
//this makes it so clicks on the target on either extreme go to the closest handle
thisSlider.val(this._targetVal).slider("refresh");
//You must wait for the stack to unwind so first slider is updated before updating second
setTimeout(function () {
otherSlider.val(first ? min : max).slider("refresh");
$.data(otherSlider.get(0), "mobileSlider").handle.focus();
self._sliderFirst.css("z-index", first ? "" : 1);
self._trigger("normalize");
}, 0);
this._proxy = ( first ) ? "first" : "last";
}
//fixes issue where when both _sliders are at min they cannot be adjusted
if (min === max) {
$.data(thisSlider.get(0), "mobileSlider").handle.css("z-index", 1);
$.data(otherSlider.get(0), "mobileSlider").handle.css("z-index", 0);
} else {
$.data(otherSlider.get(0), "mobileSlider").handle.css("z-index", "");
$.data(thisSlider.get(0), "mobileSlider").handle.css("z-index", "");
}
this._updateHighlight();
if (min >= max) {
return false;
}
},
_updateHighlight: function () {
var min = parseInt($.data(this._inputFirst.get(0), "mobileSlider").handle.get(0).style.left, 10),
max = parseInt($.data(this._inputLast.get(0), "mobileSlider").handle.get(0).style.left, 10),
width = (max - min);
this.element.find(".ui-slider-bg").css({
"margin-left": min + "%",
"width": width + "%"
});
},
_destroy: function () {
this.element.removeClass("ui-rangeslider ui-mini").find("label").show();
this._inputFirst.after(this._sliderFirst);
this._inputLast.after(this._sliderLast);
this._sliders.remove();
this.element.find("input").removeClass("ui-rangeslider-first ui-rangeslider-last").slider("destroy");
}
});
$.widget("mobile.rangeslider", $.mobile.rangeslider, $.mobile.behaviors.formReset);
//auto self-init widgets
$(document).bind("pagecreate create", function (e) {
$.mobile.rangeslider.prototype.enhanceWithin(e.target, true);
});
})(jQuery);
(function ($, undefined) {
$.widget("mobile.selectmenu", $.mobile.widget, $.extend({
options: {
theme: null,
disabled: false,
icon: "arrow-d",
iconpos: "right",
inline: false,
corners: true,
shadow: true,
iconshadow: true,
overlayTheme: "a",
dividerTheme: "b",
hidePlaceholderMenuItems: true,
closeText: "Close",
nativeMenu: true,
// This option defaults to true on iOS devices.
preventFocusZoom: /iPhone|iPad|iPod/.test(navigator.platform) && navigator.userAgent.indexOf("AppleWebKit") > -1,
initSelector: "select:not( :jqmData(role='slider') )",
mini: false
},
_button: function () {
return $("<div/>");
},
_setDisabled: function (value) {
this.element.attr("disabled", value);
this.button.attr("aria-disabled", value);
return this._setOption("disabled", value);
},
_focusButton: function () {
var self = this;
setTimeout(function () {
self.button.focus();
}, 40);
},
_selectOptions: function () {
return this.select.find("option");
},
// setup items that are generally necessary for select menu extension
_preExtension: function () {
var classes = "";
// TODO: Post 1.1--once we have time to test thoroughly--any classes manually applied to the original element should be carried over to the enhanced element, with an `-enhanced` suffix. See https://github.com/jquery/jquery-mobile/issues/3577
/* if ( $el[0].className.length ) {
classes = $el[0].className;
} */
if (!!~this.element[0].className.indexOf("ui-btn-left")) {
classes = " ui-btn-left";
}
if (!!~this.element[0].className.indexOf("ui-btn-right")) {
classes = " ui-btn-right";
}
this.select = this.element.removeClass("ui-btn-left ui-btn-right").wrap("<div class='ui-select" + classes + "'>");
this.selectID = this.select.attr("id");
this.label = $("label[for='" + this.selectID + "']").addClass("ui-select");
this.isMultiple = this.select[ 0 ].multiple;
if (!this.options.theme) {
this.options.theme = $.mobile.getInheritedTheme(this.select, "c");
}
},
_destroy: function () {
var wrapper = this.element.parents(".ui-select");
if (wrapper.length > 0) {
if (wrapper.is(".ui-btn-left, .ui-btn-right")) {
this.element.addClass(wrapper.is(".ui-btn-left") ? "ui-btn-left" : "ui-btn-right");
}
this.element.insertAfter(wrapper);
wrapper.remove();
}
},
_create: function () {
this._preExtension();
// Allows for extension of the native select for custom selects and other plugins
// see select.custom for example extension
// TODO explore plugin registration
this._trigger("beforeCreate");
this.button = this._button();
var self = this,
options = this.options,
inline = options.inline || this.select.jqmData("inline"),
mini = options.mini || this.select.jqmData("mini"),
iconpos = options.icon ? ( options.iconpos || this.select.jqmData("iconpos") ) : false,
// IE throws an exception at options.item() function when
// there is no selected item
// select first in this case
selectedIndex = this.select[ 0 ].selectedIndex === -1 ? 0 : this.select[ 0 ].selectedIndex,
// TODO values buttonId and menuId are undefined here
button = this.button
.insertBefore(this.select)
.buttonMarkup({
theme: options.theme,
icon: options.icon,
iconpos: iconpos,
inline: inline,
corners: options.corners,
shadow: options.shadow,
iconshadow: options.iconshadow,
mini: mini
});
this.setButtonText();
// Opera does not properly support opacity on select elements
// In Mini, it hides the element, but not its text
// On the desktop,it seems to do the opposite
// for these reasons, using the nativeMenu option results in a full native select in Opera
if (options.nativeMenu && window.opera && window.opera.version) {
button.addClass("ui-select-nativeonly");
}
// Add counter for multi selects
if (this.isMultiple) {
this.buttonCount = $("<span>")
.addClass("ui-li-count ui-btn-up-c ui-btn-corner-all")
.hide()
.appendTo(button.addClass('ui-li-has-count'));
}
// Disable if specified
if (options.disabled || this.element.attr('disabled')) {
this.disable();
}
// Events on native select
this.select.change(function () {
self.refresh();
if (!!options.nativeMenu) {
this.blur();
}
});
this._handleFormReset();
this.build();
},
build: function () {
var self = this;
this.select
.appendTo(self.button)
.bind("vmousedown", function () {
// Add active class to button
self.button.addClass($.mobile.activeBtnClass);
})
.bind("focus", function () {
self.button.addClass($.mobile.focusClass);
})
.bind("blur", function () {
self.button.removeClass($.mobile.focusClass);
})
.bind("focus vmouseover", function () {
self.button.trigger("vmouseover");
})
.bind("vmousemove", function () {
// Remove active class on scroll/touchmove
self.button.removeClass($.mobile.activeBtnClass);
})
.bind("change blur vmouseout", function () {
self.button.trigger("vmouseout")
.removeClass($.mobile.activeBtnClass);
})
.bind("change blur", function () {
self.button.removeClass("ui-btn-down-" + self.options.theme);
});
// In many situations, iOS will zoom into the select upon tap, this prevents that from happening
self.button.bind("vmousedown", function () {
if (self.options.preventFocusZoom) {
$.mobile.zoom.disable(true);
}
});
self.label.bind("click focus", function () {
if (self.options.preventFocusZoom) {
$.mobile.zoom.disable(true);
}
});
self.select.bind("focus", function () {
if (self.options.preventFocusZoom) {
$.mobile.zoom.disable(true);
}
});
self.button.bind("mouseup", function () {
if (self.options.preventFocusZoom) {
setTimeout(function () {
$.mobile.zoom.enable(true);
}, 0);
}
});
self.select.bind("blur", function () {
if (self.options.preventFocusZoom) {
$.mobile.zoom.enable(true);
}
});
},
selected: function () {
return this._selectOptions().filter(":selected");
},
selectedIndices: function () {
var self = this;
return this.selected().map(function () {
return self._selectOptions().index(this);
}).get();
},
setButtonText: function () {
var self = this,
selected = this.selected(),
text = this.placeholder,
span = $(document.createElement("span"));
this.button.find(".ui-btn-text").html(function () {
if (selected.length) {
text = selected.map(function () {
return $(this).text();
}).get().join(", ");
} else {
text = self.placeholder;
}
// TODO possibly aggregate multiple select option classes
return span.text(text)
.addClass(self.select.attr("class"))
.addClass(selected.attr("class"));
});
},
setButtonCount: function () {
var selected = this.selected();
// multiple count inside button
if (this.isMultiple) {
this.buttonCount[ selected.length > 1 ? "show" : "hide" ]().text(selected.length);
}
},
_reset: function () {
this.refresh();
},
refresh: function () {
this.setButtonText();
this.setButtonCount();
},
// open and close preserved in native selects
// to simplify users code when looping over selects
open: $.noop,
close: $.noop,
disable: function () {
this._setDisabled(true);
this.button.addClass("ui-disabled");
},
enable: function () {
this._setDisabled(false);
this.button.removeClass("ui-disabled");
}
}, $.mobile.behaviors.formReset));
//auto self-init widgets
$.mobile.document.bind("pagecreate create", function (e) {
$.mobile.selectmenu.prototype.enhanceWithin(e.target, true);
});
})(jQuery);
(function ($, undefined) {
function fitSegmentInsideSegment(winSize, segSize, offset, desired) {
var ret = desired;
if (winSize < segSize) {
// Center segment if it's bigger than the window
ret = offset + ( winSize - segSize ) / 2;
} else {
// Otherwise center it at the desired coordinate while keeping it completely inside the window
ret = Math.min(Math.max(offset, desired - segSize / 2), offset + winSize - segSize);
}
return ret;
}
function windowCoords() {
var $win = $.mobile.window;
return {
x: $win.scrollLeft(),
y: $win.scrollTop(),
cx: ( window.innerWidth || $win.width() ),
cy: ( window.innerHeight || $win.height() )
};
}
$.widget("mobile.popup", $.mobile.widget, {
options: {
theme: null,
overlayTheme: null,
shadow: true,
corners: true,
transition: "none",
positionTo: "origin",
tolerance: null,
initSelector: ":jqmData(role='popup')",
closeLinkSelector: "a:jqmData(rel='back')",
closeLinkEvents: "click.popup",
navigateEvents: "navigate.popup",
closeEvents: "navigate.popup pagebeforechange.popup",
dismissible: true,
// NOTE Windows Phone 7 has a scroll position caching issue that
// requires us to disable popup history management by default
// https://github.com/jquery/jquery-mobile/issues/4784
//
// NOTE this option is modified in _create!
history: !$.mobile.browser.oldIE
},
_eatEventAndClose: function (e) {
e.preventDefault();
e.stopImmediatePropagation();
if (this.options.dismissible) {
this.close();
}
return false;
},
// Make sure the screen size is increased beyond the page height if the popup's causes the document to increase in height
_resizeScreen: function () {
var popupHeight = this._ui.container.outerHeight(true);
this._ui.screen.removeAttr("style");
if (popupHeight > this._ui.screen.height()) {
this._ui.screen.height(popupHeight);
}
},
_handleWindowKeyUp: function (e) {
if (this._isOpen && e.keyCode === $.mobile.keyCode.ESCAPE) {
return this._eatEventAndClose(e);
}
},
_expectResizeEvent: function () {
var winCoords = windowCoords();
if (this._resizeData) {
if (winCoords.x === this._resizeData.winCoords.x &&
winCoords.y === this._resizeData.winCoords.y &&
winCoords.cx === this._resizeData.winCoords.cx &&
winCoords.cy === this._resizeData.winCoords.cy) {
// timeout not refreshed
return false;
} else {
// clear existing timeout - it will be refreshed below
clearTimeout(this._resizeData.timeoutId);
}
}
this._resizeData = {
timeoutId: setTimeout($.proxy(this, "_resizeTimeout"), 200),
winCoords: winCoords
};
return true;
},
_resizeTimeout: function () {
if (this._isOpen) {
if (!this._expectResizeEvent()) {
if (this._ui.container.hasClass("ui-popup-hidden")) {
// effectively rapid-open the popup while leaving the screen intact
this._ui.container.removeClass("ui-popup-hidden");
this.reposition({ positionTo: "window" });
this._ignoreResizeEvents();
}
this._resizeScreen();
this._resizeData = null;
this._orientationchangeInProgress = false;
}
} else {
this._resizeData = null;
this._orientationchangeInProgress = false;
}
},
_ignoreResizeEvents: function () {
var self = this;
if (this._ignoreResizeTo) {
clearTimeout(this._ignoreResizeTo);
}
this._ignoreResizeTo = setTimeout(function () {
self._ignoreResizeTo = 0;
}, 1000);
},
_handleWindowResize: function (e) {
if (this._isOpen && this._ignoreResizeTo === 0) {
if (( this._expectResizeEvent() || this._orientationchangeInProgress ) && !this._ui.container.hasClass("ui-popup-hidden")) {
// effectively rapid-close the popup while leaving the screen intact
this._ui.container
.addClass("ui-popup-hidden")
.removeAttr("style");
}
}
},
_handleWindowOrientationchange: function (e) {
if (!this._orientationchangeInProgress && this._isOpen && this._ignoreResizeTo === 0) {
this._expectResizeEvent();
this._orientationchangeInProgress = true;
}
},
// When the popup is open, attempting to focus on an element that is not a
// child of the popup will redirect focus to the popup
_handleDocumentFocusIn: function (e) {
var tgt = e.target, $tgt, ui = this._ui;
if (!this._isOpen) {
return;
}
if (tgt !== ui.container[ 0 ]) {
$tgt = $(e.target);
if (0 === $tgt.parents().filter(ui.container[ 0 ]).length) {
$(document.activeElement).one("focus", function (e) {
$tgt.blur();
});
ui.focusElement.focus();
e.preventDefault();
e.stopImmediatePropagation();
return false;
} else if (ui.focusElement[ 0 ] === ui.container[ 0 ]) {
ui.focusElement = $tgt;
}
}
this._ignoreResizeEvents();
},
_create: function () {
var ui = {
screen: $("<div class='ui-screen-hidden ui-popup-screen'></div>"),
placeholder: $("<div style='display: none;'><!-- placeholder --></div>"),
container: $("<div class='ui-popup-container ui-popup-hidden'></div>")
},
thisPage = this.element.closest(".ui-page"),
myId = this.element.attr("id"),
o = this.options,
key, value;
// We need to adjust the history option to be false if there's no AJAX nav.
// We can't do it in the option declarations because those are run before
// it is determined whether there shall be AJAX nav.
o.history = o.history && $.mobile.ajaxEnabled && $.mobile.hashListeningEnabled;
if (thisPage.length === 0) {
thisPage = $("body");
}
// define the container for navigation event bindings
// TODO this would be nice at the the mobile widget level
o.container = o.container || $.mobile.pageContainer || thisPage;
// Apply the proto
thisPage.append(ui.screen);
ui.container.insertAfter(ui.screen);
// Leave a placeholder where the element used to be
ui.placeholder.insertAfter(this.element);
if (myId) {
ui.screen.attr("id", myId + "-screen");
ui.container.attr("id", myId + "-popup");
ui.placeholder.html("<!-- placeholder for " + myId + " -->");
}
ui.container.append(this.element);
ui.focusElement = ui.container;
// Add class to popup element
this.element.addClass("ui-popup");
// Define instance variables
$.extend(this, {
_scrollTop: 0,
_page: thisPage,
_ui: ui,
_fallbackTransition: "",
_currentTransition: false,
_prereqs: null,
_isOpen: false,
_tolerance: null,
_resizeData: null,
_ignoreResizeTo: 0,
_orientationchangeInProgress: false
});
// This duplicates the code from the various option setters below for
// better performance. It must be kept in sync with those setters.
this._applyTheme(this.element, o.theme, "body");
this._applyTheme(this._ui.screen, o.overlayTheme, "overlay");
this._applyTransition(o.transition);
this.element
.toggleClass("ui-overlay-shadow", o.shadow)
.toggleClass("ui-corner-all", o.corners);
this._setTolerance(o.tolerance);
ui.screen.bind("vclick", $.proxy(this, "_eatEventAndClose"));
this._on($.mobile.window, {
orientationchange: $.proxy(this, "_handleWindowOrientationchange"),
resize: $.proxy(this, "_handleWindowResize"),
keyup: $.proxy(this, "_handleWindowKeyUp")
});
this._on($.mobile.document, {
focusin: $.proxy(this, "_handleDocumentFocusIn")
});
},
_applyTheme: function (dst, theme, prefix) {
var classes = ( dst.attr("class") || "").split(" "),
alreadyAdded = true,
currentTheme = null,
matches,
themeStr = String(theme);
while (classes.length > 0) {
currentTheme = classes.pop();
matches = ( new RegExp("^ui-" + prefix + "-([a-z])$") ).exec(currentTheme);
if (matches && matches.length > 1) {
currentTheme = matches[ 1 ];
break;
} else {
currentTheme = null;
}
}
if (theme !== currentTheme) {
dst.removeClass("ui-" + prefix + "-" + currentTheme);
if (!( theme === null || theme === "none" )) {
dst.addClass("ui-" + prefix + "-" + themeStr);
}
}
},
_setTheme: function (value) {
this._applyTheme(this.element, value, "body");
},
_setOverlayTheme: function (value) {
this._applyTheme(this._ui.screen, value, "overlay");
if (this._isOpen) {
this._ui.screen.addClass("in");
}
},
_setShadow: function (value) {
this.element.toggleClass("ui-overlay-shadow", value);
},
_setCorners: function (value) {
this.element.toggleClass("ui-corner-all", value);
},
_applyTransition: function (value) {
this._ui.container.removeClass(this._fallbackTransition);
if (value && value !== "none") {
this._fallbackTransition = $.mobile._maybeDegradeTransition(value);
if (this._fallbackTransition === "none") {
this._fallbackTransition = "";
}
this._ui.container.addClass(this._fallbackTransition);
}
},
_setTransition: function (value) {
if (!this._currentTransition) {
this._applyTransition(value);
}
},
_setTolerance: function (value) {
var tol = { t: 30, r: 15, b: 30, l: 15 };
if (value !== undefined) {
var ar = String(value).split(",");
$.each(ar, function (idx, val) {
ar[ idx ] = parseInt(val, 10);
});
switch (ar.length) {
// All values are to be the same
case 1:
if (!isNaN(ar[ 0 ])) {
tol.t = tol.r = tol.b = tol.l = ar[ 0 ];
}
break;
// The first value denotes top/bottom tolerance, and the second value denotes left/right tolerance
case 2:
if (!isNaN(ar[ 0 ])) {
tol.t = tol.b = ar[ 0 ];
}
if (!isNaN(ar[ 1 ])) {
tol.l = tol.r = ar[ 1 ];
}
break;
// The array contains values in the order top, right, bottom, left
case 4:
if (!isNaN(ar[ 0 ])) {
tol.t = ar[ 0 ];
}
if (!isNaN(ar[ 1 ])) {
tol.r = ar[ 1 ];
}
if (!isNaN(ar[ 2 ])) {
tol.b = ar[ 2 ];
}
if (!isNaN(ar[ 3 ])) {
tol.l = ar[ 3 ];
}
break;
default:
break;
}
}
this._tolerance = tol;
},
_setOption: function (key, value) {
var setter = "_set" + key.charAt(0).toUpperCase() + key.slice(1);
if (this[ setter ] !== undefined) {
this[ setter ](value);
}
this._super(key, value);
},
// Try and center the overlay over the given coordinates
_placementCoords: function (desired) {
// rectangle within which the popup must fit
var
winCoords = windowCoords(),
rc = {
x: this._tolerance.l,
y: winCoords.y + this._tolerance.t,
cx: winCoords.cx - this._tolerance.l - this._tolerance.r,
cy: winCoords.cy - this._tolerance.t - this._tolerance.b
},
menuSize, ret;
// Clamp the width of the menu before grabbing its size
this._ui.container.css("max-width", rc.cx);
menuSize = {
cx: this._ui.container.outerWidth(true),
cy: this._ui.container.outerHeight(true)
};
// Center the menu over the desired coordinates, while not going outside
// the window tolerances. This will center wrt. the window if the popup is too large.
ret = {
x: fitSegmentInsideSegment(rc.cx, menuSize.cx, rc.x, desired.x),
y: fitSegmentInsideSegment(rc.cy, menuSize.cy, rc.y, desired.y)
};
// Make sure the top of the menu is visible
ret.y = Math.max(0, ret.y);
// If the height of the menu is smaller than the height of the document
// align the bottom with the bottom of the document
// fix for $.mobile.document.height() bug in core 1.7.2.
var docEl = document.documentElement, docBody = document.body,
docHeight = Math.max(docEl.clientHeight, docBody.scrollHeight, docBody.offsetHeight, docEl.scrollHeight, docEl.offsetHeight);
ret.y -= Math.min(ret.y, Math.max(0, ret.y + menuSize.cy - docHeight));
return { left: ret.x, top: ret.y };
},
_createPrereqs: function (screenPrereq, containerPrereq, whenDone) {
var self = this, prereqs;
// It is important to maintain both the local variable prereqs and self._prereqs. The local variable remains in
// the closure of the functions which call the callbacks passed in. The comparison between the local variable and
// self._prereqs is necessary, because once a function has been passed to .animationComplete() it will be called
// next time an animation completes, even if that's not the animation whose end the function was supposed to catch
// (for example, if an abort happens during the opening animation, the .animationComplete handler is not called for
// that animation anymore, but the handler remains attached, so it is called the next time the popup is opened
// - making it stale. Comparing the local variable prereqs to the widget-level variable self._prereqs ensures that
// callbacks triggered by a stale .animationComplete will be ignored.
prereqs = {
screen: $.Deferred(),
container: $.Deferred()
};
prereqs.screen.then(function () {
if (prereqs === self._prereqs) {
screenPrereq();
}
});
prereqs.container.then(function () {
if (prereqs === self._prereqs) {
containerPrereq();
}
});
$.when(prereqs.screen, prereqs.container).done(function () {
if (prereqs === self._prereqs) {
self._prereqs = null;
whenDone();
}
});
self._prereqs = prereqs;
},
_animate: function (args) {
// NOTE before removing the default animation of the screen
// this had an animate callback that would resolve the deferred
// now the deferred is resolved immediately
// TODO remove the dependency on the screen deferred
this._ui.screen
.removeClass(args.classToRemove)
.addClass(args.screenClassToAdd);
args.prereqs.screen.resolve();
if (args.transition && args.transition !== "none") {
if (args.applyTransition) {
this._applyTransition(args.transition);
}
if (this._fallbackTransition) {
this._ui.container
.animationComplete($.proxy(args.prereqs.container, "resolve"))
.addClass(args.containerClassToAdd)
.removeClass(args.classToRemove);
return;
}
}
this._ui.container.removeClass(args.classToRemove);
args.prereqs.container.resolve();
},
// The desired coordinates passed in will be returned untouched if no reference element can be identified via
// desiredPosition.positionTo. Nevertheless, this function ensures that its return value always contains valid
// x and y coordinates by specifying the center middle of the window if the coordinates are absent.
// options: { x: coordinate, y: coordinate, positionTo: string: "origin", "window", or jQuery selector
_desiredCoords: function (o) {
var dst = null, offset, winCoords = windowCoords(), x = o.x, y = o.y, pTo = o.positionTo;
// Establish which element will serve as the reference
if (pTo && pTo !== "origin") {
if (pTo === "window") {
x = winCoords.cx / 2 + winCoords.x;
y = winCoords.cy / 2 + winCoords.y;
} else {
try {
dst = $(pTo);
} catch (e) {
dst = null;
}
if (dst) {
dst.filter(":visible");
if (dst.length === 0) {
dst = null;
}
}
}
}
// If an element was found, center over it
if (dst) {
offset = dst.offset();
x = offset.left + dst.outerWidth() / 2;
y = offset.top + dst.outerHeight() / 2;
}
// Make sure x and y are valid numbers - center over the window
if ($.type(x) !== "number" || isNaN(x)) {
x = winCoords.cx / 2 + winCoords.x;
}
if ($.type(y) !== "number" || isNaN(y)) {
y = winCoords.cy / 2 + winCoords.y;
}
return { x: x, y: y };
},
_reposition: function (o) {
// We only care about position-related parameters for repositioning
o = { x: o.x, y: o.y, positionTo: o.positionTo };
this._trigger("beforeposition", undefined, o);
this._ui.container.offset(this._placementCoords(this._desiredCoords(o)));
},
reposition: function (o) {
if (this._isOpen) {
this._reposition(o);
}
},
_openPrereqsComplete: function () {
this._ui.container.addClass("ui-popup-active");
this._isOpen = true;
this._resizeScreen();
this._ui.container.attr("tabindex", "0").focus();
this._ignoreResizeEvents();
this._trigger("afteropen");
},
_open: function (options) {
var o = $.extend({}, this.options, options),
// TODO move blacklist to private method
androidBlacklist = ( function () {
var w = window,
ua = navigator.userAgent,
// Rendering engine is Webkit, and capture major version
wkmatch = ua.match(/AppleWebKit\/([0-9\.]+)/),
wkversion = !!wkmatch && wkmatch[ 1 ],
androidmatch = ua.match(/Android (\d+(?:\.\d+))/),
andversion = !!androidmatch && androidmatch[ 1 ],
chromematch = ua.indexOf("Chrome") > -1;
// Platform is Android, WebKit version is greater than 534.13 ( Android 3.2.1 ) and not Chrome.
if (androidmatch !== null && andversion === "4.0" && wkversion && wkversion > 534.13 && !chromematch) {
return true;
}
return false;
}());
// Count down to triggering "popupafteropen" - we have two prerequisites:
// 1. The popup window animation completes (container())
// 2. The screen opacity animation completes (screen())
this._createPrereqs(
$.noop,
$.noop,
$.proxy(this, "_openPrereqsComplete"));
this._currentTransition = o.transition;
this._applyTransition(o.transition);
if (!this.options.theme) {
this._setTheme(this._page.jqmData("theme") || $.mobile.getInheritedTheme(this._page, "c"));
}
this._ui.screen.removeClass("ui-screen-hidden");
this._ui.container.removeClass("ui-popup-hidden");
// Give applications a chance to modify the contents of the container before it appears
this._reposition(o);
if (this.options.overlayTheme && androidBlacklist) {
/* TODO:
The native browser on Android 4.0.X ("Ice Cream Sandwich") suffers from an issue where the popup overlay appears to be z-indexed
above the popup itself when certain other styles exist on the same page -- namely, any element set to `position: fixed` and certain
types of input. These issues are reminiscent of previously uncovered bugs in older versions of Android's native browser:
https://github.com/scottjehl/Device-Bugs/issues/3
This fix closes the following bugs ( I use "closes" with reluctance, and stress that this issue should be revisited as soon as possible ):
https://github.com/jquery/jquery-mobile/issues/4816
https://github.com/jquery/jquery-mobile/issues/4844
https://github.com/jquery/jquery-mobile/issues/4874
*/
// TODO sort out why this._page isn't working
this.element.closest(".ui-page").addClass("ui-popup-open");
}
this._animate({
additionalCondition: true,
transition: o.transition,
classToRemove: "",
screenClassToAdd: "in",
containerClassToAdd: "in",
applyTransition: false,
prereqs: this._prereqs
});
},
_closePrereqScreen: function () {
this._ui.screen
.removeClass("out")
.addClass("ui-screen-hidden");
},
_closePrereqContainer: function () {
this._ui.container
.removeClass("reverse out")
.addClass("ui-popup-hidden")
.removeAttr("style");
},
_closePrereqsDone: function () {
var container = this._ui.container;
container.removeAttr("tabindex");
// remove the global mutex for popups
$.mobile.popup.active = undefined;
// Blur elements inside the container, including the container
$(":focus", container[ 0 ]).add(container[ 0 ]).blur();
// alert users that the popup is closed
this._trigger("afterclose");
},
_close: function (immediate) {
this._ui.container.removeClass("ui-popup-active");
this._page.removeClass("ui-popup-open");
this._isOpen = false;
// Count down to triggering "popupafterclose" - we have two prerequisites:
// 1. The popup window reverse animation completes (container())
// 2. The screen opacity animation completes (screen())
this._createPrereqs(
$.proxy(this, "_closePrereqScreen"),
$.proxy(this, "_closePrereqContainer"),
$.proxy(this, "_closePrereqsDone"));
this._animate({
additionalCondition: this._ui.screen.hasClass("in"),
transition: ( immediate ? "none" : ( this._currentTransition ) ),
classToRemove: "in",
screenClassToAdd: "out",
containerClassToAdd: "reverse out",
applyTransition: true,
prereqs: this._prereqs
});
},
_unenhance: function () {
// Put the element back to where the placeholder was and remove the "ui-popup" class
this._setTheme("none");
this.element
// Cannot directly insertAfter() - we need to detach() first, because
// insertAfter() will do nothing if the payload div was not attached
// to the DOM at the time the widget was created, and so the payload
// will remain inside the container even after we call insertAfter().
// If that happens and we remove the container a few lines below, we
// will cause an infinite recursion - #5244
.detach()
.insertAfter(this._ui.placeholder)
.removeClass("ui-popup ui-overlay-shadow ui-corner-all");
this._ui.screen.remove();
this._ui.container.remove();
this._ui.placeholder.remove();
},
_destroy: function () {
if ($.mobile.popup.active === this) {
this.element.one("popupafterclose", $.proxy(this, "_unenhance"));
this.close();
} else {
this._unenhance();
}
},
_closePopup: function (e, data) {
var parsedDst, toUrl, o = this.options, immediate = false;
// restore location on screen
window.scrollTo(0, this._scrollTop);
if (e && e.type === "pagebeforechange" && data) {
// Determine whether we need to rapid-close the popup, or whether we can
// take the time to run the closing transition
if (typeof data.toPage === "string") {
parsedDst = data.toPage;
} else {
parsedDst = data.toPage.jqmData("url");
}
parsedDst = $.mobile.path.parseUrl(parsedDst);
toUrl = parsedDst.pathname + parsedDst.search + parsedDst.hash;
if (this._myUrl !== $.mobile.path.makeUrlAbsolute(toUrl)) {
// Going to a different page - close immediately
immediate = true;
} else {
e.preventDefault();
}
}
// remove nav bindings
o.container.unbind(o.closeEvents);
// unbind click handlers added when history is disabled
this.element.undelegate(o.closeLinkSelector, o.closeLinkEvents);
this._close(immediate);
},
// any navigation event after a popup is opened should close the popup
// NOTE the pagebeforechange is bound to catch navigation events that don't
// alter the url (eg, dialogs from popups)
_bindContainerClose: function () {
this.options.container
.one(this.options.closeEvents, $.proxy(this, "_closePopup"));
},
// TODO no clear deliniation of what should be here and
// what should be in _open. Seems to be "visual" vs "history" for now
open: function (options) {
var self = this, opts = this.options, url, hashkey, activePage, currentIsDialog, hasHash, urlHistory;
// make sure open is idempotent
if ($.mobile.popup.active) {
return;
}
// set the global popup mutex
$.mobile.popup.active = this;
this._scrollTop = $.mobile.window.scrollTop();
// if history alteration is disabled close on navigate events
// and leave the url as is
if (!( opts.history )) {
self._open(options);
self._bindContainerClose();
// When histoy is disabled we have to grab the data-rel
// back link clicks so we can close the popup instead of
// relying on history to do it for us
self.element
.delegate(opts.closeLinkSelector, opts.closeLinkEvents, function (e) {
self.close();
e.preventDefault();
});
return;
}
// cache some values for min/readability
urlHistory = $.mobile.urlHistory;
hashkey = $.mobile.dialogHashKey;
activePage = $.mobile.activePage;
currentIsDialog = activePage.is(".ui-dialog");
this._myUrl = url = urlHistory.getActive().url;
hasHash = ( url.indexOf(hashkey) > -1 ) && !currentIsDialog && ( urlHistory.activeIndex > 0 );
if (hasHash) {
self._open(options);
self._bindContainerClose();
return;
}
// if the current url has no dialog hash key proceed as normal
// otherwise, if the page is a dialog simply tack on the hash key
if (url.indexOf(hashkey) === -1 && !currentIsDialog) {
url = url + (url.indexOf("#") > -1 ? hashkey : "#" + hashkey);
} else {
url = $.mobile.path.parseLocation().hash + hashkey;
}
// Tack on an extra hashkey if this is the first page and we've just reconstructed the initial hash
if (urlHistory.activeIndex === 0 && url === urlHistory.initialDst) {
url += hashkey;
}
// swallow the the initial navigation event, and bind for the next
$(window).one("beforenavigate", function (e) {
e.preventDefault();
self._open(options);
self._bindContainerClose();
});
this.urlAltered = true;
$.mobile.navigate(url, {role: "dialog"});
},
close: function () {
// make sure close is idempotent
if ($.mobile.popup.active !== this) {
return;
}
this._scrollTop = $.mobile.window.scrollTop();
if (this.options.history && this.urlAltered) {
$.mobile.back();
this.urlAltered = false;
} else {
// simulate the nav bindings having fired
this._closePopup();
}
}
});
// TODO this can be moved inside the widget
$.mobile.popup.handleLink = function ($link) {
var closestPage = $link.closest(":jqmData(role='page')"),
scope = ( ( closestPage.length === 0 ) ? $("body") : closestPage ),
// NOTE make sure to get only the hash, ie7 (wp7) return the absolute href
// in this case ruining the element selection
popup = $($.mobile.path.parseUrl($link.attr("href")).hash, scope[0]),
offset;
if (popup.data("mobile-popup")) {
offset = $link.offset();
popup.popup("open", {
x: offset.left + $link.outerWidth() / 2,
y: offset.top + $link.outerHeight() / 2,
transition: $link.jqmData("transition"),
positionTo: $link.jqmData("position-to")
});
}
//remove after delay
setTimeout(function () {
// Check if we are in a listview
var $parent = $link.parent().parent();
if ($parent.hasClass("ui-li")) {
$link = $parent.parent();
}
$link.removeClass($.mobile.activeBtnClass);
}, 300);
};
// TODO move inside _create
$.mobile.document.bind("pagebeforechange", function (e, data) {
if (data.options.role === "popup") {
$.mobile.popup.handleLink(data.options.link);
e.preventDefault();
}
});
$.mobile.document.bind("pagecreate create", function (e) {
$.mobile.popup.prototype.enhanceWithin(e.target, true);
});
})(jQuery);
/*
* custom "selectmenu" plugin
*/
(function ($, undefined) {
var extendSelect = function (widget) {
var select = widget.select,
origDestroy = widget._destroy,
selectID = widget.selectID,
prefix = ( selectID ? selectID : ( ( $.mobile.ns || "" ) + "uuid-" + widget.uuid ) ),
popupID = prefix + "-listbox",
dialogID = prefix + "-dialog",
label = widget.label,
thisPage = widget.select.closest(".ui-page"),
selectOptions = widget._selectOptions(),
isMultiple = widget.isMultiple = widget.select[ 0 ].multiple,
buttonId = selectID + "-button",
menuId = selectID + "-menu",
menuPage = $("<div data-" + $.mobile.ns + "role='dialog' id='" + dialogID + "' data-" + $.mobile.ns + "theme='" + widget.options.theme + "' data-" + $.mobile.ns + "overlay-theme='" + widget.options.overlayTheme + "'>" +
"<div data-" + $.mobile.ns + "role='header'>" +
"<div class='ui-title'>" + label.getEncodedText() + "</div>" +
"</div>" +
"<div data-" + $.mobile.ns + "role='content'></div>" +
"</div>"),
listbox = $("<div id='" + popupID + "' class='ui-selectmenu'>").insertAfter(widget.select).popup({ theme: widget.options.overlayTheme }),
list = $("<ul>", {
"class": "ui-selectmenu-list",
"id": menuId,
"role": "listbox",
"aria-labelledby": buttonId
}).attr("data-" + $.mobile.ns + "theme", widget.options.theme)
.attr("data-" + $.mobile.ns + "divider-theme", widget.options.dividerTheme)
.appendTo(listbox),
header = $("<div>", {
"class": "ui-header ui-bar-" + widget.options.theme
}).prependTo(listbox),
headerTitle = $("<h1>", {
"class": "ui-title"
}).appendTo(header),
menuPageContent,
menuPageClose,
headerClose;
if (widget.isMultiple) {
headerClose = $("<a>", {
"text": widget.options.closeText,
"href": "#",
"class": "ui-btn-left"
}).attr("data-" + $.mobile.ns + "iconpos", "notext").attr("data-" + $.mobile.ns + "icon", "delete").appendTo(header).buttonMarkup();
}
$.extend(widget, {
select: widget.select,
selectID: selectID,
buttonId: buttonId,
menuId: menuId,
popupID: popupID,
dialogID: dialogID,
thisPage: thisPage,
menuPage: menuPage,
label: label,
selectOptions: selectOptions,
isMultiple: isMultiple,
theme: widget.options.theme,
listbox: listbox,
list: list,
header: header,
headerTitle: headerTitle,
headerClose: headerClose,
menuPageContent: menuPageContent,
menuPageClose: menuPageClose,
placeholder: "",
build: function () {
var self = this,
escapeId = function (id) {
return id.replace(/([!"#$%&'()*+,./:;<=>?@[\]^`{|}~])/g, "\\$1");
};
// Create list from select, update state
self.refresh();
if (self._origTabIndex === undefined) {
// Map undefined to false, because self._origTabIndex === undefined
// indicates that we have not yet checked whether the select has
// originally had a tabindex attribute, whereas false indicates that
// we have checked the select for such an attribute, and have found
// none present.
self._origTabIndex = ( self.select[ 0 ].getAttribute("tabindex") === null ) ? false : self.select.attr("tabindex");
}
self.select.attr("tabindex", "-1").focus(function () {
$(this).blur();
self.button.focus();
});
// Button events
self.button.bind("vclick keydown", function (event) {
if (self.options.disabled || self.isOpen) {
return;
}
if (event.type === "vclick" ||
event.keyCode && (event.keyCode === $.mobile.keyCode.ENTER ||
event.keyCode === $.mobile.keyCode.SPACE)) {
self._decideFormat();
if (self.menuType === "overlay") {
self.button.attr("href", "#" + escapeId(self.popupID)).attr("data-" + ( $.mobile.ns || "" ) + "rel", "popup");
} else {
self.button.attr("href", "#" + escapeId(self.dialogID)).attr("data-" + ( $.mobile.ns || "" ) + "rel", "dialog");
}
self.isOpen = true;
// Do not prevent default, so the navigation may have a chance to actually open the chosen format
}
});
// Events for list items
self.list.attr("role", "listbox")
.bind("focusin", function (e) {
$(e.target)
.attr("tabindex", "0")
.trigger("vmouseover");
})
.bind("focusout", function (e) {
$(e.target)
.attr("tabindex", "-1")
.trigger("vmouseout");
})
.delegate("li:not(.ui-disabled, .ui-li-divider)", "click", function (event) {
// index of option tag to be selected
var oldIndex = self.select[ 0 ].selectedIndex,
newIndex = self.list.find("li:not(.ui-li-divider)").index(this),
option = self._selectOptions().eq(newIndex)[ 0 ];
// toggle selected status on the tag for multi selects
option.selected = self.isMultiple ? !option.selected : true;
// toggle checkbox class for multiple selects
if (self.isMultiple) {
$(this).find(".ui-icon")
.toggleClass("ui-icon-checkbox-on", option.selected)
.toggleClass("ui-icon-checkbox-off", !option.selected);
}
// trigger change if value changed
if (self.isMultiple || oldIndex !== newIndex) {
self.select.trigger("change");
}
// hide custom select for single selects only - otherwise focus clicked item
// We need to grab the clicked item the hard way, because the list may have been rebuilt
if (self.isMultiple) {
self.list.find("li:not(.ui-li-divider)").eq(newIndex)
.addClass("ui-btn-down-" + widget.options.theme).find("a").first().focus();
}
else {
self.close();
}
event.preventDefault();
})
.keydown(function (event) { //keyboard events for menu items
var target = $(event.target),
li = target.closest("li"),
prev, next;
// switch logic based on which key was pressed
switch (event.keyCode) {
// up or left arrow keys
case 38:
prev = li.prev().not(".ui-selectmenu-placeholder");
if (prev.is(".ui-li-divider")) {
prev = prev.prev();
}
// if there's a previous option, focus it
if (prev.length) {
target
.blur()
.attr("tabindex", "-1");
prev.addClass("ui-btn-down-" + widget.options.theme).find("a").first().focus();
}
return false;
// down or right arrow keys
case 40:
next = li.next();
if (next.is(".ui-li-divider")) {
next = next.next();
}
// if there's a next option, focus it
if (next.length) {
target
.blur()
.attr("tabindex", "-1");
next.addClass("ui-btn-down-" + widget.options.theme).find("a").first().focus();
}
return false;
// If enter or space is pressed, trigger click
case 13:
case 32:
target.trigger("click");
return false;
}
});
// button refocus ensures proper height calculation
// by removing the inline style and ensuring page inclusion
self.menuPage.bind("pagehide", function () {
// TODO centralize page removal binding / handling in the page plugin.
// Suggestion from @jblas to do refcounting
//
// TODO extremely confusing dependency on the open method where the pagehide.remove
// bindings are stripped to prevent the parent page from disappearing. The way
// we're keeping pages in the DOM right now sucks
//
// rebind the page remove that was unbound in the open function
// to allow for the parent page removal from actions other than the use
// of a dialog sized custom select
//
// doing this here provides for the back button on the custom select dialog
$.mobile._bindPageRemove.call(self.thisPage);
});
// Events on the popup
self.listbox.bind("popupafterclose", function (event) {
self.close();
});
// Close button on small overlays
if (self.isMultiple) {
self.headerClose.click(function () {
if (self.menuType === "overlay") {
self.close();
return false;
}
});
}
// track this dependency so that when the parent page
// is removed on pagehide it will also remove the menupage
self.thisPage.addDependents(this.menuPage);
},
_isRebuildRequired: function () {
var list = this.list.find("li"),
options = this._selectOptions();
// TODO exceedingly naive method to determine difference
// ignores value changes etc in favor of a forcedRebuild
// from the user in the refresh method
return options.text() !== list.text();
},
selected: function () {
return this._selectOptions().filter(":selected:not( :jqmData(placeholder='true') )");
},
refresh: function (forceRebuild, foo) {
var self = this,
select = this.element,
isMultiple = this.isMultiple,
indicies;
if (forceRebuild || this._isRebuildRequired()) {
self._buildList();
}
indicies = this.selectedIndices();
self.setButtonText();
self.setButtonCount();
self.list.find("li:not(.ui-li-divider)")
.removeClass($.mobile.activeBtnClass)
.attr("aria-selected", false)
.each(function (i) {
if ($.inArray(i, indicies) > -1) {
var item = $(this);
// Aria selected attr
item.attr("aria-selected", true);
// Multiple selects: add the "on" checkbox state to the icon
if (self.isMultiple) {
item.find(".ui-icon").removeClass("ui-icon-checkbox-off").addClass("ui-icon-checkbox-on");
} else {
if (item.is(".ui-selectmenu-placeholder")) {
item.next().addClass($.mobile.activeBtnClass);
} else {
item.addClass($.mobile.activeBtnClass);
}
}
}
});
},
close: function () {
if (this.options.disabled || !this.isOpen) {
return;
}
var self = this;
if (self.menuType === "page") {
self.menuPage.dialog("close");
self.list.appendTo(self.listbox);
} else {
self.listbox.popup("close");
}
self._focusButton();
// allow the dialog to be closed again
self.isOpen = false;
},
open: function () {
this.button.click();
},
_decideFormat: function () {
var self = this,
$window = $.mobile.window,
selfListParent = self.list.parent(),
menuHeight = selfListParent.outerHeight(),
menuWidth = selfListParent.outerWidth(),
activePage = $("." + $.mobile.activePageClass),
scrollTop = $window.scrollTop(),
btnOffset = self.button.offset().top,
screenHeight = $window.height(),
screenWidth = $window.width();
function focusMenuItem() {
var selector = self.list.find("." + $.mobile.activeBtnClass + " a");
if (selector.length === 0) {
selector = self.list.find("li.ui-btn:not( :jqmData(placeholder='true') ) a");
}
selector.first().focus().closest("li").addClass("ui-btn-down-" + widget.options.theme);
}
if (menuHeight > screenHeight - 80 || !$.support.scrollTop) {
self.menuPage.appendTo($.mobile.pageContainer).page();
self.menuPageContent = menuPage.find(".ui-content");
self.menuPageClose = menuPage.find(".ui-header a");
// prevent the parent page from being removed from the DOM,
// otherwise the results of selecting a list item in the dialog
// fall into a black hole
self.thisPage.unbind("pagehide.remove");
//for WebOS/Opera Mini (set lastscroll using button offset)
if (scrollTop === 0 && btnOffset > screenHeight) {
self.thisPage.one("pagehide", function () {
$(this).jqmData("lastScroll", btnOffset);
});
}
self.menuPage
.one("pageshow", function () {
focusMenuItem();
})
.one("pagehide", function () {
self.close();
});
self.menuType = "page";
self.menuPageContent.append(self.list);
self.menuPage.find("div .ui-title").text(self.label.text());
} else {
self.menuType = "overlay";
self.listbox.one("popupafteropen", focusMenuItem);
}
},
_buildList: function () {
var self = this,
o = this.options,
placeholder = this.placeholder,
needPlaceholder = true,
optgroups = [],
lis = [],
dataIcon = self.isMultiple ? "checkbox-off" : "false";
self.list.empty().filter(".ui-listview").listview("destroy");
var $options = self.select.find("option"),
numOptions = $options.length,
select = this.select[ 0 ],
dataPrefix = 'data-' + $.mobile.ns,
dataIndexAttr = dataPrefix + 'option-index',
dataIconAttr = dataPrefix + 'icon',
dataRoleAttr = dataPrefix + 'role',
dataPlaceholderAttr = dataPrefix + 'placeholder',
fragment = document.createDocumentFragment(),
isPlaceholderItem = false,
optGroup;
for (var i = 0; i < numOptions; i++, isPlaceholderItem = false) {
var option = $options[i],
$option = $(option),
parent = option.parentNode,
text = $option.text(),
anchor = document.createElement('a'),
classes = [];
anchor.setAttribute('href', '#');
anchor.appendChild(document.createTextNode(text));
// Are we inside an optgroup?
if (parent !== select && parent.nodeName.toLowerCase() === "optgroup") {
var optLabel = parent.getAttribute('label');
if (optLabel !== optGroup) {
var divider = document.createElement('li');
divider.setAttribute(dataRoleAttr, 'list-divider');
divider.setAttribute('role', 'option');
divider.setAttribute('tabindex', '-1');
divider.appendChild(document.createTextNode(optLabel));
fragment.appendChild(divider);
optGroup = optLabel;
}
}
if (needPlaceholder && ( !option.getAttribute("value") || text.length === 0 || $option.jqmData("placeholder") )) {
needPlaceholder = false;
isPlaceholderItem = true;
// If we have identified a placeholder, record the fact that it was
// us who have added the placeholder to the option and mark it
// retroactively in the select as well
if (null === option.getAttribute(dataPlaceholderAttr)) {
this._removePlaceholderAttr = true;
}
option.setAttribute(dataPlaceholderAttr, true);
if (o.hidePlaceholderMenuItems) {
classes.push("ui-selectmenu-placeholder");
}
if (placeholder !== text) {
placeholder = self.placeholder = text;
}
}
var item = document.createElement('li');
if (option.disabled) {
classes.push("ui-disabled");
item.setAttribute('aria-disabled', true);
}
item.setAttribute(dataIndexAttr, i);
item.setAttribute(dataIconAttr, dataIcon);
if (isPlaceholderItem) {
item.setAttribute(dataPlaceholderAttr, true);
}
item.className = classes.join(" ");
item.setAttribute('role', 'option');
anchor.setAttribute('tabindex', '-1');
item.appendChild(anchor);
fragment.appendChild(item);
}
self.list[0].appendChild(fragment);
// Hide header if it's not a multiselect and there's no placeholder
if (!this.isMultiple && !placeholder.length) {
this.header.hide();
} else {
this.headerTitle.text(this.placeholder);
}
// Now populated, create listview
self.list.listview();
},
_button: function () {
return $("<a>", {
"href": "#",
"role": "button",
// TODO value is undefined at creation
"id": this.buttonId,
"aria-haspopup": "true",
// TODO value is undefined at creation
"aria-owns": this.menuId
});
},
_destroy: function () {
this.close();
// Restore the tabindex attribute to its original value
if (this._origTabIndex !== undefined) {
if (this._origTabIndex !== false) {
this.select.attr("tabindex", this._origTabIndex);
} else {
this.select.removeAttr("tabindex");
}
}
// Remove the placeholder attribute if we were the ones to add it
if (this._removePlaceholderAttr) {
this._selectOptions().removeAttr("data-" + $.mobile.ns + "placeholder");
}
// Remove the popup
this.listbox.remove();
// Remove the dialog
this.menuPage.remove();
// Chain up
origDestroy.apply(this, arguments);
}
});
};
// issue #3894 - core doesn't trigger events on disabled delegates
$.mobile.document.bind("selectmenubeforecreate", function (event) {
var selectmenuWidget = $(event.target).data("mobile-selectmenu");
if (!selectmenuWidget.options.nativeMenu &&
selectmenuWidget.element.parents(":jqmData(role='popup')").length === 0) {
extendSelect(selectmenuWidget);
}
});
})(jQuery);
(function ($, undefined) {
$.widget("mobile.controlgroup", $.mobile.widget, $.extend({
options: {
shadow: false,
corners: true,
excludeInvisible: true,
type: "vertical",
mini: false,
initSelector: ":jqmData(role='controlgroup')"
},
_create: function () {
var $el = this.element,
ui = {
inner: $("<div class='ui-controlgroup-controls'></div>"),
legend: $("<div role='heading' class='ui-controlgroup-label'></div>")
},
grouplegend = $el.children("legend"),
self = this;
// Apply the proto
$el.wrapInner(ui.inner);
if (grouplegend.length) {
ui.legend.append(grouplegend).insertBefore($el.children(0));
}
$el.addClass("ui-corner-all ui-controlgroup");
$.extend(this, {
_initialRefresh: true
});
$.each(this.options, function (key, value) {
// Cause initial options to be applied by their handler by temporarily setting the option to undefined
// - the handler then sets it to the initial value
self.options[ key ] = undefined;
self._setOption(key, value, true);
});
},
_init: function () {
this.refresh();
},
_setOption: function (key, value) {
var setter = "_set" + key.charAt(0).toUpperCase() + key.slice(1);
if (this[ setter ] !== undefined) {
this[ setter ](value);
}
this._super(key, value);
this.element.attr("data-" + ( $.mobile.ns || "" ) + ( key.replace(/([A-Z])/, "-$1").toLowerCase() ), value);
},
_setType: function (value) {
this.element
.removeClass("ui-controlgroup-horizontal ui-controlgroup-vertical")
.addClass("ui-controlgroup-" + value);
this.refresh();
},
_setCorners: function (value) {
this.element.toggleClass("ui-corner-all", value);
},
_setShadow: function (value) {
this.element.toggleClass("ui-shadow", value);
},
_setMini: function (value) {
this.element.toggleClass("ui-mini", value);
},
container: function () {
return this.element.children(".ui-controlgroup-controls");
},
refresh: function () {
var els = this.element.find(".ui-btn").not(".ui-slider-handle"),
create = this._initialRefresh;
if ($.mobile.checkboxradio) {
this.element.find(":mobile-checkboxradio").checkboxradio("refresh");
}
this._addFirstLastClasses(els, this.options.excludeInvisible ? this._getVisibles(els, create) : els, create);
this._initialRefresh = false;
}
}, $.mobile.behaviors.addFirstLastClasses));
// TODO: Implement a mechanism to allow widgets to become enhanced in the
// correct order when their correct enhancement depends on other widgets in
// the page being correctly enhanced already.
//
// For now, we wait until dom-ready to attach the controlgroup's enhancement
// hook, because by that time, all the other widgets' enhancement hooks should
// already be in place, ensuring that all widgets that need to be grouped will
// already have been enhanced by the time the controlgroup is created.
$(function () {
$.mobile.document.bind("pagecreate create", function (e) {
$.mobile.controlgroup.prototype.enhanceWithin(e.target, true);
});
});
})(jQuery);
(function ($, undefined) {
$(document).bind("pagecreate create", function (e) {
//links within content areas, tests included with page
$(e.target)
.find("a")
.jqmEnhanceable()
.filter(":jqmData(rel='popup')[href][href!='']")
.each(function () {
// Accessibility info for popups
var e = this,
href = $(this).attr("href"),
idref = href.substring(1);
e.setAttribute("aria-haspopup", true);
e.setAttribute("aria-owns", idref);
e.setAttribute("aria-expanded", false);
$(document)
.on("popupafteropen", href, function () {
e.setAttribute("aria-expanded", true);
})
.on("popupafterclose", href, function () {
e.setAttribute("aria-expanded", false);
});
})
.end()
.not(".ui-btn, .ui-link-inherit, :jqmData(role='none'), :jqmData(role='nojs')")
.addClass("ui-link");
});
})(jQuery);
(function ($, undefined) {
$.widget("mobile.fixedtoolbar", $.mobile.widget, {
options: {
visibleOnPageShow: true,
disablePageZoom: true,
transition: "slide", //can be none, fade, slide (slide maps to slideup or slidedown)
fullscreen: false,
tapToggle: true,
tapToggleBlacklist: "a, button, input, select, textarea, .ui-header-fixed, .ui-footer-fixed, .ui-popup, .ui-panel, .ui-panel-dismiss-open",
hideDuringFocus: "input, textarea, select",
updatePagePadding: true,
trackPersistentToolbars: true,
// Browser detection! Weeee, here we go...
// Unfortunately, position:fixed is costly, not to mention probably impossible, to feature-detect accurately.
// Some tests exist, but they currently return false results in critical devices and browsers, which could lead to a broken experience.
// Testing fixed positioning is also pretty obtrusive to page load, requiring injected elements and scrolling the window
// The following function serves to rule out some popular browsers with known fixed-positioning issues
// This is a plugin option like any other, so feel free to improve or overwrite it
supportBlacklist: function () {
return !$.support.fixedPosition;
},
initSelector: ":jqmData(position='fixed')"
},
_create: function () {
var self = this,
o = self.options,
$el = self.element,
tbtype = $el.is(":jqmData(role='header')") ? "header" : "footer",
$page = $el.closest(".ui-page");
// Feature detecting support for
if (o.supportBlacklist()) {
self.destroy();
return;
}
$el.addClass("ui-" + tbtype + "-fixed");
// "fullscreen" overlay positioning
if (o.fullscreen) {
$el.addClass("ui-" + tbtype + "-fullscreen");
$page.addClass("ui-page-" + tbtype + "-fullscreen");
}
// If not fullscreen, add class to page to set top or bottom padding
else {
$page.addClass("ui-page-" + tbtype + "-fixed");
}
$.extend(this, {
_thisPage: null
});
self._addTransitionClass();
self._bindPageEvents();
self._bindToggleHandlers();
},
_addTransitionClass: function () {
var tclass = this.options.transition;
if (tclass && tclass !== "none") {
// use appropriate slide for header or footer
if (tclass === "slide") {
tclass = this.element.is(".ui-header") ? "slidedown" : "slideup";
}
this.element.addClass(tclass);
}
},
_bindPageEvents: function () {
this._thisPage = this.element.closest(".ui-page");
//page event bindings
// Fixed toolbars require page zoom to be disabled, otherwise usability issues crop up
// This method is meant to disable zoom while a fixed-positioned toolbar page is visible
this._on(this._thisPage, {
"pagebeforeshow": "_handlePageBeforeShow",
"webkitAnimationStart": "_handleAnimationStart",
"animationstart": "_handleAnimationStart",
"updatelayout": "_handleAnimationStart",
"pageshow": "_handlePageShow",
"pagebeforehide": "_handlePageBeforeHide"
});
},
_handlePageBeforeShow: function () {
var o = this.options;
if (o.disablePageZoom) {
$.mobile.zoom.disable(true);
}
if (!o.visibleOnPageShow) {
this.hide(true);
}
},
_handleAnimationStart: function () {
if (this.options.updatePagePadding) {
this.updatePagePadding(this._thisPage);
}
},
_handlePageShow: function () {
this.updatePagePadding(this._thisPage);
if (this.options.updatePagePadding) {
this._on($.mobile.window, { "throttledresize": "updatePagePadding" });
}
},
_handlePageBeforeHide: function (e, ui) {
var o = this.options;
if (o.disablePageZoom) {
$.mobile.zoom.enable(true);
}
if (o.updatePagePadding) {
this._off($.mobile.window, "throttledresize");
}
if (o.trackPersistentToolbars) {
var thisFooter = $(".ui-footer-fixed:jqmData(id)", this._thisPage),
thisHeader = $(".ui-header-fixed:jqmData(id)", this._thisPage),
nextFooter = thisFooter.length && ui.nextPage && $(".ui-footer-fixed:jqmData(id='" + thisFooter.jqmData("id") + "')", ui.nextPage) || $(),
nextHeader = thisHeader.length && ui.nextPage && $(".ui-header-fixed:jqmData(id='" + thisHeader.jqmData("id") + "')", ui.nextPage) || $();
if (nextFooter.length || nextHeader.length) {
nextFooter.add(nextHeader).appendTo($.mobile.pageContainer);
ui.nextPage.one("pageshow", function () {
nextHeader.prependTo(this);
nextFooter.appendTo(this);
});
}
}
},
_visible: true,
// This will set the content element's top or bottom padding equal to the toolbar's height
updatePagePadding: function (tbPage) {
var $el = this.element,
header = $el.is(".ui-header"),
pos = parseFloat($el.css(header ? "top" : "bottom"));
// This behavior only applies to "fixed", not "fullscreen"
if (this.options.fullscreen) {
return;
}
// tbPage argument can be a Page object or an event, if coming from throttled resize.
tbPage = ( tbPage && tbPage.type === undefined && tbPage ) || this._thisPage || $el.closest(".ui-page");
$(tbPage).css("padding-" + ( header ? "top" : "bottom" ), $el.outerHeight() + pos);
},
_useTransition: function (notransition) {
var $win = $.mobile.window,
$el = this.element,
scroll = $win.scrollTop(),
elHeight = $el.height(),
pHeight = $el.closest(".ui-page").height(),
viewportHeight = $.mobile.getScreenHeight(),
tbtype = $el.is(":jqmData(role='header')") ? "header" : "footer";
return !notransition &&
( this.options.transition && this.options.transition !== "none" &&
(
( tbtype === "header" && !this.options.fullscreen && scroll > elHeight ) ||
( tbtype === "footer" && !this.options.fullscreen && scroll + viewportHeight < pHeight - elHeight )
) || this.options.fullscreen
);
},
show: function (notransition) {
var hideClass = "ui-fixed-hidden",
$el = this.element;
if (this._useTransition(notransition)) {
$el
.removeClass("out " + hideClass)
.addClass("in")
.animationComplete(function () {
$el.removeClass('in');
});
}
else {
$el.removeClass(hideClass);
}
this._visible = true;
},
hide: function (notransition) {
var hideClass = "ui-fixed-hidden",
$el = this.element,
// if it's a slide transition, our new transitions need the reverse class as well to slide outward
outclass = "out" + ( this.options.transition === "slide" ? " reverse" : "" );
if (this._useTransition(notransition)) {
$el
.addClass(outclass)
.removeClass("in")
.animationComplete(function () {
$el.addClass(hideClass).removeClass(outclass);
});
}
else {
$el.addClass(hideClass).removeClass(outclass);
}
this._visible = false;
},
toggle: function () {
this[ this._visible ? "hide" : "show" ]();
},
_bindToggleHandlers: function () {
var self = this,
o = self.options,
$el = self.element,
delayShow, delayHide,
isVisible = true;
// tap toggle
$el.closest(".ui-page")
.bind("vclick", function (e) {
if (o.tapToggle && !$(e.target).closest(o.tapToggleBlacklist).length) {
self.toggle();
}
})
.bind("focusin focusout", function (e) {
//this hides the toolbars on a keyboard pop to give more screen room and prevent ios bug which
//positions fixed toolbars in the middle of the screen on pop if the input is near the top or
//bottom of the screen addresses issues #4410 Footer navbar moves up when clicking on a textbox in an Android environment
//and issue #4113 Header and footer change their position after keyboard popup - iOS
//and issue #4410 Footer navbar moves up when clicking on a textbox in an Android environment
if (screen.width < 1025 && $(e.target).is(o.hideDuringFocus) && !$(e.target).closest(".ui-header-fixed, .ui-footer-fixed").length) {
//Fix for issue #4724 Moving through form in Mobile Safari with "Next" and "Previous" system
//controls causes fixed position, tap-toggle false Header to reveal itself
// isVisible instead of self._visible because the focusin and focusout events fire twice at the same time
// Also use a delay for hiding the toolbars because on Android native browser focusin is direclty followed
// by a focusout when a native selects opens and the other way around when it closes.
if (e.type === "focusout" && !isVisible) {
isVisible = true;
//wait for the stack to unwind and see if we have jumped to another input
clearTimeout(delayHide);
delayShow = setTimeout(function () {
self.show();
}, 0);
} else if (e.type === "focusin" && !!isVisible) {
//if we have jumped to another input clear the time out to cancel the show.
clearTimeout(delayShow);
isVisible = false;
delayHide = setTimeout(function () {
self.hide();
}, 0);
}
}
});
},
_destroy: function () {
var $el = this.element,
header = $el.is(".ui-header");
$el.closest(".ui-page").css("padding-" + ( header ? "top" : "bottom" ), "");
$el.removeClass("ui-header-fixed ui-footer-fixed ui-header-fullscreen ui-footer-fullscreen in out fade slidedown slideup ui-fixed-hidden");
$el.closest(".ui-page").removeClass("ui-page-header-fixed ui-page-footer-fixed ui-page-header-fullscreen ui-page-footer-fullscreen");
}
});
//auto self-init widgets
$.mobile.document
.bind("pagecreate create", function (e) {
// DEPRECATED in 1.1: support for data-fullscreen=true|false on the page element.
// This line ensures it still works, but we recommend moving the attribute to the toolbars themselves.
if ($(e.target).jqmData("fullscreen")) {
$($.mobile.fixedtoolbar.prototype.options.initSelector, e.target).not(":jqmData(fullscreen)").jqmData("fullscreen", true);
}
$.mobile.fixedtoolbar.prototype.enhanceWithin(e.target);
});
})(jQuery);
(function ($, undefined) {
$.widget("mobile.fixedtoolbar", $.mobile.fixedtoolbar, {
_create: function () {
this._super();
this._workarounds();
},
//check the browser and version and run needed workarounds
_workarounds: function () {
var ua = navigator.userAgent,
platform = navigator.platform,
// Rendering engine is Webkit, and capture major version
wkmatch = ua.match(/AppleWebKit\/([0-9]+)/),
wkversion = !!wkmatch && wkmatch[ 1 ],
os = null,
self = this;
//set the os we are working in if it dosent match one with workarounds return
if (platform.indexOf("iPhone") > -1 || platform.indexOf("iPad") > -1 || platform.indexOf("iPod") > -1) {
os = "ios";
} else if (ua.indexOf("Android") > -1) {
os = "android";
} else {
return;
}
//check os version if it dosent match one with workarounds return
if (os === "ios") {
//iOS workarounds
self._bindScrollWorkaround();
} else if (os === "android" && wkversion && wkversion < 534) {
//Android 2.3 run all Android 2.3 workaround
self._bindScrollWorkaround();
self._bindListThumbWorkaround();
} else {
return;
}
},
//Utility class for checking header and footer positions relative to viewport
_viewportOffset: function () {
var $el = this.element,
header = $el.is(".ui-header"),
offset = Math.abs($el.offset().top - $.mobile.window.scrollTop());
if (!header) {
offset = Math.round(offset - $.mobile.window.height() + $el.outerHeight()) - 60;
}
return offset;
},
//bind events for _triggerRedraw() function
_bindScrollWorkaround: function () {
var self = this;
//bind to scrollstop and check if the toolbars are correctly positioned
this._on($.mobile.window, { scrollstop: function () {
var viewportOffset = self._viewportOffset();
//check if the header is visible and if its in the right place
if (viewportOffset > 2 && self._visible) {
self._triggerRedraw();
}
}});
},
//this addresses issue #4250 Persistent footer instability in v1.1 with long select lists in Android 2.3.3
//and issue #3748 Android 2.x: Page transitions broken when fixed toolbars used
//the absolutely positioned thumbnail in a list view causes problems with fixed position buttons above in a nav bar
//setting the li's to -webkit-transform:translate3d(0,0,0); solves this problem to avoide potential issues in other
//platforms we scope this with the class ui-android-2x-fix
_bindListThumbWorkaround: function () {
this.element.closest(".ui-page").addClass("ui-android-2x-fixed");
},
//this addresses issues #4337 Fixed header problem after scrolling content on iOS and Android
//and device bugs project issue #1 Form elements can lose click hit area in position: fixed containers.
//this also addresses not on fixed toolbars page in docs
//adding 1px of padding to the bottom then removing it causes a "redraw"
//which positions the toolbars correctly (they will always be visually correct)
_triggerRedraw: function () {
var paddingBottom = parseFloat($(".ui-page-active").css("padding-bottom"));
//trigger page redraw to fix incorrectly positioned fixed elements
$(".ui-page-active").css("padding-bottom", ( paddingBottom + 1 ) + "px");
//if the padding is reset with out a timeout the reposition will not occure.
//this is independant of JQM the browser seems to need the time to react.
setTimeout(function () {
$(".ui-page-active").css("padding-bottom", paddingBottom + "px");
}, 0);
},
destroy: function () {
this._super();
//Remove the class we added to the page previously in android 2.x
this.element.closest(".ui-page-active").removeClass("ui-android-2x-fix");
}
});
})(jQuery);
(function ($, undefined) {
$.widget("mobile.panel", $.mobile.widget, {
options: {
classes: {
panel: "ui-panel",
panelOpen: "ui-panel-open",
panelClosed: "ui-panel-closed",
panelFixed: "ui-panel-fixed",
panelInner: "ui-panel-inner",
modal: "ui-panel-dismiss",
modalOpen: "ui-panel-dismiss-open",
pagePanel: "ui-page-panel",
pagePanelOpen: "ui-page-panel-open",
contentWrap: "ui-panel-content-wrap",
contentWrapOpen: "ui-panel-content-wrap-open",
contentWrapClosed: "ui-panel-content-wrap-closed",
contentFixedToolbar: "ui-panel-content-fixed-toolbar",
contentFixedToolbarOpen: "ui-panel-content-fixed-toolbar-open",
contentFixedToolbarClosed: "ui-panel-content-fixed-toolbar-closed",
animate: "ui-panel-animate"
},
animate: true,
theme: "c",
position: "left",
dismissible: true,
display: "reveal", //accepts reveal, push, overlay
initSelector: ":jqmData(role='panel')",
swipeClose: true,
positionFixed: false
},
_panelID: null,
_closeLink: null,
_page: null,
_modal: null,
_panelInner: null,
_wrapper: null,
_fixedToolbar: null,
_create: function () {
var self = this,
$el = self.element,
page = $el.closest(":jqmData(role='page')"),
_getPageTheme = function () {
var $theme = $.data(page[0], "mobilePage").options.theme,
$pageThemeClass = "ui-body-" + $theme;
return $pageThemeClass;
},
_getPanelInner = function () {
var $panelInner = $el.find("." + self.options.classes.panelInner);
if ($panelInner.length === 0) {
$panelInner = $el.children().wrapAll('<div class="' + self.options.classes.panelInner + '" />').parent();
}
return $panelInner;
},
_getWrapper = function () {
var $wrapper = page.find("." + self.options.classes.contentWrap);
if ($wrapper.length === 0) {
$wrapper = page.children(".ui-header:not(:jqmData(position='fixed')), .ui-content:not(:jqmData(role='popup')), .ui-footer:not(:jqmData(position='fixed'))").wrapAll('<div class="' + self.options.classes.contentWrap + ' ' + _getPageTheme() + '" />').parent();
if ($.support.cssTransform3d && !!self.options.animate) {
$wrapper.addClass(self.options.classes.animate);
}
}
return $wrapper;
},
_getFixedToolbar = function () {
var $fixedToolbar = page.find("." + self.options.classes.contentFixedToolbar);
if ($fixedToolbar.length === 0) {
$fixedToolbar = page.find(".ui-header:jqmData(position='fixed'), .ui-footer:jqmData(position='fixed')").addClass(self.options.classes.contentFixedToolbar);
if ($.support.cssTransform3d && !!self.options.animate) {
$fixedToolbar.addClass(self.options.classes.animate);
}
}
return $fixedToolbar;
};
// expose some private props to other methods
$.extend(this, {
_panelID: $el.attr("id"),
_closeLink: $el.find(":jqmData(rel='close')"),
_page: $el.closest(":jqmData(role='page')"),
_pageTheme: _getPageTheme(),
_panelInner: _getPanelInner(),
_wrapper: _getWrapper(),
_fixedToolbar: _getFixedToolbar()
});
self._addPanelClasses();
self._wrapper.addClass(this.options.classes.contentWrapClosed);
self._fixedToolbar.addClass(this.options.classes.contentFixedToolbarClosed);
// add class to page so we can set "overflow-x: hidden;" for it to fix Android zoom issue
self._page.addClass(self.options.classes.pagePanel);
// if animating, add the class to do so
if ($.support.cssTransform3d && !!self.options.animate) {
this.element.addClass(self.options.classes.animate);
}
self._bindUpdateLayout();
self._bindCloseEvents();
self._bindLinkListeners();
self._bindPageEvents();
if (!!self.options.dismissible) {
self._createModal();
}
self._bindSwipeEvents();
},
_createModal: function (options) {
var self = this;
self._modal = $("<div class='" + self.options.classes.modal + "' data-panelid='" + self._panelID + "'></div>")
.on("mousedown", function () {
self.close();
})
.appendTo(this._page);
},
_getPosDisplayClasses: function (prefix) {
return prefix + "-position-" + this.options.position + " " + prefix + "-display-" + this.options.display;
},
_getPanelClasses: function () {
var panelClasses = this.options.classes.panel +
" " + this._getPosDisplayClasses(this.options.classes.panel) +
" " + this.options.classes.panelClosed;
if (this.options.theme) {
panelClasses += " ui-body-" + this.options.theme;
}
if (!!this.options.positionFixed) {
panelClasses += " " + this.options.classes.panelFixed;
}
return panelClasses;
},
_addPanelClasses: function () {
this.element.addClass(this._getPanelClasses());
},
_bindCloseEvents: function () {
var self = this;
self._closeLink.on("click.panel", function (e) {
e.preventDefault();
self.close();
return false;
});
self.element.on("click.panel", "a:jqmData(ajax='false')", function (e) {
self.close();
});
},
_positionPanel: function () {
var self = this,
panelInnerHeight = self._panelInner.outerHeight(),
expand = panelInnerHeight > $.mobile.getScreenHeight();
if (expand || !self.options.positionFixed) {
if (expand) {
self._unfixPanel();
$.mobile.resetActivePageHeight(panelInnerHeight);
}
self._scrollIntoView(panelInnerHeight);
} else {
self._fixPanel();
}
},
_scrollIntoView: function (panelInnerHeight) {
if (panelInnerHeight < $(window).scrollTop()) {
window.scrollTo(0, 0);
}
},
_bindFixListener: function () {
this._on($(window), { "throttledresize": "_positionPanel" });
},
_unbindFixListener: function () {
this._off($(window), "throttledresize");
},
_unfixPanel: function () {
if (!!this.options.positionFixed && $.support.fixedPosition) {
this.element.removeClass(this.options.classes.panelFixed);
}
},
_fixPanel: function () {
if (!!this.options.positionFixed && $.support.fixedPosition) {
this.element.addClass(this.options.classes.panelFixed);
}
},
_bindUpdateLayout: function () {
var self = this;
self.element.on("updatelayout", function (e) {
if (self._open) {
self._positionPanel();
}
});
},
_bindLinkListeners: function () {
var self = this;
self._page.on("click.panel", "a", function (e) {
if (this.href.split("#")[ 1 ] === self._panelID && self._panelID !== undefined) {
e.preventDefault();
var $link = $(this),
$parent;
if (!$link.hasClass("ui-link")) {
// Check if we are in a listview
$parent = $link.parent().parent();
if ($parent.hasClass("ui-li")) {
$link = $parent.parent();
}
$link.addClass($.mobile.activeBtnClass);
self.element.one("panelopen panelclose", function () {
$link.removeClass($.mobile.activeBtnClass);
});
}
self.toggle();
return false;
}
});
},
_bindSwipeEvents: function () {
var self = this,
area = self._modal ? self.element.add(self._modal) : self.element;
// on swipe, close the panel
if (!!self.options.swipeClose) {
if (self.options.position === "left") {
area.on("swipeleft.panel", function (e) {
self.close();
});
} else {
area.on("swiperight.panel", function (e) {
self.close();
});
}
}
},
_bindPageEvents: function () {
var self = this;
self._page
// Close the panel if another panel on the page opens
.on("panelbeforeopen", function (e) {
if (self._open && e.target !== self.element[ 0 ]) {
self.close();
}
})
// clean up open panels after page hide
.on("pagehide", function (e) {
if (self._open) {
self.close(true);
}
})
// on escape, close? might need to have a target check too...
.on("keyup.panel", function (e) {
if (e.keyCode === 27 && self._open) {
self.close();
}
});
},
// state storage of open or closed
_open: false,
_contentWrapOpenClasses: null,
_fixedToolbarOpenClasses: null,
_modalOpenClasses: null,
open: function (immediate) {
if (!this._open) {
var self = this,
o = self.options,
_openPanel = function () {
self._page.off("panelclose");
self._page.jqmData("panel", "open");
if (!immediate && $.support.cssTransform3d && !!o.animate) {
self.element.add(self._wrapper).on(self._transitionEndEvents, complete);
} else {
setTimeout(complete, 0);
}
if (self.options.theme && self.options.display !== "overlay") {
self._page
.removeClass(self._pageTheme)
.addClass("ui-body-" + self.options.theme);
}
self.element.removeClass(o.classes.panelClosed).addClass(o.classes.panelOpen);
self._positionPanel();
// Fix for IE7 min-height bug
if (self.options.theme && self.options.display !== "overlay") {
self._wrapper.css("min-height", self._page.css("min-height"));
}
self._contentWrapOpenClasses = self._getPosDisplayClasses(o.classes.contentWrap);
self._wrapper
.removeClass(o.classes.contentWrapClosed)
.addClass(self._contentWrapOpenClasses + " " + o.classes.contentWrapOpen);
self._fixedToolbarOpenClasses = self._getPosDisplayClasses(o.classes.contentFixedToolbar);
self._fixedToolbar
.removeClass(o.classes.contentFixedToolbarClosed)
.addClass(self._fixedToolbarOpenClasses + " " + o.classes.contentFixedToolbarOpen);
self._modalOpenClasses = self._getPosDisplayClasses(o.classes.modal) + " " + o.classes.modalOpen;
if (self._modal) {
self._modal.addClass(self._modalOpenClasses);
}
},
complete = function () {
self.element.add(self._wrapper).off(self._transitionEndEvents, complete);
self._page.addClass(o.classes.pagePanelOpen);
self._bindFixListener();
self._trigger("open");
};
if (this.element.closest(".ui-page-active").length < 0) {
immediate = true;
}
self._trigger("beforeopen");
if (self._page.jqmData('panel') === "open") {
self._page.on("panelclose", function () {
_openPanel();
});
} else {
_openPanel();
}
self._open = true;
}
},
close: function (immediate) {
if (this._open) {
var o = this.options,
self = this,
_closePanel = function () {
if (!immediate && $.support.cssTransform3d && !!o.animate) {
self.element.add(self._wrapper).on(self._transitionEndEvents, complete);
} else {
setTimeout(complete, 0);
}
self._page.removeClass(o.classes.pagePanelOpen);
self.element.removeClass(o.classes.panelOpen);
self._wrapper.removeClass(o.classes.contentWrapOpen);
self._fixedToolbar.removeClass(o.classes.contentFixedToolbarOpen);
if (self._modal) {
self._modal.removeClass(self._modalOpenClasses);
}
},
complete = function () {
if (self.options.theme && self.options.display !== "overlay") {
self._page.removeClass("ui-body-" + self.options.theme).addClass(self._pageTheme);
// reset fix for IE7 min-height bug
self._wrapper.css("min-height", "");
}
self.element.add(self._wrapper).off(self._transitionEndEvents, complete);
self.element.addClass(o.classes.panelClosed);
self._wrapper
.removeClass(self._contentWrapOpenClasses)
.addClass(o.classes.contentWrapClosed);
self._fixedToolbar
.removeClass(self._fixedToolbarOpenClasses)
.addClass(o.classes.contentFixedToolbarClosed);
self._fixPanel();
self._unbindFixListener();
$.mobile.resetActivePageHeight();
self._page.jqmRemoveData("panel");
self._trigger("close");
};
if (this.element.closest(".ui-page-active").length < 0) {
immediate = true;
}
self._trigger("beforeclose");
_closePanel();
self._open = false;
}
},
toggle: function (options) {
this[ this._open ? "close" : "open" ]();
},
_transitionEndEvents: "webkitTransitionEnd oTransitionEnd otransitionend transitionend msTransitionEnd",
_destroy: function () {
var classes = this.options.classes,
theme = this.options.theme,
hasOtherSiblingPanels = this.element.siblings("." + classes.panel).length;
// create
if (!hasOtherSiblingPanels) {
this._wrapper.children().unwrap();
this._page.find("a").unbind("panelopen panelclose");
this._page.removeClass(classes.pagePanel);
if (this._open) {
this._page.jqmRemoveData("panel");
this._page.removeClass(classes.pagePanelOpen);
if (theme) {
this._page.removeClass("ui-body-" + theme).addClass(this._pageTheme);
}
$.mobile.resetActivePageHeight();
}
} else if (this._open) {
this._wrapper.removeClass(classes.contentWrapOpen);
this._fixedToolbar.removeClass(classes.contentFixedToolbarOpen);
this._page.jqmRemoveData("panel");
this._page.removeClass(classes.pagePanelOpen);
if (theme) {
this._page.removeClass("ui-body-" + theme).addClass(this._pageTheme);
}
}
this._panelInner.children().unwrap();
this.element.removeClass([ this._getPanelClasses(), classes.panelAnimate ].join(" "))
.off("swipeleft.panel swiperight.panel")
.off("panelbeforeopen")
.off("panelhide")
.off("keyup.panel")
.off("updatelayout");
this._closeLink.off("click.panel");
if (this._modal) {
this._modal.remove();
}
// open and close
this.element.off(this._transitionEndEvents)
.removeClass([ classes.panelUnfixed, classes.panelClosed, classes.panelOpen ].join(" "));
}
});
//auto self-init widgets
$(document).bind("pagecreate create", function (e) {
$.mobile.panel.prototype.enhanceWithin(e.target);
});
})(jQuery);
(function ($, undefined) {
$.widget("mobile.table", $.mobile.widget, {
options: {
classes: {
table: "ui-table"
},
initSelector: ":jqmData(role='table')"
},
_create: function () {
var self = this;
self.refresh(true);
},
refresh: function (create) {
var self = this,
trs = this.element.find("thead tr");
if (create) {
this.element.addClass(this.options.classes.table);
}
// Expose headers and allHeaders properties on the widget
// headers references the THs within the first TR in the table
self.headers = this.element.find("tr:eq(0)").children();
// allHeaders references headers, plus all THs in the thead, which may include several rows, or not
self.allHeaders = self.headers.add(trs.children());
trs.each(function () {
var coltally = 0;
$(this).children().each(function (i) {
var span = parseInt($(this).attr("colspan"), 10),
sel = ":nth-child(" + ( coltally + 1 ) + ")";
$(this)
.jqmData("colstart", coltally + 1);
if (span) {
for (var j = 0; j < span - 1; j++) {
coltally++;
sel += ", :nth-child(" + ( coltally + 1 ) + ")";
}
}
if (create === undefined) {
$(this).jqmData("cells", "");
}
// Store "cells" data on header as a reference to all cells in the same column as this TH
$(this)
.jqmData("cells", self.element.find("tr").not(trs.eq(0)).not(this).children(sel));
coltally++;
});
});
// update table modes
if (create === undefined) {
this.element.trigger('refresh');
}
}
});
//auto self-init widgets
$.mobile.document.bind("pagecreate create", function (e) {
$.mobile.table.prototype.enhanceWithin(e.target);
});
})(jQuery);
(function ($, undefined) {
$.mobile.table.prototype.options.mode = "columntoggle";
$.mobile.table.prototype.options.columnBtnTheme = null;
$.mobile.table.prototype.options.columnPopupTheme = null;
$.mobile.table.prototype.options.columnBtnText = "Columns...";
$.mobile.table.prototype.options.classes = $.extend(
$.mobile.table.prototype.options.classes,
{
popup: "ui-table-columntoggle-popup",
columnBtn: "ui-table-columntoggle-btn",
priorityPrefix: "ui-table-priority-",
columnToggleTable: "ui-table-columntoggle"
}
);
$.mobile.document.delegate(":jqmData(role='table')", "tablecreate refresh", function (e) {
var $table = $(this),
self = $table.data("mobile-table"),
event = e.type,
o = self.options,
ns = $.mobile.ns,
id = ( $table.attr("id") || o.classes.popup ) + "-popup", /* TODO BETTER FALLBACK ID HERE */
$menuButton,
$popup,
$menu,
$switchboard;
if (o.mode !== "columntoggle") {
return;
}
if (event !== "refresh") {
self.element.addClass(o.classes.columnToggleTable);
$menuButton = $("<a href='#" + id + "' class='" + o.classes.columnBtn + "' data-" + ns + "rel='popup' data-" + ns + "mini='true'>" + o.columnBtnText + "</a>"),
$popup = $("<div data-" + ns + "role='popup' data-" + ns + "role='fieldcontain' class='" + o.classes.popup + "' id='" + id + "'></div>"),
$menu = $("<fieldset data-" + ns + "role='controlgroup'></fieldset>");
}
// create the hide/show toggles
self.headers.not("td").each(function (i) {
var priority = $(this).jqmData("priority"),
$cells = $(this).add($(this).jqmData("cells"));
if (priority) {
$cells.addClass(o.classes.priorityPrefix + priority);
if (event !== "refresh") {
$("<label><input type='checkbox' checked />" + $(this).text() + "</label>")
.appendTo($menu)
.children(0)
.jqmData("cells", $cells)
.checkboxradio({
theme: o.columnPopupTheme
});
} else {
$('#' + id + ' fieldset div:eq(' + i + ')').find('input').jqmData('cells', $cells);
}
}
});
if (event !== "refresh") {
$menu.appendTo($popup);
}
// bind change event listeners to inputs - TODO: move to a private method?
if ($menu === undefined) {
$switchboard = $('#' + id + ' fieldset');
} else {
$switchboard = $menu;
}
if (event !== "refresh") {
$switchboard.on("change", "input", function (e) {
if (this.checked) {
$(this).jqmData("cells").removeClass("ui-table-cell-hidden").addClass("ui-table-cell-visible");
} else {
$(this).jqmData("cells").removeClass("ui-table-cell-visible").addClass("ui-table-cell-hidden");
}
});
$menuButton
.insertBefore($table)
.buttonMarkup({
theme: o.columnBtnTheme
});
$popup
.insertBefore($table)
.popup();
}
// refresh method
self.update = function () {
$switchboard.find("input").each(function () {
if (this.checked) {
this.checked = $(this).jqmData("cells").eq(0).css("display") === "table-cell";
if (event === "refresh") {
$(this).jqmData("cells").addClass('ui-table-cell-visible');
}
} else {
$(this).jqmData("cells").addClass('ui-table-cell-hidden');
}
$(this).checkboxradio("refresh");
});
};
$.mobile.window.on("throttledresize", self.update);
self.update();
});
})(jQuery);
(function ($, undefined) {
$.mobile.table.prototype.options.mode = "reflow";
$.mobile.table.prototype.options.classes = $.extend(
$.mobile.table.prototype.options.classes,
{
reflowTable: "ui-table-reflow",
cellLabels: "ui-table-cell-label"
}
);
$.mobile.document.delegate(":jqmData(role='table')", "tablecreate refresh", function (e) {
var $table = $(this),
event = e.type,
self = $table.data("mobile-table"),
o = self.options;
// If it's not reflow mode, return here.
if (o.mode !== "reflow") {
return;
}
if (event !== "refresh") {
self.element.addClass(o.classes.reflowTable);
}
// get headers in reverse order so that top-level headers are appended last
var reverseHeaders = $(self.allHeaders.get().reverse());
// create the hide/show toggles
reverseHeaders.each(function (i) {
var $cells = $(this).jqmData("cells"),
colstart = $(this).jqmData("colstart"),
hierarchyClass = $cells.not(this).filter("thead th").length && " ui-table-cell-label-top",
text = $(this).text();
if (text !== "") {
if (hierarchyClass) {
var iteration = parseInt($(this).attr("colspan"), 10),
filter = "";
if (iteration) {
filter = "td:nth-child(" + iteration + "n + " + ( colstart ) + ")";
}
$cells.filter(filter).prepend("<b class='" + o.classes.cellLabels + hierarchyClass + "'>" + text + "</b>");
}
else {
$cells.prepend("<b class='" + o.classes.cellLabels + "'>" + text + "</b>");
}
}
});
});
})(jQuery);
(function ($, window) {
$.mobile.iosorientationfixEnabled = true;
// This fix addresses an iOS bug, so return early if the UA claims it's something else.
var ua = navigator.userAgent;
if (!( /iPhone|iPad|iPod/.test(navigator.platform) && /OS [1-5]_[0-9_]* like Mac OS X/i.test(ua) && ua.indexOf("AppleWebKit") > -1 )) {
$.mobile.iosorientationfixEnabled = false;
return;
}
var zoom = $.mobile.zoom,
evt, x, y, z, aig;
function checkTilt(e) {
evt = e.originalEvent;
aig = evt.accelerationIncludingGravity;
x = Math.abs(aig.x);
y = Math.abs(aig.y);
z = Math.abs(aig.z);
// If portrait orientation and in one of the danger zones
if (!window.orientation && ( x > 7 || ( ( z > 6 && y < 8 || z < 8 && y > 6 ) && x > 5 ) )) {
if (zoom.enabled) {
zoom.disable();
}
} else if (!zoom.enabled) {
zoom.enable();
}
}
$.mobile.document.on("mobileinit", function () {
if ($.mobile.iosorientationfixEnabled) {
$.mobile.window
.bind("orientationchange.iosorientationfix", zoom.enable)
.bind("devicemotion.iosorientationfix", checkTilt);
}
});
}(jQuery, this));
(function ($, window, undefined) {
var $html = $("html"),
$head = $("head"),
$window = $.mobile.window;
//remove initial build class (only present on first pageshow)
function hideRenderingClass() {
$html.removeClass("ui-mobile-rendering");
}
// trigger mobileinit event - useful hook for configuring $.mobile settings before they're used
$(window.document).trigger("mobileinit");
// support conditions
// if device support condition(s) aren't met, leave things as they are -> a basic, usable experience,
// otherwise, proceed with the enhancements
if (!$.mobile.gradeA()) {
return;
}
// override ajaxEnabled on platforms that have known conflicts with hash history updates
// or generally work better browsing in regular http for full page refreshes (BB5, Opera Mini)
if ($.mobile.ajaxBlacklist) {
$.mobile.ajaxEnabled = false;
}
// Add mobile, initial load "rendering" classes to docEl
$html.addClass("ui-mobile ui-mobile-rendering");
// This is a fallback. If anything goes wrong (JS errors, etc), or events don't fire,
// this ensures the rendering class is removed after 5 seconds, so content is visible and accessible
setTimeout(hideRenderingClass, 5000);
$.extend($.mobile, {
// find and enhance the pages in the dom and transition to the first page.
initializePage: function () {
// find present pages
var path = $.mobile.path,
$pages = $(":jqmData(role='page'), :jqmData(role='dialog')"),
hash = path.stripHash(path.stripQueryParams(path.parseLocation().hash)),
hashPage = document.getElementById(hash);
// if no pages are found, create one with body's inner html
if (!$pages.length) {
$pages = $("body").wrapInner("<div data-" + $.mobile.ns + "role='page'></div>").children(0);
}
// add dialogs, set data-url attrs
$pages.each(function () {
var $this = $(this);
// unless the data url is already set set it to the pathname
if (!$this.jqmData("url")) {
$this.attr("data-" + $.mobile.ns + "url", $this.attr("id") || location.pathname + location.search);
}
});
// define first page in dom case one backs out to the directory root (not always the first page visited, but defined as fallback)
$.mobile.firstPage = $pages.first();
// define page container
$.mobile.pageContainer = $.mobile.firstPage.parent().addClass("ui-mobile-viewport");
// initialize navigation events now, after mobileinit has occurred and the page container
// has been created but before the rest of the library is alerted to that fact
$.mobile.navreadyDeferred.resolve();
// alert listeners that the pagecontainer has been determined for binding
// to events triggered on it
$window.trigger("pagecontainercreate");
// cue page loading message
$.mobile.showPageLoadingMsg();
//remove initial build class (only present on first pageshow)
hideRenderingClass();
// if hashchange listening is disabled, there's no hash deeplink,
// the hash is not valid (contains more than one # or does not start with #)
// or there is no page with that hash, change to the first page in the DOM
// Remember, however, that the hash can also be a path!
if (!( $.mobile.hashListeningEnabled &&
$.mobile.path.isHashValid(location.hash) &&
( $(hashPage).is(':jqmData(role="page")') ||
$.mobile.path.isPath(hash) ||
hash === $.mobile.dialogHashKey ) )) {
// Store the initial destination
if ($.mobile.path.isHashValid(location.hash)) {
$.mobile.urlHistory.initialDst = hash.replace("#", "");
}
// make sure to set initial popstate state if it exists
// so that navigation back to the initial page works properly
if ($.event.special.navigate.isPushStateEnabled()) {
$.mobile.navigate.navigator.squash(path.parseLocation().href);
}
$.mobile.changePage($.mobile.firstPage, {
transition: "none",
reverse: true,
changeHash: false,
fromHashChange: true
});
} else {
// trigger hashchange or navigate to squash and record the correct
// history entry for an initial hash path
if (!$.event.special.navigate.isPushStateEnabled()) {
$window.trigger("hashchange", [true]);
} else {
// TODO figure out how to simplify this interaction with the initial history entry
// at the bottom js/navigate/navigate.js
$.mobile.navigate.history.stack = [];
$.mobile.navigate($.mobile.path.isPath(location.hash) ? location.hash : location.href);
}
}
}
});
// check which scrollTop value should be used by scrolling to 1 immediately at domready
// then check what the scroll top is. Android will report 0... others 1
// note that this initial scroll won't hide the address bar. It's just for the check.
$(function () {
window.scrollTo(0, 1);
// if defaultHomeScroll hasn't been set yet, see if scrollTop is 1
// it should be 1 in most browsers, but android treats 1 as 0 (for hiding addr bar)
// so if it's 1, use 0 from now on
$.mobile.defaultHomeScroll = ( !$.support.scrollTop || $.mobile.window.scrollTop() === 1 ) ? 0 : 1;
//dom-ready inits
if ($.mobile.autoInitializePage) {
$.mobile.initializePage();
}
// window load event
// hide iOS browser chrome on load
$window.load($.mobile.silentScroll);
if (!$.support.cssPointerEvents) {
// IE and Opera don't support CSS pointer-events: none that we use to disable link-based buttons
// by adding the 'ui-disabled' class to them. Using a JavaScript workaround for those browser.
// https://github.com/jquery/jquery-mobile/issues/3558
$.mobile.document.delegate(".ui-disabled", "vclick",
function (e) {
e.preventDefault();
e.stopImmediatePropagation();
}
);
}
});
}(jQuery, this));
}));
| sohailalam2/Generic-Skeleton-Website | CLIENT/libraries/jquery/jquery.mobile.js | JavaScript | apache-2.0 | 484,125 |
/**
* Tiny, modular implementation of the CommonJS
* Modules/AsynchronousDefinition as described in
* http://wiki.commonjs.org/wiki/Modules/AsynchronousDefinition
*
* This extension provides the absolute minimum support necessary to use
* jQuery with tAMD.
*
* Copyright 2012-2013 Jive Software
*
* 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.
*/
/*global define */
define['amd']['jQuery'] = true;
| jivesoftware/tAMD | src/jquery-minimal.js | JavaScript | apache-2.0 | 918 |
// Generated by CoffeeScript 1.3.3
(function() {
var KiiRequest, KiiUtilities, root, _Kii, _KiiSocialConnect,
__bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
_this = this;
root = typeof exports !== "undefined" && exports !== null ? exports : this;
root.KiiSocialNetworkName = {
FACEBOOK: 1
};
root.KiiSite = {
US: "https://api.kii.com/api",
JP: "https://api-jp.kii.com/api"
};
/**
@class The main SDK class
@exports root.Kii as Kii
This class must be initialized before any Kii SDK functions are performed. This class also allows the application to make some high-level user calls and access some application-wide data at any time using static methods.
*/
root.Kii = (function() {
var _instance;
function Kii() {}
_instance = null;
/**
Kii SDK Build Number
@returns {String} current build number of the SDK
*/
Kii.getBuildNumber = function() {
return "1";
};
/**
Kii SDK Version Number
@returns {String} current version number of the SDK
*/
Kii.getSDKVersion = function() {
return "1.0";
};
Kii.setCurrentUser = function(user) {
return _instance._currentUser = jQuery.extend(true, {}, user);
};
Kii.getBaseURL = function() {
return _instance._baseURL;
};
/**
Retrieve the current app ID
@returns {String} The current app ID
*/
Kii.getAppID = function() {
return _instance._appID;
};
/**
Retrieve the current app key
@returns {String} The current app key
*/
Kii.getAppKey = function() {
return _instance._appKey;
};
Kii.isLogging = function() {
return _instance._logging;
};
Kii.setLogging = function(logging) {
Kii.logger("Setting logging: " + logging);
return _instance._logging = logging;
};
/** Initialize the Kii SDK with a specific URL
Should be the first Kii SDK action your application makes
@param String appID The application ID found in your Kii developer console
@param String appKey The application key found in your Kii developer console
@param KiiSite site Can be one of the constants KiiSite.US or KiiSite.JP, depending on your location
@example
Kii.initializeWithSite("my-app-id", "my-app-key", KiiSite.JP);
*/
Kii.initializeWithSite = function(appID, appKey, site) {
if (_instance == null) {
_instance = new _Kii(appID, appKey, site);
}
return Kii.logger("Initialized " + appID + ", " + appKey + ", " + site);
};
/** Initialize the Kii SDK
Should be the first Kii SDK action your application makes
@param String appID The application ID found in your Kii developer console
@param String appKey The application key found in your Kii developer console
@example
Kii.initialize("my-app-id", "my-app-key");
*/
Kii.initialize = function(appID, appKey) {
return Kii.initializeWithSite(appID, appKey, KiiSite.US);
};
Kii.error = function(message) {
return console.log("KiiSDK Error => " + message);
};
Kii.logger = function(message) {
if (_instance._logging) {
return console.log(message);
}
};
/**
Creates a reference to a bucket for this user
<br><br>The bucket will be created/accessed within this app's scope
@param String bucketName The name of the bucket the app should create/access
@returns {KiiBucket} A working KiiBucket object
@example
var bucket = Kii.bucketWithName("myBucket");
*/
Kii.bucketWithName = function(bucketName) {
return new KiiBucket.bucketWithName(bucketName, null);
};
/**
Creates a reference to a group with the given name
@param {String} groupName An application-specific group name
@returns {KiiGroup} A new KiiGroup reference
@example
var group = new Kii.groupWithName("myGroup");
*/
Kii.groupWithName = function(groupName) {
return new Kii.groupWithNameAndMembers(groupName, null);
};
/**
Creates a reference to a group with the given name and a list of default members
@param {String} groupName An application-specific group name
@param {Array} members An array of KiiUser objects to add to the group
@returns {KiiGroup} A new KiiGroup reference
@example
var group = new KiiGroup.groupWithName("myGroup", members);
*/
Kii.groupWithNameAndMembers = function(groupName, members) {
return new KiiGroup.groupWithNameAndMembers(groupName, members);
};
Kii.logOut = function() {
return _instance._currentUser = null;
};
Kii.loggedIn = function() {
return _instance._currentUser != null;
};
Kii.getCurrentUser = function() {
if (_instance._currentUser != null) {
return jQuery.extend(true, {}, _instance._currentUser);
} else {
return null;
}
};
return Kii;
})();
_Kii = (function() {
_Kii.prototype._logging = false;
_Kii.prototype._baseURL = null;
_Kii.prototype._currentUser = null;
function _Kii(appID, appKey, site) {
if (site === KiiSite.JP) {
site = KiiSite.JP;
} else if (site === KiiSite.DEV) {
site = KiiSite.DEV;
} else {
site = KiiSite.US;
}
this._appKey = appKey;
this._appID = appID;
this._baseURL = site;
}
return _Kii;
})();
/**
@class Represents a KiiACL object
@exports root.KiiACL as KiiACL
*/
root.KiiACL = (function() {
var _entries, _parent, _thisACL;
_thisACL = null;
_entries = null;
_parent = null;
function KiiACL() {
this.save = __bind(this.save, this);
this._saveWithIndex = __bind(this._saveWithIndex, this);
this._saveSingle = __bind(this._saveSingle, this);
this.removeACLEntry = __bind(this.removeACLEntry, this);
this.putACLEntry = __bind(this.putACLEntry, this);
this.listACLEntries = __bind(this.listACLEntries, this);
this.aclPath = __bind(this.aclPath, this);
this._setParent = __bind(this._setParent, this);
this._entries = [];
}
KiiACL.prototype._setParent = function(_parent) {
this._parent = _parent;
};
KiiACL.prototype.aclPath = function() {
var bucket, bucketName, className, group, object, objectId, path, user;
className = KiiUtilities.getObjectClass(this._parent);
if (className === "KiiObject") {
object = this._parent;
if (object.getBucket().getUser() != null) {
user = object.getBucket().getUser();
} else if (object.getBucket().getGroup() != null) {
group = object.getBucket().getGroup();
}
bucketName = object.getBucket().getBucketName();
objectId = object.getUUID();
} else if (className === "KiiBucket") {
bucket = this._parent;
if (bucket.getUser() != null) {
user = bucket.getUser();
} else if (bucket.getGroup() != null) {
group = bucket.getGroup();
}
bucketName = bucket.getBucketName();
} else {
Kii.error("Invalid ACL parent. Must belong to a KiiObject");
}
path = "/";
if (group != null) {
path += "groups/" + (group.getUUID()) + "/";
} else if (user != null) {
path += "users/" + (user.getUUID()) + "/";
}
if (objectId != null) {
path += "buckets/" + bucketName + "/objects/" + objectId + "/acl";
} else {
path += "buckets/" + bucketName + "/acl";
}
return path;
};
/** Get the list of active ACLs associated with this object from the server
@param {Object} callbacks An object with callback methods defined
@param {Method} callbacks.success The callback method to call on a successful list request
@param {Method} callbacks.failure The callback method to call on a failed list request
@example
var acl = . . .; // a KiiACL object
acl.listACLEntries({
success: function(theACL, theEntries) {
// do something
},
failure: function(theACL, anErrorString) {
// do something with the error response
}
});
*/
KiiACL.prototype.listACLEntries = function(callbacks) {
var listCallbacks, request,
_this = this;
_thisACL = this;
Kii.logger("Listing ACL entries");
request = new KiiRequest(this.aclPath(), true);
listCallbacks = {
success: function(data, statusCode) {
var action, entity, key, results, subject, value, _i, _len;
if (statusCode < 300 && statusCode >= 200) {
results = [];
for (key in data) {
value = data[key];
if (key === "WRITE_EXISTING_OBJECT") {
action = KiiACLAction.KiiACLObjectActionWrite;
} else if (key === "READ_EXISTING_OBJECT") {
action = KiiACLAction.KiiACLObjectActionRead;
} else if (key === "QUERY_OBJECTS_IN_BUCKET") {
action = KiiACLAction.KiiACLBucketActionQueryObjects;
} else if (key === "CREATE_OBJECTS_IN_BUCKET") {
action = KiiACLAction.KiiACLBucketActionCreateObjects;
} else if (key === "DROP_BUCKET_WITH_ALL_CONTENT") {
action = KiiACLAction.KiiACLBucketActionDropBucket;
}
for (_i = 0, _len = value.length; _i < _len; _i++) {
entity = value[_i];
if (entity.groupID != null) {
subject = KiiGroup.groupWithID(entity.groupID);
} else if (entity.userID != null) {
subject = KiiUser.userWithID(entity.userID);
}
results.push(KiiACLEntry.entryWithSubject(subject, action));
}
}
return callbacks.success(_thisACL, results);
} else {
return callbacks.failure(_thisACL, "Unable to retrieve ACL list");
}
},
failure: function(error, statusCode) {
return callbacks.failure(_thisACL, error);
}
};
return request.execute(listCallbacks, false);
};
/** Add a KiiACLEntry to the local object, if not already present. This does not explicitly grant any permissions, which should be done through the KiiACLEntry itself. This method simply adds the entry to the local ACL object so it can be saved to the server.
@param {KiiACLEntry} entry The KiiACLEntry to add
@example
var aclEntry = . . .; // a KiiACLEntry object
var acl = . . .; // a KiiACL object
acl.putACLEntry(aclEntry);
*/
KiiACL.prototype.putACLEntry = function(entry) {
if (($.inArray(entry, this._entries)) === -1) {
return this._entries.push(entry);
}
};
/** Remove a KiiACLEntry to the local object. This does not explicitly revoke any permissions, which should be done through the KiiACLEntry itself. This method simply removes the entry from the local ACL object and will not be saved to the server.
@param {KiiACLEntry} entry The KiiACLEntry to remove
@example
var aclEntry = . . .; // a KiiACLEntry object
var acl = . . .; // a KiiACL object
acl.removeACLEntry(aclEntry);
*/
KiiACL.prototype.removeACLEntry = function(entry) {
var ndx;
ndx = $.inArray(entry, this._entries);
if (ndx > -1) {
return KiiUtilities.arrayRemove(this._entries, ndx, ndx);
}
};
KiiACL.prototype._saveSingle = function(aclEntry, callbacks) {
var path, request;
path = "" + (this.aclPath()) + "/" + (aclEntry.getActionString()) + "/" + (aclEntry.getEntityString());
Kii.logger("Saving single @path: " + path);
request = new KiiRequest(path, true);
request.setMethod(aclEntry.getGrant() === true ? "PUT" : "DELETE");
return request.execute(callbacks, true);
};
KiiACL.prototype._saveWithIndex = function(callbacks, index) {
var entry,
_this = this;
_thisACL = this;
entry = this._entries[index];
Kii.logger("" + entry);
if (entry != null) {
return this._saveSingle(entry, {
success: function() {
Kii.logger("Did succeed");
return _thisACL._saveWithIndex(callbacks, index + 1);
},
failure: function() {
Kii.logger("Did fail");
return callbacks.failure();
}
});
} else {
return callbacks.success(this);
}
};
/** Save the list of ACLEntry objects associated with this ACL object to the server
@param {Object} callbacks An object with callback methods defined
@param {Method} callbacks.success The callback method to call on a successful save request
@param {Method} callbacks.failure The callback method to call on a failed save request
@example
var obj = . . .; // a KiiObject
obj.save({
success: function(theSavedACL) {
// do something with the saved acl
},
failure: function(theACL, anErrorString) {
// do something with the error response
}
});
*/
KiiACL.prototype.save = function(callbacks) {
Kii.logger("SAving acl");
return this._saveWithIndex(callbacks, 0);
};
KiiACL.aclWithParent = function(parent) {
var acl;
acl = new KiiACL();
acl._setParent(parent);
return acl;
};
return KiiACL;
}).call(this);
root.KiiACLAction = {
KiiACLBucketActionCreateObjects: 0,
KiiACLBucketActionQueryObjects: 1,
KiiACLBucketActionDropBucket: 2,
KiiACLObjectActionRead: 3,
KiiACLObjectActionWrite: 4
};
/**
@class Represents a KiiACLEntry object
@exports root.KiiACLEntry as KiiACLEntry
*/
root.KiiACLEntry = (function() {
var _action, _grant, _subject;
_action = null;
_subject = null;
_grant = null;
function KiiACLEntry() {
this.getEntityString = __bind(this.getEntityString, this);
this.getActionString = __bind(this.getActionString, this);
this.getGrant = __bind(this.getGrant, this);
this.setGrant = __bind(this.setGrant, this);
this.getSubject = __bind(this.getSubject, this);
this.setSubject = __bind(this.setSubject, this);
this.getAction = __bind(this.getAction, this);
this.setAction = __bind(this.setAction, this);
this._action = -1;
this._grant = true;
}
/** The action that is being permitted/restricted. Possible values:
<br><br>
KiiACLAction.KiiACLBucketActionCreateObjects,<br>
KiiACLAction.KiiACLBucketActionQueryObjects, <br>
KiiACLAction.KiiACLBucketActionDropBucket,<br>
KiiACLAction.KiiACLObjectActionRead,<br>
KiiACLAction.KiiACLObjectActionWrite
@param {KiiACLAction} value The action being permitted/restricted
@throws {InvalidACLAction} If the value is not one of the permitted values
*/
KiiACLEntry.prototype.setAction = function(value) {
if (value >= KiiACLAction.KiiACLBucketActionCreateObjects && value <= KiiACLAction.KiiACLObjectActionWrite) {
return this._action = value;
} else {
throw new InvalidACLAction;
}
};
/** Get the action that is being permitted/restricted in this entry
@returns {KiiACLAction}
*/
KiiACLEntry.prototype.getAction = function() {
return this._action;
};
/** The KiiUser or KiiGroup entity that is being permitted/restricted
@param {KiiUser|KiiGroup} value The entity being permitted/restricted
@throws {InvalidACLSubject} If the value is not one of the permitted values
*/
KiiACLEntry.prototype.setSubject = function(value) {
var type;
type = KiiUtilities.getObjectClass(value);
if (type === "KiiGroup" || type === "KiiUser" || type === "KiiAnyAuthenticatedUser" || type === "KiiAnonymousUser") {
return this._subject = value;
} else {
throw new InvalidACLSubject;
}
};
/** Get the subject that is being permitted/restricted in this entry
@returns {KiiUser|KiiGroup}
*/
KiiACLEntry.prototype.getSubject = function() {
return this._subject;
};
/** Set whether or not the action is being permitted to the subject
@param {Boolean} value true if the action is permitted, false otherwise
@throws {InvalidACLGrant} If the value is not a boolean type
*/
KiiACLEntry.prototype.setGrant = function(value) {
if (value === true || value === false) {
return this._grant = value;
} else {
throw new InvalidACLGrant;
}
};
/** Get whether or not the action is being permitted to the subject
@returns {Boolean}
*/
KiiACLEntry.prototype.getGrant = function() {
return this._grant;
};
/** Create a KiiACLEntry object with a subject and action
The entry will not be applied on the server until the KiiACL object is explicitly saved. This method simply returns a working KiiACLEntry with a specified subject and action.
@param {KiiGroup|KiiUser|KiiAnyAuthenticatedUser|KiiAnonymousUser} subject A KiiGroup or KiiUser object to which the action/grant is being applied
@param {KiiACLAction} action One of the specified KiiACLAction values the permissions is being applied to
@return A KiiACLEntry object with the specified attributes
*/
KiiACLEntry.entryWithSubject = function(subject, action) {
var entry;
Kii.logger("EWS: " + subject + ", " + action);
entry = new KiiACLEntry();
entry.setSubject(subject);
entry.setAction(action);
return entry;
};
KiiACLEntry.prototype.getActionString = function() {
var retString;
Kii.logger("Action: " + this.action);
switch (this._action) {
case KiiACLAction.KiiACLBucketActionCreateObjects:
retString = "CREATE_OBJECTS_IN_BUCKET";
break;
case KiiACLAction.KiiACLBucketActionQueryObjects:
retString = "QUERY_OBJECTS_IN_BUCKET";
break;
case KiiACLAction.KiiACLBucketActionDropBucket:
retString = "DROP_BUCKET_WITH_ALL_CONTENT";
break;
case KiiACLAction.KiiACLObjectActionRead:
retString = "READ_EXISTING_OBJECT";
break;
case KiiACLAction.KiiACLObjectActionWrite:
retString = "WRITE_EXISTING_OBJECT";
break;
default:
return retString;
}
return retString;
};
KiiACLEntry.prototype.getEntityString = function() {
var entityId, subjectType, type;
subjectType = KiiUtilities.getObjectClass(this._subject);
if (subjectType === "KiiGroup") {
entityId = this._subject.getUUID();
type = "GroupID";
} else if (subjectType === "KiiUser") {
entityId = this._subject.getUUID();
type = "UserID";
} else if (subjectType === "KiiAnyAuthenticatedUser") {
type = "UserID";
entityId = "ANY_AUTHENTICATED_USER";
} else if (subjectType === "KiiAnonymousUser") {
type = "UserID";
entityId = "ANONYMOUS_USER";
}
return "" + type + ":" + entityId;
};
return KiiACLEntry;
}).call(this);
/**
@class Represents a KiiBucket object
@exports root.KiiBucket as KiiBucket
*/
root.KiiBucket = (function() {
var _bucketName, _group, _thisBucket, _user;
function KiiBucket() {
this.objectWithJSON = __bind(this.objectWithJSON, this);
this._generatePath = __bind(this._generatePath, this);
this["delete"] = __bind(this["delete"], this);
this.executeQuery = __bind(this.executeQuery, this);
this.acl = __bind(this.acl, this);
this.createObjectWithType = __bind(this.createObjectWithType, this);
this.createObject = __bind(this.createObject, this);
this._setBucketName = __bind(this._setBucketName, this);
this.getBucketName = __bind(this.getBucketName, this);
this._setGroup = __bind(this._setGroup, this);
this.getGroup = __bind(this.getGroup, this);
this._setUser = __bind(this._setUser, this);
this.getUser = __bind(this.getUser, this);
}
KiiBucket.prototype._className = "KiiBucket";
_thisBucket = null;
_bucketName = null;
_user = null;
_group = null;
KiiBucket.prototype.getUser = function() {
return this._user;
};
KiiBucket.prototype._setUser = function(_user) {
this._user = _user;
};
KiiBucket.prototype.getGroup = function() {
return this._group;
};
KiiBucket.prototype._setGroup = function(_group) {
this._group = _group;
};
/** The name of this bucket
@returns {String}
*/
KiiBucket.prototype.getBucketName = function() {
return this._bucketName;
};
KiiBucket.prototype._setBucketName = function(_bucketName) {
this._bucketName = _bucketName;
};
/** Create a KiiObject within the current bucket
<br><br>The object will not be created on the server until the KiiObject is explicitly saved. This method simply returns an empty working KiiObject.
@returns {KiiObject} An empty KiiObject with no specific type
@example
var bucket = . . .; // a KiiBucket
var object = bucket.createObject();
*/
KiiBucket.prototype.createObject = function() {
return KiiObject.objectWithBucket(this, null);
};
/** Create a KiiObject within the current bucket, with type
<br><br>The object will not be created on the server until the KiiObject is explicitly saved. This method simply returns an empty working KiiObject with a specified type. The type allows for better indexing and improved query results. It is recommended to use this method - but for lazy creation, the createObject method is also available.
@param String type A string representing the desired object type
@returns An empty KiiObject with specified type
@example
var bucket = . . .; // a KiiBucket
var object = bucket.createObjectWithType("scores");
*/
KiiBucket.prototype.createObjectWithType = function(type) {
return KiiObject.objectWithBucket(this, type);
};
/** Get the ACL handle for this bucket
<br><br>Any KiiACLEntry objects added or revoked from this ACL object will be appended to/removed from the server on ACL save.
@returns {KiiACL} A KiiACL object associated with this KiiObject
@example
var bucket = . . .; // a KiiBucket
var acl = bucket.acl();
*/
KiiBucket.prototype.acl = function() {
return KiiACL.aclWithParent(this);
};
/** Perform a query on the given bucket
<br><br>The query will be executed against the server, returning a result set.
@param KiiQuery query An object with callback methods defined
@param Object callbacks An object with callback methods defined
@param {Method} callbacks.success The callback method to call on a successful query request
@param {Method} callbacks.failure The callback method to call on a failed query request
@example
var bucket = . . .; // a KiiBucket
var queryObject = . . .; // a KiiQuery
// define the callbacks (stored in a variable for reusability)
var queryCallbacks = {
success: function(queryPerformed, resultSet, nextQuery) {
// do something with the results
for(var i=0; i<resultSet.length; i++) {
// do something with the object
// resultSet[i]; // could be KiiObject, KiiGroup, KiiUser, etc
}
// if there are more results to be retrieved
if(nextQuery != null) {
// get them and repeat recursively until no results remain
bucket.executeQuery(nextQuery, queryCallbacks);
}
},
failure: function(queryPerformed, anErrorString) {
// do something with the error response
}
};
bucket.executeQuery(queryObject, queryCallbacks);
*/
KiiBucket.prototype.executeQuery = function(query, callbacks) {
var clauseData, data, executeCallbacks, path, request,
_this = this;
_thisBucket = this;
path = this._generatePath() + "/query";
data = {};
if (query != null) {
clauseData = query._dictValue();
data.bestEffortLimit = query.getLimit();
if (query.getPaginationKey() != null) {
data.paginationKey = query.getPaginationKey();
}
} else {
clauseData = {
"clause": KiiQuery._emptyDictValue()
};
}
request = new KiiRequest(path, true);
request.setMethod("POST");
request.setContentType("application/vnd.kii.QueryRequest+json");
data.bucketQuery = clauseData;
request.setData(data);
executeCallbacks = {
success: function(data, statusCode) {
var nextQuery, result, resultSet, _i, _len, _ref;
if (statusCode < 300 && statusCode >= 200) {
resultSet = [];
_ref = data.results;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
result = _ref[_i];
resultSet.push(_thisBucket.objectWithJSON(result));
}
if (data.nextPaginationKey != null) {
nextQuery = jQuery.extend(true, {}, query);
nextQuery.setPaginationKey(data.nextPaginationKey);
}
if (callbacks != null) {
return callbacks.success(query, resultSet, nextQuery);
}
} else if (callbacks != null) {
return callbacks.failure(query, "Unable to parse response");
}
},
failure: function(error, statusCode) {
if (callbacks != null) {
return callbacks.failure(_thisBucket, error);
}
}
};
return request.execute(executeCallbacks, false);
};
/** Delete the given bucket from the server
@param Object callbacks An object with callback methods defined
@param {Method} callbacks.success The callback method to call on a successful query request
@param {Method} callbacks.failure The callback method to call on a failed query request
@example
var bucket = . . .; // a KiiBucket
bucket.delete({
success: function(deletedBucket) {
// do something with the result
},
failure: function(bucketToDelete, anErrorString) {
// do something with the error response
}
});
*/
KiiBucket.prototype["delete"] = function(callbacks) {
var executeCallbacks, request,
_this = this;
_thisBucket = this;
request = new KiiRequest(this._generatePath(), true);
request.setMethod("DELETE");
executeCallbacks = {
success: function(data, statusCode) {
if (callbacks != null) {
return callbacks.success(_thisBucket);
}
},
failure: function(error, statusCode) {
if (callbacks != null) {
return callbacks.failure(_thisBucket, error);
}
}
};
return request.execute(executeCallbacks, true);
};
KiiBucket.bucketWithName = function(bucketName, parent) {
var bucket, className;
bucket = new KiiBucket;
bucket._setBucketName(bucketName);
if (parent != null) {
className = KiiUtilities.getObjectClass(parent);
if (className === "KiiGroup") {
bucket._setGroup(parent);
} else if (className === "KiiUser") {
bucket._setUser(parent);
}
}
return bucket;
};
KiiBucket.prototype._generatePath = function() {
var path;
if (this._user != null) {
path = "/users/" + (this._user.getUUID()) + "/buckets/" + this._bucketName;
} else if (this._group != null) {
path = "/groups/" + (this._group.getUUID()) + "/buckets/" + this._bucketName;
} else {
path = "/buckets/" + this._bucketName;
}
return path;
};
KiiBucket.prototype.objectWithJSON = function(json) {
var newobject;
newobject = this.createObject();
newobject._updateWithJSON(json);
return newobject;
};
return KiiBucket;
}).call(this);
/**
@class Represents a KiiGroup object
@exports root.KiiGroup as KiiGroup
*/
root.KiiGroup = (function() {
var _addMembers, _groupName, _owner, _removeMembers, _thisGroup;
_thisGroup = null;
_groupName = null;
_owner = null;
_addMembers = null;
_removeMembers = null;
KiiGroup.prototype._getAddMembers = function() {
return this._addMembers;
};
KiiGroup.prototype._getRemoveMembers = function() {
return this._removeMembers;
};
function KiiGroup() {
this.getOwner = __bind(this.getOwner, this);
this["delete"] = __bind(this["delete"], this);
this.refresh = __bind(this.refresh, this);
this.save = __bind(this.save, this);
this.changeGroupName = __bind(this.changeGroupName, this);
this._saveMembers = __bind(this._saveMembers, this);
this.getMemberList = __bind(this.getMemberList, this);
this._removeMember = __bind(this._removeMember, this);
this._addMember = __bind(this._addMember, this);
this.removeUser = __bind(this.removeUser, this);
this.addUser = __bind(this.addUser, this);
this.bucketWithName = __bind(this.bucketWithName, this);
this.objectURI = __bind(this.objectURI, this);
this._setOwner = __bind(this._setOwner, this);
this.getOwner = __bind(this.getOwner, this);
this._setName = __bind(this._setName, this);
this.getName = __bind(this.getName, this);
this._setUUID = __bind(this._setUUID, this);
this.getUUID = __bind(this.getUUID, this);
this._setAddMembers = __bind(this._setAddMembers, this);
this._getRemoveMembers = __bind(this._getRemoveMembers, this);
this._getAddMembers = __bind(this._getAddMembers, this);
this._addMembers = [];
this._removeMembers = [];
}
KiiGroup.prototype._setAddMembers = function(members) {
var member, _i, _len, _results;
if (members != null) {
_results = [];
for (_i = 0, _len = members.length; _i < _len; _i++) {
member = members[_i];
_results.push(this._addMembers.push(member));
}
return _results;
}
};
/** Get the UUID of the given group, assigned by the server
@returns {String}
*/
KiiGroup.prototype.getUUID = function() {
return this._uuid;
};
KiiGroup.prototype._setUUID = function(_uuid) {
this._uuid = _uuid;
};
/** The name of this group
@returns {String}
*/
KiiGroup.prototype.getName = function() {
return this._groupName;
};
KiiGroup.prototype._setName = function(_groupName) {
this._groupName = _groupName;
};
/** Get the creator of this group
@returns {KiiUser}
*/
KiiGroup.prototype.getOwner = function() {
return this._owner;
};
KiiGroup.prototype._setOwner = function(_owner) {
this._owner = _owner;
};
/** Get a specifically formatted string referencing the group
<br><br>The group must exist in the cloud (have a valid UUID).
@returns {String} A URI string based on the current group. null if a URI couldn't be generated.
@example
var group = . . .; // a KiiGroup
var uri = group.objectURI();
*/
KiiGroup.prototype.objectURI = function() {
if (this._uuid != null) {
return "kiicloud://groups/" + this._uuid;
} else {
return null;
}
};
/** Creates a reference to a bucket for this group
<br><br>The bucket will be created/accessed within this group's scope
@param {String} bucketName The name of the bucket the user should create/access
@returns {KiiBucket} A working KiiBucket object
@example
var group = . . .; // a KiiGroup
var bucket = group.bucketWithName("myBucket");
*/
KiiGroup.prototype.bucketWithName = function(bucketName) {
return new KiiBucket.bucketWithName(bucketName, this);
};
/** Adds a user to the given group
<br><br>This method will NOT access the server immediately. You must call save to add the user on the server. This allows multiple users to be added/removed before calling save.
@param {KiiUser} member The user to be added to the group
@example
var user = . . .; // a KiiUser
var group = . . .; // a KiiGroup
group.addUser(user);
group.save(callbacks);
*/
KiiGroup.prototype.addUser = function(member) {
var ndx;
if ($.inArray(member, this._addMembers === -1)) {
this._addMembers.push(member);
}
ndx = $.inArray(member, this._removeMembers);
if (ndx >= 0) {
return KiiUtilities.arrayRemove(this._removeMembers, ndx, ndx);
}
};
/** Removes a user from the given group
<br><br>This method will NOT access the server immediately. You must call save to remove the user on the server. This allows multiple users to be added/removed before calling save.
@param {KiiUser} member The user to be added to the group
@example
var user = . . .; // a KiiUser
var group = . . .; // a KiiGroup
group.removeUser(user);
group.save(callbacks);
*/
KiiGroup.prototype.removeUser = function(member) {
var ndx;
if ($.inArray(member, this._removeMembers === -1)) {
this._removeMembers.push(member);
}
ndx = $.inArray(member, this._addMembers);
if (ndx >= 0) {
return KiiUtilities.arrayRemove(this._addMembers, ndx, ndx);
}
};
KiiGroup.prototype._addMember = function(member, callback) {
var memberCallbacks, request,
_this = this;
_thisGroup = this;
Kii.logger("Adding member " + (member.getUUID()) + " to group " + this._groupName);
request = new KiiRequest("/groups/" + this._uuid + "/members/" + (member.getUUID()), true);
request.setMethod("PUT");
memberCallbacks = {
success: function(data, statusCode) {
var ndx;
ndx = $.inArray(member, _thisGroup._getAddMembers());
KiiUtilities.arrayRemove(_thisGroup._getAddMembers(), ndx, ndx);
return callback();
},
failure: function(error, statusCode) {
var ndx;
ndx = $.inArray(member, _thisGroup._getAddMembers());
KiiUtilities.arrayRemove(_thisGroup._getAddMembers(), ndx, ndx);
return callback();
}
};
return request.execute(memberCallbacks, true);
};
KiiGroup.prototype._removeMember = function(member, callback) {
var removeCallbacks, request,
_this = this;
_thisGroup = this;
Kii.logger("Removing member " + (member.getUUID()) + " to group " + this._groupName);
request = new KiiRequest("/groups/" + this._uuid + "/members/" + (member.getUUID()), true);
request.setMethod("DELETE");
removeCallbacks = {
success: function(data, statusCode) {
var ndx;
ndx = $.inArray(member, _thisGroup._getRemoveMembers());
KiiUtilities.arrayRemove(_thisGroup._getRemoveMembers(), ndx, ndx);
return callback();
},
failure: function(error, statusCode) {
var ndx;
ndx = $.inArray(member, _thisGroup._getRemoveMembers());
KiiUtilities.arrayRemove(_thisGroup._getRemoveMembers(), ndx, ndx);
return callback();
}
};
return request.execute(removeCallbacks, true);
};
/** Gets a list of all current members of a group
@param {Object} callbacks An object with callback methods defined
@param {Method} callbacks.success The callback method to call on a successful list request
@param {Method} callbacks.failure The callback method to call on a failed list request
@example
var group = . . .; // a KiiGroup
group.getMemberList({
success: function(theGroup, memberList) {
// do something with the result
for(var i=0; i<memberList.length; i++){
var u = memberList[i]; // a KiiUser within the group
}
},
failure: function(theGroup, anErrorString) {
// do something with the error response
}
});
*/
KiiGroup.prototype.getMemberList = function(callbacks) {
var listCallbacks, request,
_this = this;
_thisGroup = this;
Kii.logger("Getting member list for group " + this._groupName);
request = new KiiRequest("/groups/" + this._uuid + "/members", true);
request.setAccept("application/vnd.kii.MembersRetrievalResponse+json");
listCallbacks = {
success: function(data, statusCode) {
var member, memberList, _i, _len, _ref;
if (statusCode < 300 && statusCode >= 200) {
memberList = [];
_ref = data.members;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
member = _ref[_i];
memberList.push(KiiUser.userWithID(member.userID));
}
if (callbacks != null) {
return callbacks.success(_thisGroup, memberList);
}
} else if (callbacks != null) {
return callbacks.failure(_thisGroup, member, "Unable to get member list of group");
}
},
failure: function(error, statusCode) {
if (callbacks != null) {
return callbacks.failure(_thisGroup, error);
}
}
};
return request.execute(listCallbacks, true);
};
KiiGroup.prototype._saveMembers = function(callbacks) {
var member, _i, _j, _len, _len1, _ref, _ref1,
_this = this;
_thisGroup = this;
_ref = this._removeMembers;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
member = _ref[_i];
this._removeMember(member, function() {
return _thisGroup._saveMembers(callbacks);
});
return;
}
_ref1 = this._addMembers;
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
member = _ref1[_j];
this._addMember(member, function() {
return _thisGroup._saveMembers(callbacks);
});
return;
}
return callbacks.success(_thisGroup);
};
/** Updates the group name on the server
@param {String} newName A String of the desired group name
@param {Object} callbacks An object with callback methods defined
@param {Method} callbacks.success The callback method to call on a successful save request
@param {Method} callbacks.failure The callback method to call on a failed save request
@example
var group = . . .; // a KiiGroup
group.changeGroupName("myNewName", {
success: function(theRenamedGroup) {
// do something with the group
},
failure: function(theGroup, anErrorString) {
// do something with the error response
}
});
*/
KiiGroup.prototype.changeGroupName = function(newName, callbacks) {
var request, saveCallbacks,
_this = this;
_thisGroup = this;
Kii.logger("Saving group: " + this.name);
if (this._uuid != null) {
request = new KiiRequest("/groups/" + this._uuid + "/name", true);
request.setContentType("text/plain");
request.setMethod("PUT");
request.setData(newName);
saveCallbacks = {
success: function(data, statusCode) {
if (statusCode < 300 && statusCode >= 200) {
_thisGroup._setName(newName);
if (callbacks != null) {
return callbacks.success(_thisGroup);
}
} else if (callbacks != null) {
return callbacks.failure(_thisGroup, "Unable to change group name - invalid response");
}
},
failure: function(error, statusCode) {
if (callbacks != null) {
return callbacks.failure(_thisGroup, error);
}
}
};
return request.execute(saveCallbacks, true);
} else {
return callbacks.failure(_thisGroup, "Invalid group. Save the group on the server before updating the name.");
}
};
/** Saves the latest group values to the server
<br><br>If the group does not yet exist, it will be created. If the group already exists, the fields that have changed will be updated accordingly.
@param {Object} callbacks An object with callback methods defined
@param {Method} callbacks.success The callback method to call on a successful save request
@param {Method} callbacks.failure The callback method to call on a failed save request
@example
var group = . . .; // a KiiGroup
group.save({
success: function(theSavedGroup) {
// do something with the saved group
},
failure: function(theGroup, anErrorString) {
// do something with the error response
}
});
*/
KiiGroup.prototype.save = function(callbacks) {
var data, request, saveCallbacks,
_this = this;
_thisGroup = this;
Kii.logger("Saving group: " + this.name);
if (!(this._uuid != null)) {
request = new KiiRequest("/groups", true);
request.setContentType("application/vnd.kii.GroupCreationRequest+json");
request.setMethod("POST");
data = {};
if (this._groupName != null) {
data.name = this._groupName;
}
if (Kii.getCurrentUser() != null) {
this._owner = Kii.getCurrentUser();
data.owner = this._owner.getUUID();
}
request.setData(data);
saveCallbacks = {
success: function(data, statusCode) {
if (statusCode < 300 && statusCode >= 200) {
_thisGroup._setUUID(data.groupID);
return _thisGroup._saveMembers(callbacks);
}
},
failure: function(error, statusCode) {
if (callbacks != null) {
return callbacks.failure(_thisGroup, error);
}
}
};
return request.execute(saveCallbacks, false);
} else {
return this._saveMembers(callbacks);
}
};
/** Updates the local group's data with the group data on the server
<br><br>The group must exist on the server. Local data will be overwritten.
@param {Object} callbacks An object with callback methods defined
@param {Method} callbacks.success The callback method to call on a successful refresh request
@param {Method} callbacks.failure The callback method to call on a failed refresh request
@example
var group = . . .; // a KiiGroup
group.refresh({
success: function(theRefreshedGroup) {
// do something with the refreshed group
},
failure: function(theGroup, anErrorString) {
// do something with the error response
}
});
*/
KiiGroup.prototype.refresh = function(callbacks) {
var refreshCallbacks, request,
_this = this;
_thisGroup = this;
Kii.logger("Refreshing group: " + this._groupName);
request = new KiiRequest("/groups/" + this._uuid, true);
request.setAccept("application/vnd.kii.GroupRetrievalResponse+json");
refreshCallbacks = {
success: function(data, statusCode) {
_thisGroup = KiiGroup.groupWithJSON(data);
if (callbacks != null) {
return callbacks.success(_thisGroup);
}
},
failure: function(error, statusCode) {
if (callbacks != null) {
return callbacks.failure(_thisGroup, error);
}
}
};
return request.execute(refreshCallbacks, false);
};
/** Delete the group from the server
@param {Object} callbacks An object with callback methods defined
@param {Method} callbacks.success The callback method to call on a successful delete request
@param {Method} callbacks.failure The callback method to call on a failed delete request
@example
var group = . . .; // a KiiGroup
group.delete({
success: function(theDeletedGroup) {
// do something
},
failure: function(theGroup, anErrorString) {
// do something with the error response
}
});
*/
KiiGroup.prototype["delete"] = function(callbacks) {
var deleteCallbacks, request,
_this = this;
_thisGroup = this;
Kii.logger("Deleting group: " + this._groupName);
request = new KiiRequest("/groups/" + this._uuid, true);
request.setMethod("DELETE");
deleteCallbacks = {
success: function(data, statusCode) {
if (statusCode < 300 && statusCode >= 200 && (callbacks != null)) {
return callbacks.success(_thisGroup);
} else if (callbacks != null) {
return callbacks.failure(_thisGroup, "Unable to parse response");
}
},
failure: function(error, statusCode) {
if (callbacks != null) {
return callbacks.failure(_thisGroup, error);
}
}
};
return request.execute(deleteCallbacks, true);
};
/** Gets the owner of the associated group
@param {Object} callbacks An object with callback methods defined
@param {Method} callbacks.success The callback method to call on a successful add request
@param {Method} callbacks.failure The callback method to call on a failed add request
@example
var group = . . .; // a KiiGroup
group.getOwner({
success: function(theGroup, theOwner) {
// do something
},
failure: function(theGroup, anErrorString) {
// do something with the error response
}
});
*/
KiiGroup.prototype.getOwner = function(member, callbacks) {
var _this = this;
_thisGroup = this;
Kii.logger("Getting owner of group " + this._groupName);
return this.refresh({
success: function(group) {
if (callbacks != null) {
return callbacks.success(group, group.getOwner());
}
},
failure: function(group, error) {
if (callbacks != null) {
return callbacks.failure(group, error);
}
}
});
};
/** Creates a reference to a group with the given name
@param {String} groupName An application-specific group name
@returns {KiiGroup} A new KiiGroup reference
@example
var group = new KiiGroup.groupWithName("myGroup");
*/
KiiGroup.groupWithName = function(groupName) {
return KiiGroup.groupWithNameAndMembers(groupName, null);
};
/** Creates a reference to a group with the given name and a list of default members
@param {String} groupName An application-specific group name
@param {Array} members An array of KiiUser objects to add to the group
@returns {KiiGroup} A new KiiGroup reference
@example
var group = new KiiGroup.groupWithName("myGroup", members);
*/
KiiGroup.groupWithNameAndMembers = function(groupName, members) {
var group;
group = new KiiGroup();
group._setName(groupName);
group._setAddMembers(members);
return group;
};
/** Generate a new KiiGroup based on a given URI
@param {String} uri The URI of the group to be represented
@returns {KiiGroup} A new KiiGroup with its parameters filled in from the URI
@throws {InvalidURIException} If the URI given is invalid
@example
var group = new KiiGroup.groupWithURI("kiicloud://myuri");
*/
KiiGroup.groupWithURI = function(uri) {
var compLength, components, group, newURI;
group = null;
newURI = uri.substr("kiicloud://".length);
components = newURI.split("/");
compLength = components.length;
if (compLength > 0) {
group = new KiiGroup();
group._setUUID(components[compLength - 1]);
} else {
throw new InvalidURIException;
}
return group;
};
KiiGroup.groupWithID = function(id) {
var group;
group = new KiiGroup();
group._setUUID(id);
return group;
};
KiiGroup.groupWithJSON = function(json) {
var group;
group = new KiiGroup();
if (json.groupID != null) {
group._setUUID(json.groupID);
}
if (json.name != null) {
group._setName(json.name);
}
if (json.owner != null) {
group._setOwner(KiiUser.userWithID(json.owner));
}
return group;
};
return KiiGroup;
}).call(this);
/**
@class Represents a KiiObject object
@exports root.KiiObject as KiiObject
*/
root.KiiObject = (function() {
var _bucket, _created, _customInfo, _modified, _objectType, _owner, _thisObject, _uuid;
_thisObject = null;
KiiObject.prototype._alteredFields = [];
_uuid = null;
_created = null;
_modified = null;
_objectType = null;
_customInfo = null;
_bucket = null;
_owner = null;
/** Get the UUID of the given object, assigned by the server
@returns {String}
*/
KiiObject.prototype.getUUID = function() {
return this._uuid;
};
KiiObject.prototype._setUUID = function(_uuid) {
this._uuid = _uuid;
};
/** Get the server's creation date of this object
@returns {String}
*/
KiiObject.prototype.getCreated = function() {
return this._created;
};
KiiObject.prototype._setCreated = function(_created) {
this._created = _created;
};
/** Get the modified date of the given object, assigned by the server
@returns {String}
*/
KiiObject.prototype.getModified = function() {
return this._modified;
};
KiiObject.prototype._setModified = function(_modified) {
this._modified = _modified;
};
/** Get the application-defined type name of the object
@returns {String}
*/
KiiObject.prototype.getObjectType = function() {
return this._objectType;
};
KiiObject.prototype._setObjectType = function(_objectType) {
this._objectType = _objectType;
};
KiiObject.prototype.getBucket = function() {
Kii.logger("GEtting bucket " + this._bucket);
return this._bucket;
};
KiiObject.prototype._setBucket = function(_bucket) {
this._bucket = _bucket;
};
function KiiObject() {
this["delete"] = __bind(this["delete"], this);
this.refresh = __bind(this.refresh, this);
this.save = __bind(this.save, this);
this.saveAllFields = __bind(this.saveAllFields, this);
this._performSave = __bind(this._performSave, this);
this._updateWithJSON = __bind(this._updateWithJSON, this);
this.objectURI = __bind(this.objectURI, this);
this.objectACL = __bind(this.objectACL, this);
this.get = __bind(this.get, this);
this.set = __bind(this.set, this);
this._getPath = __bind(this._getPath, this);
this._setBucket = __bind(this._setBucket, this);
this.getBucket = __bind(this.getBucket, this);
this._setObjectType = __bind(this._setObjectType, this);
this.getObjectType = __bind(this.getObjectType, this);
this._setModified = __bind(this._setModified, this);
this.getModified = __bind(this.getModified, this);
this._setCreated = __bind(this._setCreated, this);
this.getCreated = __bind(this.getCreated, this);
this._setUUID = __bind(this._setUUID, this);
this.getUUID = __bind(this.getUUID, this);
this._customInfo = {};
}
KiiObject.prototype._getPath = function() {
var path;
if (this._bucket.getUser() != null) {
path = "/users/" + (this._bucket.getUser().getUUID()) + "/buckets/" + (this._bucket.getBucketName()) + "/objects/";
} else if (this._bucket.getGroup() != null) {
path = "/groups/" + (this._bucket.getGroup().getUUID()) + "/buckets/" + (this._bucket.getBucketName()) + "/objects/";
} else {
path = "/buckets/" + (this._bucket.getBucketName()) + "/objects/";
}
if (this._uuid != null) {
path += this._uuid;
}
return path;
};
/** Sets a key/value pair to a KiiObject
<br><br>If the key already exists, its value will be written over. If the object is of invalid type, it will return false and a KiiError will be thrown (quietly). Accepted types are any JSON-encodable objects.
@param {String} key The key to set. The key must not be a system key (created, metadata, modified, type, uuid) or begin with an underscore (_)
@param {Object} value The value to be set. Object must be of a JSON-encodable type (Ex: dictionary, array, string, number, etc)
@example
var obj = . . .; // a KiiObject
obj.set("score", 4298);
*/
KiiObject.prototype.set = function(key, value) {
this._customInfo[key] = value;
return this._alteredFields.push(key);
};
/** Gets the value associated with the given key
@param {String} key The key to retrieve
@returns {Object} The object associated with the key. null if none exists
@example
var obj = . . .; // a KiiObject
var score = obj.get("score");
*/
KiiObject.prototype.get = function(key) {
return this._customInfo[key];
};
/** Get the ACL handle for this file
<br><br>Any KiiACLEntry objects added or revoked from this ACL object will be appended to/removed from the server on ACL save.
@returns {KiiACL} A KiiACL object associated with this KiiObject
@example
var obj = . . .; // a KiiObject
var acl = obj.objectACL();
*/
KiiObject.prototype.objectACL = function() {
return KiiACL.aclWithParent(this);
};
/** Get a specifically formatted string referencing the object
<br><br>The object must exist in the cloud (have a valid UUID).
@returns {String} A URI string based on the current object. null if a URI couldn't be generated.
@example
var obj = . . .; // a KiiObject
var uri = obj.objectURI();
*/
KiiObject.prototype.objectURI = function() {
var base, uri;
base = "kiicloud://";
if ((this._bucket != null) && (this._uuid != null)) {
uri = base;
if (this._bucket.getGroup() != null) {
uri += "groups/" + (this._bucket.getGroup().getUUID()) + "/";
} else if (this._bucket.getUser() != null) {
uri += "users/" + (this._bucket.getUser().getUUID()) + "/";
}
uri += "buckets/" + (this._bucket.getBucketName()) + "/objects/" + this._uuid;
}
return uri;
};
KiiObject.prototype._updateWithJSON = function(json) {
var key, val, _results;
_results = [];
for (key in json) {
val = json[key];
if (key === "objectID" || key === "_id" || key === "uuid") {
Kii.logger("Setting uuid: " + val);
_results.push(this._uuid = val);
} else if (key === "createdAt" || key === "_created" || key === "created") {
_results.push(this._created = val);
} else if (key === "modifiedAt" || key === "_modified" || key === "modified") {
_results.push(this._modified = val);
} else if (key === "_owner") {
_results.push(this._owner = KiiUser.userWithID(val));
} else if (key === "_dataType") {
_results.push(this._objectType = val);
} else if (key[0] !== "_") {
_results.push(this._customInfo[key] = val);
} else {
_results.push(void 0);
}
}
return _results;
};
KiiObject.prototype._performSave = function(allFields, callbacks) {
var data, key, path, request, saveCallbacks, _i, _len, _ref,
_this = this;
_thisObject = this;
path = this._getPath();
request = new KiiRequest(path, true);
request.setMethod(this._uuid != null ? "PUT" : "POST");
data = {};
if (allFields) {
data = this._customInfo;
} else {
_ref = this._alteredFields;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
key = _ref[_i];
data[key] = this._customInfo[key];
}
}
request.setData(data);
if (this._objectType != null) {
request.setContentType("application/vnd." + (Kii.getAppID()) + "." + this._objectType + "+json");
}
if ((this._uuid != null) && !allFields) {
request.addHeader("X-HTTP-Method-Override", "PATCH");
}
saveCallbacks = {
success: function(data, statusCode) {
if (statusCode < 300 && statusCode >= 200) {
_thisObject._updateWithJSON(data);
_thisObject._alteredFields = [];
if (callbacks != null) {
return callbacks.success(_thisObject);
}
} else if (callbacks != null) {
return callbacks.failure(_thisObject, "Unable to parse response");
}
},
failure: function(error, statusCode) {
if (callbacks != null) {
return callbacks.failure(_thisObject, error);
}
}
};
return request.execute(saveCallbacks, false);
};
/** Saves the latest object values to the server
<br><br>If the object does not yet exist, it will be created. If the object already exists, all fields will be removed or changed to match the local values.
@param {Object} callbacks An object with callback methods defined
@param {Method} callbacks.success The callback method to call on a successful save request
@param {Method} callbacks.failure The callback method to call on a failed save request
@example
var obj = . . .; // a KiiObject
obj.saveAllFields({
success: function(theSavedObject) {
// do something with the saved object
},
failure: function(theObject, anErrorString) {
// do something with the error response
}
});
*/
KiiObject.prototype.saveAllFields = function(callbacks) {
return this._performSave(true, callbacks);
};
/** Saves the latest object values to the server
<br><br>If the object does not yet exist, it will be created. If the object already exists, the fields that have changed will be updated accordingly.
@param {Object} callbacks An object with callback methods defined
@param {Method} callbacks.success The callback method to call on a successful save request
@param {Method} callbacks.failure The callback method to call on a failed save request
@example
var obj = . . .; // a KiiObject
obj.save({
success: function(theSavedObject) {
// do something with the saved object
},
failure: function(theObject, anErrorString) {
// do something with the error response
}
});
*/
KiiObject.prototype.save = function(callbacks) {
return this._performSave(false, callbacks);
};
/** Updates the local object's data with the user data on the server
<br><br>The object must exist on the server. Local data will be overwritten.
@param {Object} callbacks An object with callback methods defined
@param {Method} callbacks.success The callback method to call on a successful refresh request
@param {Method} callbacks.failure The callback method to call on a failed refresh request
@example
var obj = . . .; // a KiiObject
obj.refresh({
success: function(theRefreshedObject) {
// do something with the refreshed object
},
failure: function(theObject, anErrorString) {
// do something with the error response
}
});
*/
KiiObject.prototype.refresh = function(callbacks) {
var path, refreshCallbacks, request,
_this = this;
_thisObject = this;
path = this._getPath();
request = new KiiRequest(path, true);
refreshCallbacks = {
success: function(data, statusCode) {
if (statusCode < 300 && statusCode >= 200) {
_thisObject._updateWithJSON(data);
if (callbacks != null) {
return callbacks.success(_thisObject);
}
} else if (callbacks != null) {
return callbacks.failure(_thisObject, "Unable to parse response");
}
},
failure: function(error, statusCode) {
if (callbacks != null) {
return callbacks.failure(_thisObject, error);
}
}
};
return request.execute(refreshCallbacks, false);
};
/** Delete the object from the server
@param {Object} callbacks An object with callback methods defined
@param {Method} callbacks.success The callback method to call on a successful delete request
@param {Method} callbacks.failure The callback method to call on a failed delete request
@example
var obj = . . .; // a KiiObject
obj.delete({
success: function(theDeletedObject) {
// do something
},
failure: function(theObject, anErrorString) {
// do something with the error response
}
});
*/
KiiObject.prototype["delete"] = function(callbacks) {
var path, refreshCallbacks, request,
_this = this;
_thisObject = this;
path = this._getPath();
request = new KiiRequest(path, true);
request.setMethod("DELETE");
refreshCallbacks = {
success: function(data, statusCode) {
if (statusCode < 300 && statusCode >= 200 && (callbacks != null)) {
return callbacks.success(_thisObject);
} else if (callbacks != null) {
return callbacks.failure(_thisObject, "Unable to parse response");
}
},
failure: function(error, statusCode) {
if (callbacks != null) {
return callbacks.failure(_thisObject, error);
}
}
};
return request.execute(refreshCallbacks, true);
};
KiiObject.objectWithBucket = function(bucket, type) {
var obj;
Kii.logger("Creating object w type: " + type);
obj = new KiiObject;
obj._setBucket(bucket);
obj._setObjectType(type);
Kii.logger(obj);
return obj;
};
/** Generate a new KiiObject based on a given URI
@param {String} uri The URI of the object to be represented
@returns {KiiObject} A new KiiObject with its parameters filled in from the URI
@throws {InvalidURIException} If the URI is not in the proper format
@example
var group = new KiiObject.objectWithURI("kiicloud://myuri");
*/
KiiObject.objectWithURI = function(uri) {
var bucket, bucketIndex, bucketName, compLength, components, group, newURI, obj, subject, user;
newURI = uri.substr("kiicloud://".length);
components = newURI.split("/");
compLength = components.length;
Kii.logger(components);
if (compLength >= 4) {
bucketIndex = compLength === 4 ? 1 : 3;
bucketName = components[bucketIndex];
if (components[0] === "groups") {
group = new KiiGroup.groupWithID(components[1]);
} else if (components[0] === "users") {
user = new KiiUser.userWithID(components[1]);
}
subject = null;
if (group != null) {
subject = group;
} else if (user != null) {
subject = user;
}
bucket = new KiiBucket.bucketWithName(bucketName, subject);
Kii.logger(bucket);
obj = bucket.createObject();
obj._setUUID(components[compLength - 1]);
Kii.logger(obj);
} else {
throw new InvalidURIException;
}
return obj;
};
return KiiObject;
}).call(this);
/**
@class Represents a KiiQuery object
@exports root.KiiQuery as KiiQuery
*/
root.KiiQuery = (function() {
var _clause, _cursor, _limit, _paginationKey, _sortDescending, _sortField, _sortString;
function KiiQuery() {
this._dictValue = __bind(this._dictValue, this);
this.sortByAsc = __bind(this.sortByAsc, this);
this.sortByDesc = __bind(this.sortByDesc, this);
this.setLimit = __bind(this.setLimit, this);
this.getLimit = __bind(this.getLimit, this);
this._setClause = __bind(this._setClause, this);
this.setPaginationKey = __bind(this.setPaginationKey, this);
this.getPaginationKey = __bind(this.getPaginationKey, this);
}
_sortString = null;
_cursor = null;
_paginationKey = null;
_sortDescending = false;
_sortField = null;
_limit = 25;
_clause = null;
KiiQuery.prototype.getPaginationKey = function() {
return this._paginationKey;
};
KiiQuery.prototype.setPaginationKey = function(_paginationKey) {
this._paginationKey = _paginationKey;
};
KiiQuery.prototype._setClause = function(_clause) {
this._clause = _clause;
};
/** Get the limit of the current query
@returns {Integer}
*/
KiiQuery.prototype.getLimit = function() {
return this._limit;
};
/** Set the limit of the given query
@param value The desired limit. Must be an integer > 0
@throws InvalidLimitException
*/
KiiQuery.prototype.setLimit = function(value) {
if (value > 0) {
return this._limit = value;
} else {
throw new InvalidLimitException;
}
};
/** Create a KiiQuery object based on a KiiClause
@param clause The KiiClause to be executed with the query
*/
KiiQuery.queryWithClause = function(clause) {
var query;
query = new KiiQuery();
query._setClause(clause);
return query;
};
/** Set the query to sort by a field in descending order
If a sort has already been set, it will be overwritten.
@param {String} field The key that should be used to sort
*/
KiiQuery.prototype.sortByDesc = function(_sortField) {
this._sortField = _sortField;
return this._sortDescending = true;
};
/** Set the query to sort by a field in ascending order
If a sort has already been set, it will be overwritten.
@param {String} field The key that should be used to sort
*/
KiiQuery.prototype.sortByAsc = function(_sortField) {
this._sortField = _sortField;
return this._sortDescending = false;
};
KiiQuery._emptyDictValue = function() {
return {
type: "all"
};
};
KiiQuery.prototype._dictValue = function() {
var data;
data = {
descending: this._sortDescending
};
if (this._clause != null) {
data.clause = this._clause._getDictValue();
} else {
data.clause = KiiQuery._emptyDictValue();
}
if (this._sortField != null) {
data.orderBy = this._sortField;
}
return data;
};
return KiiQuery;
}).call(this);
/**
@class Represents a KiiClause expression object
@exports root.KiiClause as KiiClause
*/
root.KiiClause = (function() {
var _dictExpression, _whereClauses, _whereType;
function KiiClause() {
this._getDictValue = __bind(this._getDictValue, this);
this._setDictValue = __bind(this._setDictValue, this);
this._setWhereClauses = __bind(this._setWhereClauses, this);
this._setWhereType = __bind(this._setWhereType, this);
}
_dictExpression = null;
_whereType = null;
_whereClauses = null;
KiiClause.constructor = function() {
KiiClause._whereClauses = [];
return KiiClause._dictExpression = {};
};
KiiClause.prototype._setWhereType = function(_whereType) {
this._whereType = _whereType;
};
KiiClause.prototype._setWhereClauses = function(_whereClauses) {
this._whereClauses = _whereClauses;
};
KiiClause.prototype._setDictValue = function(_dictExpression) {
this._dictExpression = _dictExpression;
};
KiiClause.prototype._getDictValue = function() {
var clause, clauses, retDict, _i, _len, _ref;
retDict = {};
if ((this._whereClauses != null) && (this._whereType != null)) {
clauses = [];
if (this._whereClauses.length === 1) {
clause = this._whereClauses[0];
if (this._whereType === "not") {
retDict = {
"type": this._whereType,
"clause": clause._getDictValue()
};
} else {
retDict = clause._getDictValue();
}
} else {
_ref = this._whereClauses;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
clause = _ref[_i];
clauses.push(clause._getDictValue());
}
retDict = {
"type": this._whereType,
"clauses": clauses
};
}
} else if (this._whereClauses != null) {
if (this._whereClauses.length > 0) {
retDict = this._whereClauses[0]._getDictValue();
}
} else if (this._dictExpression != null) {
retDict = this._dictExpression;
}
if (!(retDict != null)) {
retDict = KiiQuery.emptyDictValue();
}
return retDict;
};
KiiClause.createWithWhere = function(whereType, whereClauses) {
var expression;
expression = new KiiClause();
expression._setWhereType(whereType);
expression._setWhereClauses(whereClauses);
return expression;
};
KiiClause.create = function(operator, key, value) {
var expression, _dict;
expression = new KiiClause();
_dict = {};
if (operator === "=") {
_dict.type = "eq";
_dict.field = key;
_dict.value = value;
} else if (operator === "<") {
_dict.type = "range";
_dict.field = key;
_dict.upperLimit = value;
_dict.upperIncluded = false;
} else if (operator === "<=") {
_dict.type = "range";
_dict.field = key;
_dict.upperLimit = value;
_dict.upperIncluded = true;
} else if (operator === ">") {
_dict.type = "range";
_dict.field = key;
_dict.lowerLimit = value;
_dict.lowerIncluded = false;
} else if (operator === ">=") {
_dict.type = "range";
_dict.field = key;
_dict.lowerLimit = value;
_dict.lowerIncluded = true;
} else if (operator === "in") {
_dict.type = "in";
_dict.field = key;
_dict.values = value;
} else if (operator === "prefix") {
_dict.type = "prefix";
_dict.field = key;
_dict.prefix = value;
}
expression._setDictValue(_dict);
return expression;
};
/** Create a KiiClause with the AND operator concatenating multiple KiiClause objects
@param {List} A variable-length list of KiiClause objects to concatenate
@example
KiiClause clause = KiiClause.and(clause1, clause2, clause3, . . .)
*/
KiiClause.and = function() {
return KiiClause.createWithWhere("and", arguments);
};
/** Create a KiiClause with the OR operator concatenating multiple KiiClause objects
@param {List} A variable-length list of KiiClause objects to concatenate
@example
KiiClause clause = KiiClause.or(clause1, clause2, clause3, . . .)
*/
KiiClause.or = function() {
return KiiClause.createWithWhere("or", arguments);
};
/** Create an expression of the form (key == value)
@param {String} key The key to compare
@param {Object} value the value to compare
*/
KiiClause.equals = function(key, value) {
if (value._className != null) {
value = value.objectURI;
}
return KiiClause.create("=", key, value);
};
/** Create an expression of the form (key != value)
@param {String} key The key to compare
@param {Object} value the value to compare
*/
KiiClause.notEquals = function(key, value) {
if (value._className != null) {
value = value.objectURI;
}
return KiiClause.createWithWhere("not", [KiiClause.equals(key, value)]);
};
/** Create an expression of the form (key > value)
@param {String} key The key to compare
@param {Object} value the value to compare
*/
KiiClause.greaterThan = function(key, value) {
return KiiClause.create(">", key, value);
};
/** Create an expression of the form (key >= value)
@param {String} key The key to compare
@param {Object} value the value to compare
*/
KiiClause.greaterThanOrEqual = function(key, value) {
return KiiClause.create(">=", key, value);
};
/** Create an expression of the form (key < value)
@param {String} key The key to compare
@param {Object} value the value to compare
*/
KiiClause.lessThan = function(key, value) {
return KiiClause.create("<", key, value);
};
/** Create an expression of the form (key <= value)
@param {String} key The key to compare
@param {Object} value the value to compare
*/
KiiClause.lessThanOrEqual = function(key, value) {
return KiiClause.create("<=", key, value);
};
/** Create an expression of the form (key in values)
@param {String} key The key to compare
@param {Object} value the value to compare
*/
KiiClause["in"] = function(key, values) {
return KiiClause.create("in", key, values);
};
/** Create an expression of the form (key STARTS WITH value)
@param {String} key The key to compare
@param {Object} value the value to compare
*/
KiiClause.startsWith = function(key, value) {
return KiiClause.create("prefix", key, value);
};
return KiiClause;
}).call(this);
KiiRequest = (function() {
var _thisRequest;
_thisRequest = null;
KiiRequest._path = null;
KiiRequest._method = null;
KiiRequest._headers = null;
KiiRequest._data = null;
KiiRequest._contentType = null;
KiiRequest._anonymous = false;
KiiRequest._accept = null;
KiiRequest._success = null;
KiiRequest._failure = null;
KiiRequest.prototype.getPath = function() {
return this._path;
};
KiiRequest.prototype.setPath = function(_path) {
this._path = _path;
};
KiiRequest.prototype.getMethod = function() {
return this._method;
};
KiiRequest.prototype.setMethod = function(_method) {
this._method = _method;
};
KiiRequest.prototype.getHeaders = function() {
return this._headers;
};
KiiRequest.prototype.setHeaders = function(_headers) {
this._headers = _headers;
};
KiiRequest.prototype.getData = function() {
return this._data;
};
KiiRequest.prototype.setData = function(_data) {
this._data = _data;
};
KiiRequest.prototype.getContentType = function() {
return this._contentType;
};
KiiRequest.prototype.setContentType = function(_contentType) {
this._contentType = _contentType;
};
KiiRequest.prototype.isAnonymous = function() {
return this._anonymous;
};
KiiRequest.prototype.setAnonymous = function(_anonymous) {
this._anonymous = _anonymous;
};
KiiRequest.prototype.getAccept = function() {
return this._accept;
};
KiiRequest.prototype.setAccept = function(_accept) {
this._accept = _accept;
};
KiiRequest.prototype.addHeader = function(name, value) {
return this._headers[name] = value;
};
function KiiRequest(path, withApp) {
this.execute = __bind(this.execute, this);
this.addHeader = __bind(this.addHeader, this);
this.setAccept = __bind(this.setAccept, this);
this.getAccept = __bind(this.getAccept, this);
this.setAnonymous = __bind(this.setAnonymous, this);
this.isAnonymous = __bind(this.isAnonymous, this);
this.setContentType = __bind(this.setContentType, this);
this.getContentType = __bind(this.getContentType, this);
this.setData = __bind(this.setData, this);
this.getData = __bind(this.getData, this);
this.setHeaders = __bind(this.setHeaders, this);
this.getHeaders = __bind(this.getHeaders, this);
this.setMethod = __bind(this.setMethod, this);
this.getMethod = __bind(this.getMethod, this);
this.setPath = __bind(this.setPath, this);
this.getPath = __bind(this.getPath, this);
var _this = this;
_thisRequest = this;
this._path = withApp ? "/apps/" + (Kii.getAppID()) + path : path;
this._method = "GET";
this._headers = {
"accept": "*/*"
};
this._contentType = "application/json";
this._anonymous = false;
this._success = function() {};
this._failure = function() {};
}
KiiRequest.prototype.execute = function(callbacks, ignoreBody) {
var ajaxData, json_text, key, postData, url, val, _ref,
_this = this;
this._success = callbacks.success != null ? callbacks.success : this._success;
this._failure = callbacks.failure != null ? callbacks.failure : this._failure;
url = Kii.getBaseURL() + this._path;
Kii.logger("POSTING: ");
Kii.logger(this._data);
if (this._data != null) {
postData = {};
}
_ref = this._data;
for (key in _ref) {
val = _ref[key];
postData[key] = encodeURIComponent(val);
}
json_text = JSON.stringify(this._data);
Kii.logger("Making request[" + this._method + "] to " + url + " with data: " + json_text);
this._headers['x-kii-appid'] = Kii.getAppID();
this._headers['x-kii-appkey'] = Kii.getAppKey();
if (this._accept != null) {
this._headers['accept'] = this._accept;
}
if (!this._anonymous && (KiiUser.getCurrentUser() != null)) {
this._headers['Authorization'] = "Bearer " + (KiiUser.getCurrentUser().getAccessToken());
}
Kii.logger("Headers: ");
Kii.logger(this._headers);
$.support.cors = true;
ajaxData = {
type: this._method,
url: url,
dataType: "json",
headers: this._headers,
contentType: this._contentType,
error: function(xhr, status, error) {
var errString, json;
errString = error;
json = jQuery.parseJSON(decodeURIComponent(xhr.responseText));
if (json != null) {
if (json.errorCode != null) {
errString = json.errorCode;
if (json.message != null) {
errString += ": " + json.message;
}
}
}
Kii.logger("Failure: " + errString);
Kii.logger(xhr.responseText);
return _thisRequest._failure(errString, xhr.status);
},
success: function(data, status, xhr) {
var errString, json;
Kii.logger("Completed Request[" + xhr.status + "]");
Kii.logger(xhr.responseText);
json = jQuery.parseJSON(xhr.responseText);
if (json != null) {
if (json.errorCode != null) {
errString = json.errorCode;
if (json.message != null) {
errString += ": " + json.message;
}
return _thisRequest._failure(errString, xhr.status, json.errorCode);
} else {
return _thisRequest._success(json, xhr.status);
}
} else if (ignoreBody) {
return _thisRequest._success(null, xhr.status);
} else {
return _thisRequest._failure("Unable to parse server response. HTTP Status: " + xhr.status, xhr.status, "PARSE_ERROR");
}
}
};
if (this.method !== "GET" && (json_text != null)) {
ajaxData.data = json_text;
ajaxData.processData = false;
}
return $.ajax(ajaxData);
};
return KiiRequest;
})();
/**
@class Represents a KiiUser object
@exports root.KiiUser as KiiUser
*/
root.KiiUser = (function() {
var _accessToken, _country, _created, _customInfo, _displayName, _emailAddress, _emailVerified, _modified, _password, _phoneNumber, _phoneVerified, _thisUser, _username, _uuid;
_thisUser = null;
_uuid = null;
_username = null;
_displayName = null;
_password = null;
_emailAddress = null;
_phoneNumber = null;
_country = null;
_created = null;
_modified = null;
_emailVerified = null;
_phoneVerified = null;
_accessToken = null;
_customInfo = null;
function KiiUser() {
this._updateWithJSON = __bind(this._updateWithJSON, this);
this["delete"] = __bind(this["delete"], this);
this.refresh = __bind(this.refresh, this);
this.save = __bind(this.save, this);
this.changeEmail = __bind(this.changeEmail, this);
this.changePhone = __bind(this.changePhone, this);
this.memberOfGroups = __bind(this.memberOfGroups, this);
this.resendPhoneNumberVerification = __bind(this.resendPhoneNumberVerification, this);
this.resendEmailVerification = __bind(this.resendEmailVerification, this);
this.resendVerification = __bind(this.resendVerification, this);
this.verifyPhoneNumber = __bind(this.verifyPhoneNumber, this);
this.verifyCredentials = __bind(this.verifyCredentials, this);
this.updatePassword = __bind(this.updatePassword, this);
this.register = __bind(this.register, this);
this._authenticateWithToken = __bind(this._authenticateWithToken, this);
this._authenticate = __bind(this._authenticate, this);
this.bucketWithName = __bind(this.bucketWithName, this);
this.get = __bind(this.get, this);
this.set = __bind(this.set, this);
this.objectURI = __bind(this.objectURI, this);
this._setAccessToken = __bind(this._setAccessToken, this);
this.getAccessToken = __bind(this.getAccessToken, this);
this._setPhoneVerified = __bind(this._setPhoneVerified, this);
this.getPhoneVerified = __bind(this.getPhoneVerified, this);
this._setEmailVerified = __bind(this._setEmailVerified, this);
this.getEmailVerified = __bind(this.getEmailVerified, this);
this._setModified = __bind(this._setModified, this);
this.getModified = __bind(this.getModified, this);
this._setCreated = __bind(this._setCreated, this);
this.getCreated = __bind(this.getCreated, this);
this.setCountry = __bind(this.setCountry, this);
this.getCountry = __bind(this.getCountry, this);
this._setPassword = __bind(this._setPassword, this);
this._setPhoneNumber = __bind(this._setPhoneNumber, this);
this.getPhoneNumber = __bind(this.getPhoneNumber, this);
this._setEmailAddress = __bind(this._setEmailAddress, this);
this.getEmailAddress = __bind(this.getEmailAddress, this);
this.setDisplayName = __bind(this.setDisplayName, this);
this.getDisplayName = __bind(this.getDisplayName, this);
this._setUsername = __bind(this._setUsername, this);
this.getUsername = __bind(this.getUsername, this);
this._setUUID = __bind(this._setUUID, this);
this.getUUID = __bind(this.getUUID, this);
this._customInfo = {};
}
/** Get the UUID of the given user, assigned by the server
@returns {String}
*/
KiiUser.prototype.getUUID = function() {
return this._uuid;
};
KiiUser.prototype._setUUID = function(_uuid) {
this._uuid = _uuid;
};
/** Get the username of the given user
@returns {String}
*/
KiiUser.prototype.getUsername = function() {
return this._username;
};
KiiUser.prototype._setUsername = function(value) {
Kii.logger("Setting username: " + value);
if (KiiUtilities._validateUsername(value)) {
return this._username = $.trim(value);
} else {
throw new InvalidUsernameException;
}
};
/** Get the display name associated with this user
@returns {String}
*/
KiiUser.prototype.getDisplayName = function() {
return this._displayName;
};
/** Set the display name associated with this user. Cannot be used for logging a user in; is non-unique
@param {String} value Must be between 4-50 alphanumeric characters, must start with a letter
@throws {InvalidDisplayNameException} If the displayName is not a valid format
*/
KiiUser.prototype.setDisplayName = function(value) {
var pattern;
pattern = /^[A-Za-z0-9-_]{4,50}$/i;
if ((typeof value).toLowerCase() !== "string") {
throw new InvalidDisplayNameException;
} else if (value.match(pattern)) {
return this._displayName = value;
} else {
throw new InvalidDisplayNameException;
}
};
/** Get the email address associated with this user
@returns {String}
*/
KiiUser.prototype.getEmailAddress = function() {
return this._emailAddress;
};
KiiUser.prototype._setEmailAddress = function(value) {
Kii.logger("Setting email: " + value);
if (KiiUtilities._validateEmail(value)) {
return this._emailAddress = $.trim(value);
} else {
throw new InvalidEmailException;
}
};
/** Get the phone number associated with this user
@returns {String}
*/
KiiUser.prototype.getPhoneNumber = function() {
return this._phoneNumber;
};
KiiUser.prototype._setPhoneNumber = function(value) {
Kii.logger("Setting phone number: " + value);
if (KiiUtilities._validatePhoneNumber(value)) {
return this._phoneNumber = value;
} else {
throw new InvalidPhoneNumberException;
}
};
KiiUser.prototype._setPassword = function(value) {
if (KiiUtilities._validatePassword(value)) {
return this._password = value;
} else {
throw new InvalidPasswordException;
}
};
/** Get the country code associated with this user
@returns {String}
*/
KiiUser.prototype.getCountry = function() {
return this._country;
};
/** Set the country code associated with this user
@param {String} value The country code to set. Must be 2 alphabetic characters. Ex: US, JP, CN
@throws {InvalidCountryException} If the country code is not a valid format
*/
KiiUser.prototype.setCountry = function(value) {
if (KiiUtilities._validateCountryCode(value)) {
return this._country = value;
} else {
throw new InvalidCountryException;
}
};
/** Get the server's creation date of this user
@returns {String}
*/
KiiUser.prototype.getCreated = function() {
return this._created;
};
KiiUser.prototype._setCreated = function(_created) {
this._created = _created;
};
/** Get the modified date of the given user, assigned by the server
@returns {String}
*/
KiiUser.prototype.getModified = function() {
return this._modified;
};
KiiUser.prototype._setModified = function(_modified) {
this._modified = _modified;
};
/** Get the status of the user's email verification. This field is assigned by the server
@returns {Boolean} true if the user's email address has been verified by the user, false otherwise
*/
KiiUser.prototype.getEmailVerified = function() {
return this._emailVerified;
};
KiiUser.prototype._setEmailVerified = function(_emailVerified) {
this._emailVerified = _emailVerified;
};
/** Get the status of the user's phone number verification. This field is assigned by the server
@returns {Boolean} true if the user's email address has been verified by the user, false otherwise
*/
KiiUser.prototype.getPhoneVerified = function() {
return this._phoneVerified;
};
KiiUser.prototype._setPhoneVerified = function(_phoneVerified) {
this._phoneVerified = _phoneVerified;
};
/** Get the access token for the user - only available if the user is currently logged in
@returns {String}
*/
KiiUser.prototype.getAccessToken = function() {
Kii.logger("Getting access token: " + this._accessToken);
return this._accessToken;
};
KiiUser.prototype._setAccessToken = function(_accessToken) {
this._accessToken = _accessToken;
return Kii.logger("Setting access token: " + this._accessToken);
};
/** Get a specifically formatted string referencing the user
<br><br>The user must exist in the cloud (have a valid UUID).
@returns {String} A URI string based on the given user. null if a URI couldn't be generated.
@example
var user = . . .; // a KiiUser
var uri = user.objectURI();
*/
KiiUser.prototype.objectURI = function() {
var uri;
if (this._uuid != null) {
uri = "kiicloud://users/" + this._uuid;
}
return uri;
};
/** Sets a key/value pair to a KiiUser
<br><br>If the key already exists, its value will be written over. If the object is of invalid type, it will return false and a KiiError will be thrown (quietly). Accepted types are any JSON-encodable objects.
@param {String} key The key to set. The key must not be a system key (created, metadata, modified, type, uuid) or begin with an underscore (_)
@param {Object} value The value to be set. Object must be of a JSON-encodable type (Ex: dictionary, array, string, number, etc)
@example
var user = . . .; // a KiiUser
user.set("score", 4298);
*/
KiiUser.prototype.set = function(key, value) {
Kii.logger(this);
Kii.logger(this._customInfo);
return this._customInfo[key] = value;
};
/** Gets the value associated with the given key
@param {String} key The key to retrieve
@returns {Object} The object associated with the key. null if none exists
@example
var user = . . .; // a KiiUser
var score = user.get("score");
*/
KiiUser.prototype.get = function(key) {
return this._customInfo[key];
};
/**
The currently authenticated user
@returns {KiiUser}
@example
var user = KiiUser.getCurrentUser();
*/
KiiUser.getCurrentUser = function() {
return Kii.getCurrentUser();
};
/** Create a user object to prepare for registration with credentials pre-filled
<br><br>Creates an pre-filled user object for manipulation. This user will not be authenticated until one of the authentication methods are called on it. It can be treated as any other KiiObject before it is authenticated.
@param username The user's desired username. Must be between 3 and 64 characters, which can include alphanumeric characters as well as underscores '_' and periods '.'
@param password The user's password. Must be at least 4 characters, made up of alphanumeric and/or: @,#,$,%,^,&
@returns a working KiiUser object
@throws {InvalidUsernameException} If the username is not in the proper format
@throws {InvalidPasswordException} If the password is not in the proper format
@example
var user = KiiUser.userWithUsername("myusername", "mypassword");
*/
KiiUser.userWithUsername = function(username, password) {
var user;
user = new KiiUser();
user._setUsername(username);
user._setPassword(password);
return user;
};
KiiUser._userWithEmailAddress = function(emailAddress, password) {
var user;
user = new KiiUser();
user._setEmailAddress(emailAddress);
user._setPassword(password);
return user;
};
KiiUser._userWithPhoneNumber = function(phoneNumber, password) {
var user;
user = new KiiUser();
user._setPhoneNumber(phoneNumber);
user._setPassword(password);
return user;
};
/** Create a user object to prepare for registration with credentials pre-filled
<br><br>Creates an pre-filled user object for registration. This user will not be authenticated until the registration method is called on it. It can be treated as any other KiiUser before it is registered.
@param phoneNumber The user's phone number
@param password The user's password. Must be at least 4 characters, made up of alphanumeric and/or: @,#,$,%,^,&
@throws {InvalidPasswordException} If the password is not in the proper format
@throws {InvalidPhoneNumberException} If the phone number is not in the proper format
@returns a working KiiUser object
@example
var user = KiiUser.userWithPhoneNumber("15559847589", "mypassword");
*/
KiiUser.userWithPhoneNumber = function(phoneNumber, password) {
var user;
user = new KiiUser();
user._setPhoneNumber(phoneNumber);
user._setPassword(password);
return user;
};
/** Create a user object to prepare for registration with credentials pre-filled
<br><br>Creates an pre-filled user object for registration. This user will not be authenticated until the registration method is called on it. It can be treated as any other KiiUser before it is registered.
@param phoneNumber The user's phone number
@param username The user's desired username. Must be between 3 and 64 characters, which can include alphanumeric characters as well as underscores '_' and periods '.'
@param password The user's password. Must be at least 4 characters, made up of alphanumeric and/or: @,#,$,%,^,&
@throws {InvalidUsernameException} If the username is not in the proper format
@throws {InvalidPasswordException} If the password is not in the proper format
@throws {InvalidPhoneNumberException} If the phone number is not in the proper format
@returns a working KiiUser object
@example
var user = KiiUser.userWithPhoneNumberAndUsername("15559847589", "johndoe", "mypassword");
*/
KiiUser.userWithPhoneNumberAndUsername = function(phoneNumber, username, password) {
var user;
user = new KiiUser();
user._setPhoneNumber(phoneNumber);
user._setUsername(username);
user._setPassword(password);
return user;
};
/** Create a user object to prepare for registration with credentials pre-filled
<br><br>Creates an pre-filled user object for registration. This user will not be authenticated until the registration method is called on it. It can be treated as any other KiiUser before it is registered.
@param emailAddress The user's email address
@param password The user's password. Must be at least 4 characters, made up of alphanumeric and/or: @,#,$,%,^,&
@throws {InvalidPasswordException} If the password is not in the proper format
@throws {InvalidEmailException} If the email address is not in the proper format
@returns a working KiiUser object
@example
var user = KiiUser.userWithEmailAddress("[email protected]", "mypassword");
*/
KiiUser.userWithEmailAddress = function(emailAddress, password) {
var user;
user = new KiiUser();
user._setEmailAddress(emailAddress);
user._setPassword(password);
return user;
};
/** Create a user object to prepare for registration with credentials pre-filled
<br><br>Creates an pre-filled user object for registration. This user will not be authenticated until the registration method is called on it. It can be treated as any other KiiUser before it is registered.
@param emailAddress The user's email address
@param username The user's desired username. Must be between 3 and 64 characters, which can include alphanumeric characters as well as underscores '_' and periods '.'
@param password The user's password. Must be at least 4 characters, made up of alphanumeric and/or: @,#,$,%,^,&
@throws {InvalidUsernameException} If the username is not in the proper format
@throws {InvalidPasswordException} If the password is not in the proper format
@throws {InvalidEmailException} If the phone number is not in the proper format
@returns a working KiiUser object
@example
var user = KiiUser.userWithEmailAddressAndUsername("[email protected]", "johndoe", "mypassword");
*/
KiiUser.userWithEmailAddressAndUsername = function(emailAddress, username, password) {
var user;
user = new KiiUser();
user._setEmailAddress(emailAddress);
user._setUsername(username);
user._setPassword(password);
return user;
};
KiiUser._validateURI = function(value) {
var match, pattern, retValue;
value = $.trim(value);
pattern = /^kiicloud:\/\/users\/([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})$/i;
if ((typeof value).toLowerCase() === "string") {
match = value.match(pattern);
if (match != null) {
retValue = match[1];
}
}
return retValue;
};
/** Generate a new KiiUser based on a given URI
@param {String} uri The URI of the object to be represented
@returns {KiiUser} A new KiiUser with its parameters filled in from the URI
@throws {InvalidURIException} If the URI is not in the proper format
@example
var user = new KiiUser.userWithURI("kiicloud://myuri");
*/
KiiUser.userWithURI = function(uri) {
var user, uuid;
Kii.logger("About to extract from: " + uri);
uuid = KiiUser._validateURI(uri);
Kii.logger("Extracted uuid from uri: " + uuid);
if (uuid != null) {
user = new KiiUser();
user._setUUID(uuid);
} else {
throw new InvalidURIException;
}
return user;
};
KiiUser.userWithID = function(id) {
var user;
user = new KiiUser();
user._setUUID(id);
return user;
};
/** Creates a reference to a bucket for this user
<br><br>The bucket will be created/accessed within this user's scope
@param {String} bucketName The name of the bucket the user should create/access
@returns {KiiBucket} A working KiiBucket object
@example
var user = . . .; // a KiiUser
var bucket = user.bucketWithName("myBucket");
*/
KiiUser.prototype.bucketWithName = function(bucketName) {
return new KiiBucket.bucketWithName(bucketName, this);
};
KiiUser.prototype._authenticate = function(callbacks) {
var authCallbacks, request, username,
_this = this;
_thisUser = this;
Kii.logger("Authenticating user " + this);
Kii.logger(callbacks);
if (this._username != null) {
username = this._username;
} else if (this._emailAddress != null) {
username = this._emailAddress;
} else if (this._phoneNumber != null) {
username = this._phoneNumber;
}
request = new KiiRequest("/oauth2/token", false);
request.setAnonymous(true);
request.setMethod("POST");
request.setData({
username: username,
password: this._password
});
authCallbacks = {
success: function(data) {
_thisUser._setUUID(data.id);
_thisUser._setAccessToken(data.access_token);
Kii.setCurrentUser(_thisUser);
if (callbacks != null) {
return callbacks.success(Kii.getCurrentUser());
}
},
failure: function(error, statusCode) {
if (callbacks != null) {
return callbacks.failure(_thisUser, error);
}
}
};
return request.execute(authCallbacks, false);
};
KiiUser.prototype._authenticateWithToken = function(token, callbacks) {
var authCallbacks, request,
_this = this;
_thisUser = this;
Kii.logger("Authenticating user " + this);
Kii.logger(callbacks);
request = new KiiRequest("/users/me", true);
request.setAnonymous(true);
request.addHeader("Authorization", "Bearer " + token);
authCallbacks = {
success: function(data) {
_thisUser._updateWithJSON(data);
_thisUser._setAccessToken(token);
Kii.setCurrentUser(_thisUser);
if (callbacks != null) {
return callbacks.success(Kii.getCurrentUser());
}
},
failure: function(error, statusCode) {
if (callbacks != null) {
return callbacks.failure(_thisUser, error);
}
}
};
return request.execute(authCallbacks, false);
};
/** Authenticates a user with the server
@param {String} userIdentifier The username, validated email address, or validated phone number of the user to authenticate
@param {String} password The password of the user to authenticate
@param {Object} callbacks An object with callback methods defined
@param {Method} callbacks.success The callback method to call on a successful authentication request
@param {Method} callbacks.failure The callback method to call on a failed authentication request
@example
KiiUser.authenticate("myusername", "mypassword", {
success: function(theAuthedUser) {
// do something with the authenticated user
},
failure: function(theUser, anErrorString) {
// do something with the error response
}
});
*/
KiiUser.authenticate = function(userIdentifier, password, callbacks) {
var user;
try {
if (KiiUtilities._validateEmail(userIdentifier)) {
user = KiiUser._userWithEmailAddress(userIdentifier, password);
} else if (KiiUtilities._validatePhoneNumber(userIdentifier)) {
user = KiiUser._userWithPhoneNumber(userIdentifier, password);
} else {
user = KiiUser.userWithUsername(userIdentifier, password);
}
return user._authenticate(callbacks);
} catch (error) {
if (callbacks != null) {
return callbacks.failure(null, "Unable to authenticate. Ensure the user identifier and password are valid");
}
}
};
/** Asynchronously authenticates a user with the server using a valid access token
Authenticates a user with the server. This method is non-blocking.
@param {String} accessToken A valid access token associated with the desired user
@param {Object} callbacks An object with callback methods defined
@param {Method} callbacks.success The callback method to call on a successful authentication request
@param {Method} callbacks.failure The callback method to call on a failed authentication request
@example
KiiUser.authenticateWithToken("mytoken", {
success: function(theAuthedUser) {
// do something with the authenticated user
},
failure: function(theUser, anErrorString) {
// do something with the error response
}
});
*/
KiiUser.authenticateWithToken = function(token, callbacks) {
var user;
user = new KiiUser();
return user._authenticateWithToken(token, callbacks);
};
/** Registers a user with the server
<br><br>The user object must have an associated email/password combination.
@param {Object} callbacks An object with callback methods defined
@param {Method} callbacks.success The callback method to call on a successful registration request
@param {Method} callbacks.failure The callback method to call on a failed registration request
@example
var user = KiiUser.userWithUsername("myusername", "mypassword");
user.register({
success: function(theAuthedUser) {
// do something with the authenticated user
},
failure: function(theUser, anErrorString) {
// do something with the error response
}
});
*/
KiiUser.prototype.register = function(callbacks) {
var data, key, registrationCallbacks, request, value, _ref,
_this = this;
_thisUser = this;
Kii.logger("Registering user " + this);
data = {
password: this._password
};
if (this._username != null) {
data.loginName = this._username;
}
if (this._displayName != null) {
data.displayName = this._displayName;
}
if (this._emailAddress != null) {
data.emailAddress = this._emailAddress;
}
if (this._phoneNumber != null) {
data.phoneNumber = this._phoneNumber;
}
if (this._country != null) {
data.country = this._country;
}
Kii.logger("CINFO");
Kii.logger(this._customInfo);
_ref = this._customInfo;
for (key in _ref) {
value = _ref[key];
Kii.logger("Key/val: " + key + "/" + value);
data[key] = value;
}
request = new KiiRequest("/users", true);
request.setMethod("POST");
request.setData(data);
request.setAnonymous(true);
request.setContentType("application/vnd.kii.RegistrationRequest+json");
registrationCallbacks = {
success: function(data) {
Kii.logger("Succreg");
return _thisUser._authenticate(callbacks);
},
failure: function(error, statusCode) {
Kii.logger("Failreg");
if (callbacks != null) {
return callbacks.failure(_thisUser, error);
}
}
};
return request.execute(registrationCallbacks, false);
};
/** Update a user's password on the server
<br><br>Update a user's password with the server. The fromPassword must be equal to the current password associated with the account in order to succeed.
@param {String} fromPassword The user's current password
@param {String} toPassword The user's desired password. Must be at least 4 characters, made up of alphanumeric and/or: @,#,$,%,^,&
@param {Object} callbacks An object with callback methods defined
@param {Method} callbacks.success The callback method to call on a successful update password request
@param {Method} callbacks.failure The callback method to call on a failed update password request
@throws {InvalidPasswordException} If the new password is not in the proper format
@example
var user = Kii.currentUser();
user.updatePassword("oldpassword", "newpassword", {
success: function(theUser) {
// do something
},
failure: function(theUser, anErrorString) {
// do something with the error response
}
});
*/
KiiUser.prototype.updatePassword = function(fromPassword, toPassword, callbacks) {
var data, path, request, updateCallbacks,
_this = this;
_thisUser = this;
Kii.logger("Updating password from " + fromPassword + " to " + toPassword);
if (KiiUtilities._validatePassword(toPassword)) {
data = {
oldPassword: fromPassword,
newPassword: toPassword
};
path = "/users/" + this._uuid + "/password";
request = new KiiRequest(path, true);
request.setMethod("PUT");
request.setData(data);
request.setContentType("application/vnd.kii.ChangePasswordRequest+json");
updateCallbacks = {
success: function(data, statusCode) {
if (statusCode < 300 && statusCode >= 200) {
_thisUser._setPassword(toPassword);
if (callbacks != null) {
return callbacks.success(_thisUser);
}
} else if (callbacks != null) {
return callbacks.failure(_thisUser, "Unable to change password");
}
},
failure: function(error, statusCode) {
if (callbacks != null) {
return callbacks.failure(_thisUser, error);
}
}
};
return request.execute(updateCallbacks, true);
} else if (callbacks != null) {
return callbacks.failure(_thisUser, (new InvalidPasswordException()).message);
}
};
/** Reset a user's password on the server
<br><br>Reset a user's password on the server. The user is determined by the specified userIdentifier - which can be an email address or phone number that has already been associated with an account. Reset instructions will be sent to that identifier.
@param {String} userIdentifier The user's current password
@param {Object} callbacks An object with callback methods defined
@param {Method} callbacks.success The callback method to call on a successful update password request
@param {Method} callbacks.failure The callback method to call on a failed update password request
@example
KiiUser.resetPassword("[email protected]", {
success: function() {
// do something
},
failure: function(anErrorString) {
// do something with the error response
}
});
*/
KiiUser.resetPassword = function(userIdentifier, callbacks) {
var accountType, path, request, resetCallbacks;
Kii.logger("Resetting password with identifier: " + userIdentifier);
if (KiiUtilities._validateEmail(userIdentifier)) {
accountType = "EMAIL";
} else if (KiiUtilities._validatePhoneNumber(userIdentifier)) {
accountType = "PHONE";
} else if (callbacks != null) {
callbacks.failure("Invalid user identifier. Must be a valid email address or phone number");
return;
}
if (accountType != null) {
path = "/users/" + accountType + ":" + userIdentifier + "/password/request-reset";
request = new KiiRequest(path, true);
request.setMethod("POST");
request.setAnonymous(true);
resetCallbacks = {
success: function(data, statusCode) {
if (statusCode < 300 && statusCode >= 200 && (callbacks != null)) {
return callbacks.success();
} else if (callbacks != null) {
return callbacks.failure("Unable to reset password");
}
},
failure: function(error, statusCode) {
if (callbacks != null) {
return callbacks.failure(error);
}
}
};
return request.execute(resetCallbacks, true);
}
};
KiiUser.prototype.verifyCredentials = function(type, code, callbacks) {
var path, request, verifyCallbacks,
_this = this;
_thisUser = this;
Kii.logger("Verifying " + type + " with code: " + code);
path = "/users/me/" + type + "/verify";
request = new KiiRequest(path, true);
request.setMethod("POST");
request.setData({
verificationCode: code
});
request.setContentType("application/vnd.kii.AddressVerificationRequest+json");
verifyCallbacks = {
success: function(data, statusCode) {
if (statusCode < 300 && statusCode >= 200) {
if (type === "email-address") {
_thisUser._setEmailVerified(true);
} else if (type === "phone-number") {
_thisUser._setPhoneVerified(true);
}
if (callbacks != null) {
return callbacks.success(_thisUser);
}
} else if (callbacks != null) {
return callbacks.failure(_thisUser, "Unable to verify " + type);
}
},
failure: function(error, statusCode) {
if (callbacks != null) {
return callbacks.failure(_thisUser, error);
}
}
};
return request.execute(verifyCallbacks, true);
};
/** Verify the current user's phone number
<br><br>This method is used to verify the phone number of the currently logged in user.
@param {String} verificationCode The code which verifies the currently logged in user
@param {Object} callbacks An object with callback methods defined
@param {Method} callbacks.success The callback method to call on a successful verification request
@param {Method} callbacks.failure The callback method to call on a failed verification request
@example
var user = Kii.currentUser();
user.verifyPhoneNumber("012345", {
success: function(theUser) {
// do something
},
failure: function(theUser, anErrorString) {
// do something with the error response
}
});
*/
KiiUser.prototype.verifyPhoneNumber = function(verificationCode, callbacks) {
return this.verifyCredentials("phone-number", verificationCode, callbacks);
};
KiiUser.prototype.resendVerification = function(type, callbacks) {
var path, request, resendCallbacks,
_this = this;
_thisUser = this;
Kii.logger("Resending verification " + type);
path = "/users/me/" + type + "/resend-verification";
request = new KiiRequest(path, true);
request.setMethod("POST");
resendCallbacks = {
success: function(data, statusCode) {
if (statusCode < 300 && statusCode >= 200 && (callbacks != null)) {
return callbacks.success(_thisUser);
} else if (callbacks != null) {
return callbacks.failure(_thisUser, "Unable to resend " + type + " verification");
}
},
failure: function(error, statusCode) {
if (callbacks != null) {
return callbacks.failure(_thisUser, error);
}
}
};
return request.execute(resendCallbacks, true);
};
/** Resend the email verification code to the user
<br><br>This method will re-send the email verification to the currently logged in user
@param {Object} callbacks An object with callback methods defined
@param {Method} callbacks.success The callback method to call on a successful resend request
@param {Method} callbacks.failure The callback method to call on a failed resend request
@example
var user = Kii.currentUser();
user.resendEmailVerification({
success: function(theUser) {
// do something
},
failure: function(theUser, anErrorString) {
// do something with the error response
}
});
*/
KiiUser.prototype.resendEmailVerification = function(callbacks) {
return this.resendVerification("email-address", callbacks);
};
/** Resend the SMS verification code to the user
<br><br>This method will re-send the SMS verification to the currently logged in user
@param {Object} callbacks An object with callback methods defined
@param {Method} callbacks.success The callback method to call on a successful resend request
@param {Method} callbacks.failure The callback method to call on a failed resend request
@example
var user = Kii.currentUser();
user.resendPhoneNumberVerification({
success: function(theUser) {
// do something
},
failure: function(theUser, anErrorString) {
// do something with the error response
}
});
*/
KiiUser.prototype.resendPhoneNumberVerification = function(callbacks) {
return this.resendVerification("phone-number", callbacks);
};
/** Retrieve a list of groups which the user is a member of
@param {Object} callbacks An object with callback methods defined
@param {Method} callbacks.success The callback method to call on a successful resend request
@param {Method} callbacks.failure The callback method to call on a failed resend request
@example
var user = Kii.currentUser();
user.memberOfGroups({
success: function(theUser, groupList) {
// do something with the results
for(var i=0; i<groupList.length; i++) {
var g = groupList[i]; // a KiiGroup object
}
},
failure: function(theUser, anErrorString) {
// do something with the error response
}
});
*/
KiiUser.prototype.memberOfGroups = function(callbacks) {
var memberCallbacks, path, request,
_this = this;
_thisUser = this;
Kii.logger("Getting groups for member " + this._uuid);
path = "/groups/?is_member=" + this._uuid;
request = new KiiRequest(path, true);
request.setAccept("application/vnd.kii.GroupsRetrievalResponse+json");
memberCallbacks = {
success: function(data, statusCode) {
var group, groupList, _i, _len, _ref;
if (statusCode < 300 && statusCode >= 200) {
groupList = [];
_ref = data.groups;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
group = _ref[_i];
groupList.push(KiiGroup.groupWithJSON(group));
}
if (callbacks != null) {
return callbacks.success(_thisUser, groupList);
}
} else if (callbacks != null) {
return callbacks.failure(_thisUser, "Unable to retrieve groups");
}
},
failure: function(error, statusCode) {
if (callbacks != null) {
return callbacks.failure(_thisUser, error);
}
}
};
return request.execute(memberCallbacks, false);
};
/** Updates the user's phone number on the server
@param {String} newPhoneNumber The new phone number to change to
@param {Object} callbacks An object with callback methods defined
@param {Method} callbacks.success The callback method to call on a successful resend request
@param {Method} callbacks.failure The callback method to call on a failed resend request
@example
var user = Kii.currentUser();
user.changePhone('+19415551234', {
success: function(theUser) {
// do something on success
},
failure: function(theUser, anErrorString) {
// do something with the error response
}
});
*/
KiiUser.prototype.changePhone = function(newPhoneNumber, callbacks) {
var path, request, updateCallbacks,
_this = this;
_thisUser = this;
Kii.logger("Updating phone number to " + newPhoneNumber);
path = "/users/" + this._uuid + "/phone-number";
request = new KiiRequest(path, true);
request.setMethod("PUT");
request.setContentType("application/vnd.kii.PhoneNumberModificationRequest+json");
request.setData({
phoneNumber: newPhoneNumber
});
updateCallbacks = {
success: function(data, statusCode) {
if (statusCode < 300 && statusCode >= 200 && (callbacks != null)) {
_thisUser._setPhoneVerified(false);
_thisUser._setPhoneNumber(newPhoneNumber);
return callbacks.success(_thisUser);
} else if (callbacks != null) {
return callbacks.failure(_thisUser, "Unable to update phone number");
}
},
failure: function(error, statusCode) {
if (callbacks != null) {
return callbacks.failure(_thisUser, error);
}
}
};
return request.execute(updateCallbacks, true);
};
/** Updates the user's email address on the server
@param {String} newEmail The new email address to change to
@param {Object} callbacks An object with callback methods defined
@param {Method} callbacks.success The callback method to call on a successful resend request
@param {Method} callbacks.failure The callback method to call on a failed resend request
@example
var user = Kii.currentUser();
user.changeEmail('[email protected]', {
success: function(theUser) {
// do something on success
},
failure: function(theUser, anErrorString) {
// do something with the error response
}
});
*/
KiiUser.prototype.changeEmail = function(newEmail, callbacks) {
var path, request, updateCallbacks,
_this = this;
_thisUser = this;
Kii.logger("Updating email address to: " + newEmail);
if (KiiUtilities._validateEmail(newEmail)) {
path = "/users/" + this._uuid + "/email-address";
request = new KiiRequest(path, true);
request.setMethod("PUT");
request.setContentType("application/vnd.kii.EmailAddressModificationRequest+json");
request.setData({
emailAddress: newEmail
});
updateCallbacks = {
success: function(data, statusCode) {
if (statusCode < 300 && statusCode >= 200 && (callbacks != null)) {
_thisUser._setEmailVerified(false);
_thisUser._setEmailAddress(newEmail);
return callbacks.success(_thisUser);
} else if (callbacks != null) {
return callbacks.failure(_thisUser, "Unable to update email address");
}
},
failure: function(error, statusCode) {
if (callbacks != null) {
return callbacks.failure(_thisUser, error);
}
}
};
return request.execute(updateCallbacks, true);
} else {
return callbacks.failure(_thisUser, "Invalid email address format");
}
};
/** Saves the latest user values to the server
<br><br>If the user does not yet exist, it will NOT be created. Otherwise, the fields that have changed will be updated accordingly.
@param {Object} callbacks An object with callback methods defined
@param {Method} callbacks.success The callback method to call on a successful save request
@param {Method} callbacks.failure The callback method to call on a failed save request
@example
var user = Kii.getCurrentUser(); // a KiiUser
user.save({
success: function(theSavedUser) {
// do something with the saved user
},
failure: function(theUser, anErrorString) {
// do something with the error response
}
});
*/
KiiUser.prototype.save = function(callbacks) {
var data, path, request, updateCallbacks,
_this = this;
_thisUser = this;
Kii.logger("Saving user: " + this._uuid);
path = "/users/" + this._uuid;
Kii.logger("CUSTOMINFO: ");
Kii.logger(this._customInfo);
request = new KiiRequest(path, true);
request.setMethod("POST");
request.setContentType("application/vnd.kii.UserUpdateRequest+json");
data = this._customInfo;
if (this._country != null) {
data.country = this._country;
}
if (this._displayName != null) {
data.displayName = this._displayName;
}
request.setData(data);
updateCallbacks = {
success: function(data, statusCode) {
if (statusCode < 300 && statusCode >= 200) {
_thisUser._setModified(data.modifiedAt);
if (callbacks != null) {
return callbacks.success(_thisUser);
}
} else if (callbacks != null) {
return callbacks.failure(_thisUser, "Unable to parse response");
}
},
failure: function(error, statusCode) {
if (callbacks != null) {
return callbacks.failure(_thisUser, error);
}
}
};
return request.execute(updateCallbacks, false);
};
/** Updates the local user's data with the user data on the server
<br><br>The user must exist on the server. Local data will be overwritten.
@param {Object} callbacks An object with callback methods defined
@param {Method} callbacks.success The callback method to call on a successful refresh request
@param {Method} callbacks.failure The callback method to call on a failed refresh request
@example
var user = Kii.getCurrentUser(); // a KiiUser
user.refresh({
success: function(theRefreshedUser) {
// do something with the refreshed user
},
failure: function(theUser, anErrorString) {
// do something with the error response
}
});
*/
KiiUser.prototype.refresh = function(callbacks) {
var refreshCallbacks, request,
_this = this;
_thisUser = this;
Kii.logger("Refreshing user: " + this._uuid);
request = new KiiRequest("/users/" + this._uuid, true);
refreshCallbacks = {
success: function(data, statusCode) {
if (statusCode < 300 && statusCode >= 200) {
_thisUser._updateWithJSON(data);
if (callbacks != null) {
return callbacks.success(_thisUser);
}
} else if (callbacks != null) {
return callbacks.failure(_thisUser, "Unable to parse response");
}
},
failure: function(error, statusCode) {
if (callbacks != null) {
return callbacks.failure(_thisUser, error);
}
}
};
return request.execute(refreshCallbacks, false);
};
/** Delete the user from the server
@param {Object} callbacks An object with callback methods defined
@param {Method} callbacks.success The callback method to call on a successful delete request
@param {Method} callbacks.failure The callback method to call on a failed delete request
@example
var user = Kii.getCurrentUser(); // a KiiUser
obj.delete({
success: function(theDeletedUser) {
// do something
},
failure: function(theUser, anErrorString) {
// do something with the error response
}
});
*/
KiiUser.prototype["delete"] = function(callbacks) {
var refreshCallbacks, request,
_this = this;
Kii.logger("Deleting user...");
_thisUser = this;
request = new KiiRequest("/users/" + this._uuid, true);
request.setMethod("DELETE");
refreshCallbacks = {
success: function(data, statusCode) {
if (statusCode < 300 && statusCode >= 200 && (callbacks != null)) {
return callbacks.success(_thisUser);
} else if (callbacks != null) {
return callbacks.failure(_thisUser, "Unable to parse response");
}
},
failure: function(error, statusCode) {
if (callbacks != null) {
return callbacks.failure(_thisUser, error);
}
}
};
return request.execute(refreshCallbacks, true);
};
/**
Logs the currently logged-in user out of the KiiSDK
@example
KiiUser.logOut();
*/
KiiUser.logOut = function() {
return Kii.logOut();
};
/**
Checks to see if there is a user authenticated with the SDK
@example
if(KiiUser.loggedIn()) {
// do something
}
*/
KiiUser.loggedIn = function() {
return Kii.loggedIn();
};
/**
Retrieves the currently logged-in user
@example
KiiUser.getCurrentUser();
*/
KiiUser.getCurrentUser = function() {
return Kii.getCurrentUser();
};
KiiUser.prototype._updateWithJSON = function(json) {
var key, value;
Kii.logger("Updating with:");
Kii.logger(json);
for (key in json) {
value = json[key];
Kii.logger("key/val => " + key + "/" + value);
Kii.logger("Substr " + (key.substring(0, 1)));
if (key === "userID" || key === "id") {
this._uuid = value;
} else if (key === "created" || key === "createdAt" || key === "_created") {
this._created = value;
} else if (key === "modified" || key === "modifiedAt" || key === "_modified") {
this._modified = value;
} else if (key === "loginName") {
this._username = value;
} else if (key === "displayName") {
this._displayName = value;
} else if (key === "country") {
Kii.logger("Is setting country");
this._country = value;
} else if (key === "emailAddress") {
this._emailAddress = value;
} else if (key === "phoneNumber") {
this._phoneNumber = value;
} else if (key === "emailAddressVerified") {
this._emailAddressVerified = value;
} else if (key === "phoneNumberVerified") {
this._phoneNumberVerified = value;
} else if (key === "") {
Kii.logger("Setting empty to custom info");
this._customInfo[key] = value;
} else if (key.substring(0, 1 !== "_")) {
Kii.logger("Setting to custom info");
this._customInfo[key] = value;
} else {
Kii.logger("Doing nothing");
}
}
if (!(this._displayName != null) && (this._username != null)) {
return this._displayName = this._username;
}
};
return KiiUser;
}).call(this);
KiiUtilities = (function() {
function KiiUtilities() {}
KiiUtilities.getObjectClass = function(obj) {
var arr;
if (obj && obj.constructor && obj.constructor.toString) {
arr = obj.constructor.toString().match(/function\s*(\w+)/);
if (arr && arr.length === 2) {
return arr[1];
}
}
return void 0;
};
KiiUtilities.arrayRemove = function(array, from, to) {
var rest;
rest = array.slice(((to || from) + 1) || array.length);
array.length = from < 0 ? array.length + from : from;
return array.push.apply(array, rest);
};
KiiUtilities._validateEmail = function(value) {
var pattern;
value = $.trim(value);
pattern = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,6}$/i;
if ((typeof value).toLowerCase() !== "string") {
Kii.logger("Not string");
return false;
} else if (value.match(pattern)) {
return true;
} else {
return false;
}
};
KiiUtilities._validatePhoneNumber = function(value) {
var pattern;
value = $.trim(value);
pattern = /^[\\+]+[0-9]{10,}$/i;
if ((typeof value).toLowerCase() !== "string") {
Kii.logger("Not string");
return false;
} else if (value.match(pattern)) {
return true;
} else {
return false;
}
};
KiiUtilities._validateCountryCode = function(value) {
var pattern;
value = $.trim(value);
pattern = /^[a-z]{2}$/i;
if ((typeof value).toLowerCase() !== "string") {
Kii.logger("Not string");
return false;
} else if (value.match(pattern)) {
Kii.logger("Is true");
return true;
} else {
return false;
}
};
KiiUtilities._validatePassword = function(value) {
var pattern;
Kii.logger("Validating password: " + value);
pattern = /^[A-Za-z0-9\\@\\#\\$\\%\\^\\&]{4,}$/i;
if ((typeof value).toLowerCase() !== "string") {
Kii.logger("not string");
return false;
} else if (value.match(pattern)) {
Kii.logger("matched");
return true;
} else {
Kii.logger("other exception");
return false;
}
};
KiiUtilities._validateUsername = function(value) {
var pattern;
pattern = /^[a-zA-Z0-9-_\\.]{3,64}$/i;
if ((typeof value).toLowerCase() !== "string") {
return false;
} else if (value.match(pattern)) {
return true;
} else {
return false;
}
};
return KiiUtilities;
}).call(this);
/**
@class Represents a KiiSocialConnect object
@exports root.KiiACL as KiiACL
*/
root.KiiSocialConnect = (function() {
var _instance;
function KiiSocialConnect() {}
_instance = null;
/** Set up a reference to one of the supported KiiSocialNetworks.
The user will not be authenticated or linked to a KiiUser
until one of those methods are called explicitly.
@param {KiiSocialNetworkName} networkName One of the supported KiiSocialNetworkName values
@param {String} apiKey The SDK key assigned by the social network provider
@param {String} apiSecret The SDK secret assigned by the social network provider
@param {Object} extras Extra options that should be passed to the SNS. Examples could be (Facebook) a dictionary of permissions to grant to the authenticated user.
*/
KiiSocialConnect.setupNetwork = function(networkName, apiKey, apiSecret, extras) {
var manager;
if (_instance == null) {
_instance = new _KiiSocialConnect;
}
manager = _instance._getManager(networkName);
manager._reset();
manager._setup(apiKey, apiSecret, extras);
return Kii.logger("Set key: " + manager._key);
};
/** Log a user into the social network provided
This will initiate the login process for the given network. If a KiiUser has already been authenticated, this will authenticate and link the user to the network. Otherwise, this will generate a KiiUser that is automatically linked to the social network. The network must already be set up via setupNetwork
@param networkName One of the supported KiiSocialNetworkName values
@param options A dictionary of key/values to pass to KiiSocialConnect
@param {Object} callbacks An object with callback methods defined
@param {Method} callbacks.success The callback method to call on a successful log in request
@param {Method} callbacks.failure The callback method to call on a failed log in request
@example
KiiSocialConnect.logIn(KiiSocialNetworkName.FACEBOOK, {
success: function(user, network) {
// do something now that the user is logged in
},
failure: function(user, network, anErrorString) {
// do something with the error response
}
});
*/
KiiSocialConnect.logIn = function(networkName, options, callbacks) {
var called;
called = false;
if (_instance != null) {
Kii.logger("And manager: ");
Kii.logger(_instance._getManager(networkName));
if (_instance._getManager(networkName)) {
_instance._getManager(networkName)._logIn(options, callbacks);
called = true;
}
}
Kii.logger("Callbacks");
Kii.logger(callbacks);
if (!called && (callbacks != null)) {
return callbacks.failure(KiiUser.getCurrentUser(), networkName, "Unable to get network. Please ensure the network name is one of the supported KiiSocialNetworkName values");
}
};
/** Link the currently logged in user with a social network
This will initiate the login process for the given network, which for SSO-enabled services like Facebook, will send the user to the Facebook site for authentication. There must be a currently authenticated KiiUser. Otherwise, you can use the logIn: method to create and log in a KiiUser using a network. The network must already be set up via setupNetwork
@param networkName One of the supported KiiSocialNetworkName values
@param options A dictionary of key/values to pass to KiiSocialConnect
@param {Object} callbacks An object with callback methods defined
@param {Method} callbacks.success The callback method to call on a successful log in request
@param {Method} callbacks.failure The callback method to call on a failed log in request
@example
KiiSocialConnect.linkCurrentUserWithNetwork(KiiSocialNetworkName.FACEBOOK, {
success: function(user, network) {
// do something now that the user is linked
},
failure: function(user, network, anErrorString) {
// do something with the error response
}
});
*/
KiiSocialConnect.linkCurrentUserWithNetwork = function(networkName, options, callbacks) {
var called;
Kii.logger("Trying with instance");
Kii.logger(_instance);
called = false;
if (_instance != null) {
Kii.logger("And manager: ");
Kii.logger(_instance._getManager(networkName));
if (_instance._getManager(networkName)) {
_instance._getManager(networkName)._linkWithCurrentUser(options, callbacks);
called = true;
}
}
Kii.logger("Callbacks");
Kii.logger(callbacks);
if (!called && (callbacks != null)) {
return callbacks.failure(KiiUser.getCurrentUser(), networkName, "Unable to get network. Please ensure the network name is one of the supported KiiSocialNetworkName values");
}
};
/** Unlink the currently logged in user with a social network
The network must already be set up via setupNetwork
@param networkName One of the supported KiiSocialNetworkName values
@param {Object} callbacks An object with callback methods defined
@param {Method} callbacks.success The callback method to call on a successful log in request
@param {Method} callbacks.failure The callback method to call on a failed log in request
@example
KiiSocialConnect.unLinkCurrentUserFromNetwork(KiiSocialNetworkName.FACEBOOK, {
success: function(user, network) {
// do something now that the user is unlinked
},
failure: function(user, network, anErrorString) {
// do something with the error response
}
});
*/
KiiSocialConnect.unLinkCurrentUserFromNetwork = function(networkName, callbacks) {
var called;
Kii.logger("Trying with instance");
Kii.logger(_instance);
called = false;
if (_instance != null) {
Kii.logger("And manager: ");
Kii.logger(_instance._getManager(networkName));
if (_instance._getManager(networkName)) {
_instance._getManager(networkName)._unlinkFromCurrentUser(callbacks);
called = true;
}
}
Kii.logger("Callbacks");
Kii.logger(callbacks);
if (!called && (callbacks != null)) {
return callbacks.failure(KiiUser.getCurrentUser(), networkName, "Unable to get network. Please ensure the network name is one of the supported KiiSocialNetworkName values");
}
};
/** Retrieve the current user's access token from a social network
The network must be set up and linked to the current user. It is recommended you save this to preferences for multi-session use.
@param networkName One of the supported KiiSocialNetworkName values
@returns {String} The current access token, null if unavailable
*/
KiiSocialConnect.getAccessTokenForNetwork = function(networkName) {
return _instance._getManager(networkName)._getToken();
};
/** Retrieve the current user's access token expiration date from a social network
The network must be set up and linked to the current user. It is recommended you save this to preferences for multi-session use.
@param networkName One of the supported KiiSocialNetworkName values
@returns {String} The current access token expiration date, null if unavailable
*/
KiiSocialConnect.getAccessTokenExpirationForNetwork = function(networkName) {
return _instance._getManager(networkName)._getTokenExpiration();
};
return KiiSocialConnect;
}).call(this);
_KiiSocialConnect = (function() {
var _facebookManager;
function _KiiSocialConnect() {
this._getManager = __bind(this._getManager, this);
}
_facebookManager = null;
_KiiSocialConnect.prototype._getManager = function(networkName) {
if (networkName === KiiSocialNetworkName.FACEBOOK) {
if (this._facebookManager != null) {
return this._facebookManager;
} else {
return this._facebookManager = new KiiSCNFacebook();
}
}
};
return _KiiSocialConnect;
})();
root.KiiSocialConnectNetwork = (function() {
var _callbacks, _extras, _key, _network, _secret, _token, _tokenExpiration;
KiiSocialConnectNetwork.prototype._className = "KiiSocialConnectNetwork";
_network = null;
_key = null;
_secret = null;
_extras = null;
_token = null;
_tokenExpiration = null;
_callbacks = null;
KiiSocialConnectNetwork.prototype._setNetwork = function(_network) {
this._network = _network;
};
KiiSocialConnectNetwork.prototype._getNetwork = function() {
return this._network;
};
KiiSocialConnectNetwork.prototype._setKey = function(_key) {
this._key = _key;
};
KiiSocialConnectNetwork.prototype._getKey = function() {
return this._key;
};
KiiSocialConnectNetwork.prototype._setSecret = function(_secret) {
this._secret = _secret;
};
KiiSocialConnectNetwork.prototype._getSecret = function() {
return this._secret;
};
KiiSocialConnectNetwork.prototype._setExtras = function(_extras) {
this._extras = _extras;
};
KiiSocialConnectNetwork.prototype._getExtras = function() {
return this._extras;
};
KiiSocialConnectNetwork.prototype._setToken = function(_token) {
this._token = _token;
};
KiiSocialConnectNetwork.prototype._getToken = function() {
return this._token;
};
KiiSocialConnectNetwork.prototype._setTokenExpiration = function(_tokenExpiration) {
this._tokenExpiration = _tokenExpiration;
};
KiiSocialConnectNetwork.prototype._getTokenExpiration = function() {
return this._tokenExpiration;
};
KiiSocialConnectNetwork.prototype._setCallbacks = function(_callbacks) {
this._callbacks = _callbacks;
};
KiiSocialConnectNetwork.prototype._getCallbacks = function() {
return this._callbacks;
};
function KiiSocialConnectNetwork(_network) {
this._network = _network;
this._setup = __bind(this._setup, this);
this._unlinkFromCurrentUser = __bind(this._unlinkFromCurrentUser, this);
this._linkWithCurrentUser = __bind(this._linkWithCurrentUser, this);
this._logOut = __bind(this._logOut, this);
this._logIn = __bind(this._logIn, this);
this._reset = __bind(this._reset, this);
this._isAuthenticated = __bind(this._isAuthenticated, this);
this._getCallbacks = __bind(this._getCallbacks, this);
this._setCallbacks = __bind(this._setCallbacks, this);
this._getTokenExpiration = __bind(this._getTokenExpiration, this);
this._setTokenExpiration = __bind(this._setTokenExpiration, this);
this._getToken = __bind(this._getToken, this);
this._setToken = __bind(this._setToken, this);
this._getExtras = __bind(this._getExtras, this);
this._setExtras = __bind(this._setExtras, this);
this._getSecret = __bind(this._getSecret, this);
this._setSecret = __bind(this._setSecret, this);
this._getKey = __bind(this._getKey, this);
this._setKey = __bind(this._setKey, this);
this._getNetwork = __bind(this._getNetwork, this);
this._setNetwork = __bind(this._setNetwork, this);
}
KiiSocialConnectNetwork.prototype._isAuthenticated = function() {
return this._token != null;
};
KiiSocialConnectNetwork.prototype._reset = function() {
this._token = null;
this._tokenExpiration = null;
this._key = null;
this._secret = null;
return this._extras = null;
};
KiiSocialConnectNetwork.prototype._logIn = function(options, _callbacks) {
this._callbacks = _callbacks;
};
KiiSocialConnectNetwork.prototype._logOut = function() {};
KiiSocialConnectNetwork.prototype._linkWithCurrentUser = function(options, _callbacks) {
this._callbacks = _callbacks;
};
KiiSocialConnectNetwork.prototype._unlinkFromCurrentUser = function(_callbacks) {
this._callbacks = _callbacks;
};
KiiSocialConnectNetwork.prototype._setup = function(_key, _secret, _extras) {
this._key = _key;
this._secret = _secret;
this._extras = _extras;
};
return KiiSocialConnectNetwork;
})();
root.KiiSCNFacebook = (function(_super) {
var _authWindow;
__extends(KiiSCNFacebook, _super);
_authWindow = null;
function KiiSCNFacebook() {
this._unlinkFromCurrentUser = __bind(this._unlinkFromCurrentUser, this);
this._linkWithCurrentUser = __bind(this._linkWithCurrentUser, this);
this._logOut = __bind(this._logOut, this);
this._logIn = __bind(this._logIn, this);
this._unlink = __bind(this._unlink, this);
this._link = __bind(this._link, this);
this._register = __bind(this._register, this);
this._setup = __bind(this._setup, this);
KiiSCNFacebook.__super__.constructor.call(this, KiiSocialNetworkName.FACEBOOK);
}
KiiSCNFacebook.prototype._setup = function(_key, _secret, _extras) {
this._key = _key;
this._secret = _secret;
this._extras = _extras;
KiiSCNFacebook.__super__._setup.call(this, this._key, this._secret, this._extras);
this._extras.appId = this._key;
Kii.logger(this._extras);
return FB.init(this._extras);
};
KiiSCNFacebook.prototype._register = function(token, expires) {
var registrationCallbacks, request,
_this = this;
_this = this;
request = new KiiRequest("/integration/facebook", true);
request.setMethod("POST");
request.setData({
accessToken: token
});
request.setAnonymous(true);
request.setContentType("application/vnd.kii.AuthTokenFacebookRequest+json");
registrationCallbacks = {
success: function(data) {
var user;
_this._setToken(token);
_this._setTokenExpiration(expires);
user = new KiiUser();
user._updateWithJSON(data);
user._setAccessToken(data['access_token']);
Kii.setCurrentUser(user);
if (_this._callbacks != null) {
return _this._callbacks.success(KiiUser.getCurrentUser(), _this._network);
}
},
failure: function(error, statusCode) {
if (_this._callbacks != null) {
return _this._callbacks.failure(null, _this._network, error);
}
}
};
return request.execute(registrationCallbacks, false);
};
KiiSCNFacebook.prototype._link = function(token, expires) {
var linkCallbacks, request,
_this = this;
_this = this;
request = new KiiRequest("/users/me/facebook/link", true);
request.setMethod("POST");
request.setData({
accessToken: token
});
linkCallbacks = {
success: function(data) {
_this._setToken(token);
_this._setTokenExpiration(expires);
if (_this._callbacks != null) {
return _this._callbacks.success(KiiUser.getCurrentUser(), _this._network);
}
},
failure: function(error, statusCode) {
if (_this._callbacks != null) {
return _this._callbacks.failure(KiiUser.getCurrentUser(), _this._network, error);
}
}
};
return request.execute(linkCallbacks, true);
};
KiiSCNFacebook.prototype._unlink = function() {
var request, unlinkCallbacks,
_this = this;
_this = this;
request = new KiiRequest("/users/me/facebook/unlink", true);
request.setMethod("POST");
unlinkCallbacks = {
success: function(data) {
if (_this._callbacks != null) {
return _this._callbacks.success(KiiUser.getCurrentUser(), _this._network);
}
},
failure: function(error, statusCode) {
if (_this._callbacks != null) {
return _this._callbacks.failure(KiiUser.getCurrentUser(), _this._network, error);
}
}
};
return request.execute(unlinkCallbacks, true);
};
KiiSCNFacebook.prototype._logIn = function(options, callbacks) {
var _this = this;
KiiSCNFacebook.__super__._logIn.call(this, options, callbacks);
Kii.logger("should auth fb");
_this = this;
Kii.logger("Checking options");
Kii.logger(options);
if ((options != null) && (options.access_token != null) && (options.access_token_expires != null)) {
Kii.logger("Have options: ");
Kii.logger(options);
if (KiiUser.getCurrentUser() != null) {
return _this._link(options.access_token, options.access_token_expires);
} else {
return _this._register(options.access_token, options.access_token_expires);
}
} else {
return FB.login(function(response) {
if (response.authResponse != null) {
if (KiiUser.getCurrentUser() != null) {
return _this._link(response.authResponse.accessToken, response.authResponse.expiresIn);
} else {
return _this._register(response.authResponse.accessToken, response.authResponse.expiresIn);
}
} else {
if (_this._callbacks != null) {
return _this._callbacks.failure(null, _this._network, "User cancelled login or did not fully authorize");
}
}
});
}
};
KiiSCNFacebook.prototype._logOut = function() {
KiiSCNFacebook.__super__._logOut.apply(this, arguments);
return Kii.logger("Log out fb");
};
KiiSCNFacebook.prototype._linkWithCurrentUser = function(options, callbacks) {
var _this = this;
KiiSCNFacebook.__super__._linkWithCurrentUser.call(this, options, callbacks);
_this = this;
if (KiiUser.getCurrentUser() != null) {
if ((options != null) && (options.access_token != null) && (options.access_token_expires != null)) {
return _this._link(options.access_token, options.access_token_expires);
} else {
return FB.login(function(response) {
if (response.authResponse) {
return _this._link(response.authResponse.accessToken, response.authResponse.expiresIn);
} else if (_this._callbacks != null) {
return _this._callbacks.failure(null, _this._network, "User cancelled Facebook login or did not fully authorize");
}
});
}
} else if (callbacks != null) {
return callbacks.failure("A KiiUser must be logged in before linking to Facebook");
}
};
KiiSCNFacebook.prototype._unlinkFromCurrentUser = function(callbacks) {
KiiSCNFacebook.__super__._unlinkFromCurrentUser.call(this, callbacks);
if (KiiUser.getCurrentUser() != null) {
return this._unlink();
} else if (callbacks != null) {
return callbacks.failure("A KiiUser must be logged in before unlinking from Facebook");
}
};
return KiiSCNFacebook;
})(root.KiiSocialConnectNetwork);
root.InvalidDisplayNameException = function() {
return this.message = "Unable to set displayName. Must be between 4-50 alphanumeric characters, must start with a letter";
};
root.InvalidPasswordException = function() {
return this.message = "Unable to set password. Must be at least 4 characters, made up of alphanumeric and/or: @,#,$,%,^,&";
};
root.InvalidUsernameException = function() {
return this.message = "Unable to set username. Must be between 3 and 64 characters, which can include alphanumeric characters as well as underscores '_' and periods '.'";
};
root.InvalidEmailException = function() {
return this.message = "Unable to set email address. Must be a valid email";
};
root.InvalidPhoneNumberException = function() {
return this.message = "Unable to set phone number. Must begin with a '+' and be at least 10 digits";
};
root.InvalidCountryException = function() {
return _this.message = "Unable to set country code. Must be 2 alphabetic characters. Ex: US, JP, CN";
};
root.InvalidURIException = function() {
return _this.message = "Unable to set URI. Must be of the form kiicloud://some/path/to/object/or/entity";
};
root.InvalidACLAction = function() {
return _this.message = "Unable to set ACL action. Must be one of the permitted values in KiiACLAction";
};
root.InvalidACLSubject = function() {
return _this.message = "Unable to set ACL subject. Must be of type KiiUser or KiiGroup";
};
root.InvalidACLGrant = function() {
return _this.message = "Unable to set ACL grant. Must be a boolean type";
};
root.InvalidLimitException = function() {
return _this.message = "Unable to set query limit. Must be an integer > 0";
};
/**
@class Represent any authenticated user for setting the ACL of an object. This will include anyone using the application who has registered and authenticated in the current session.
When retrieving ACL from an object, test for this class to determine the subject type. Example:
if(acl.subject typeof KiiAnyAuthenticatedUser) {
// the ACL is set for any authenticated users
}
@exports root.KiiAnyAuthenticatedUser as KiiAnyAuthenticatedUser
*/
root.KiiAnyAuthenticatedUser = (function() {
function KiiAnyAuthenticatedUser() {}
return KiiAnyAuthenticatedUser;
})();
/**
@class Represent an anonymous user for setting the ACL of an object. This will include anyone using the application but have not signed up or authenticated as registered user.
When retrieving ACL from an object, test for this class to determine the subject type. Example:
if(acl.subject typeof KiiAnonymousUser) {
// the ACL is set for anonymous users
}
@exports root.KiiAnonymousUser as KiiAnonymousUser
*/
root.KiiAnonymousUser = (function() {
function KiiAnonymousUser() {}
return KiiAnonymousUser;
})();
}).call(this);
| KiiCorp/HelloKii-JavaScript | KiiSDKv2.1.1.js | JavaScript | apache-2.0 | 154,833 |
/* React Tutorial Example
- Completed following the tutorial provided by Facebook and the React.js
documentation. Includes only the public javascript and not the server or json */
var data = [
{ id: 1, author: "Pete Hunt", text: "This is one comment." },
{ id: 2, author: "Jordan Walke", text: "This is *another* comment."}
];
var CommentBox = React.createClass({ displayName: "CommentBox",
loadCommentsFromServer: function loadCommentsFromServer() {
$.ajax({
url: this.props.url,
dataType: "json",
cache: false,
success: function getDataSuccess(data) {
this.setState({ data: data });
}.bind(this),
error: function getDataError(xhr, status, error) {
console.error(this.props.url, status, error.toString());
}.bind(this)
});
},
//parent function to handle the form's submit event
handleCommentSubmit: function handleCommentSubmit(comment) {
var comments = this.state.data;
// Optimistically set an id on the new comment. It will be replaced by an
// id generated by the server. In a production application you would likely
// not use Date.now() for this and would have a more robust system in place.
comment.id = Date.now();
var newComments = comments.concat([comment]);
this.setState({ data: newComments });
$.ajax({
url: this.props.url,
type: "POST",
data: comment,
success: function submitCommentSuccess(data) {
this.setState({ data: data });
}.bind(this),
error: function submitCommentError(xhr, status, error) {
console.error(this.props.url, status, error.toString());
}.bind(this)
});
},
getInitialState: function getInitialState() {
return { data: [] };
},
/* called automatically by React after a component is rendered the first time
polls the server for live updates via the loadCommentsFromServer function at an
interval specified in the initial render property */
componentDidMount: function componentDidMount() {
this.loadCommentsFromServer();
setInterval(this.loadCommentsFromServer, this.props.pollInterval);
},
render: function render() {
return (
React.createElement("div", { className: "commentBox" },
React.createElement("h1", null, "Comments"),
React.createElement(CommentList, { data: this.state.data }),
React.createElement(CommentForm, { onCommentSubmit: this.handleCommentSubmit })
)
);
}
});
var CommentList = React.createClass({ displayName: "CommentList",
render: function render() {
var commentNodes = this.props.data.map(function(comment) {
return (
React.createElement(Comment, { author: comment.author, key: comment.id }, comment.text)
);
});
return (
React.createElement("div", { className: "commentList" }, commentNodes)
);
}
});
var CommentForm = React.createClass({ displayName: "CommentForm",
getInitialState: function getInitialState() {
return { author: "", text: "" };
},
handleAuthorChange: function handleAuthorChange(event) {
this.setState({ author: event.target.value });
},
handleTextChange: function handleAuthorChange(event) {
this.setState({ text: event.target.value });
},
handleSubmit: function handleSubmit(event) {
event.preventDefault();
var author = this.state.author.trim();
var text = this.state.text.trim();
if(!text || !author) {
return;
}
this.props.onCommentSubmit({ author: author, text: text });
this.setState({ author: "", text: "" });
},
render: function render() {
return (
React.createElement("form", { className: "commentForm", onSubmit: this.handleSubmit },
React.createElement("input", { type: "text", placeholder: "Your name", value: this.state.author, onChange: this.handleAuthorChange }),
React.createElement("input", { type: "text", placeholder: "Say something...", value: this.state.text, onChange: this.handleTextChange }),
React.createElement("input", { type: "submit", value: "Post". onCh })
)
);
}
});
var Comment = React.createClass({
rawMarkup: function rawMarkup() {
var rawMarkup = marked(this.props.children.toString(), { sanitize: true });
return { __html: rawMarkup };
},
render: function render() {
return (
React.createElement("div", { className: "comment" },
React.createElement("h2", { className: "commentAuthor" }, this.props.author),
React.createElement("span", { dangerouslySetInnerHTML: this.rawMarkup() })
)
);
}
});
ReactDOM.render(React.createElement(CommentBox, { url: "/api/comments", pollInterval: 2000 }), document.getElementById("content"));
| masharp/portfolio-apps | frameworks-and-databases/ReactExample/example.js | JavaScript | apache-2.0 | 4,724 |
/**
* Copyright (c) 2012-2017 Netflix, 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.
*/
/**
* Unauthenticated entity authentication data unit tests.
*
* @author Wesley Miaw <[email protected]>
*/
describe("UnauthenticatedAuthenticationData", function() {
var MslEncoderFormat = require('msl-core/io/MslEncoderFormat.js');
var EntityAuthenticationScheme = require('msl-core/entityauth/EntityAuthenticationScheme.js');
var UnauthenticatedAuthenticationData = require('msl-core/entityauth/UnauthenticatedAuthenticationData.js');
var EntityAuthenticationData = require('msl-core/entityauth/EntityAuthenticationData.js');
var MslEncodingException = require('msl-core/MslEncodingException.js');
var MslError = require('msl-core/MslError.js');
var MslTestConstants = require('msl-tests/MslTestConstants.js');
var MockMslContext = require('msl-tests/util/MockMslContext.js');
var MslTestUtils = require('msl-tests/util/MslTestUtils.js');
/** MSL encoder format. */
var ENCODER_FORMAT = MslEncoderFormat.JSON;
/** Key entity authentication scheme. */
var KEY_SCHEME = "scheme";
/** Key entity authentication data. */
var KEY_AUTHDATA = "authdata";
/** Key entity identity. */
var KEY_IDENTITY = "identity";
var IDENTITY = "identity";
/** MSL context. */
var ctx;
/** MSL encoder factory. */
var encoder;
var initialized = false;
beforeEach(function() {
if (!initialized) {
runs(function() {
MockMslContext.create(EntityAuthenticationScheme.X509, false, {
result: function(c) { ctx = c; },
error: function(e) { expect(function() { throw e; }).not.toThrow(); }
});
});
waitsFor(function() { return ctx; }, "ctx", MslTestConstants.TIMEOUT_CTX);
runs(function() {
encoder = ctx.getMslEncoderFactory();
initialized = true;
});
}
});
it("ctors", function() {
var data = new UnauthenticatedAuthenticationData(IDENTITY);
expect(data.getIdentity()).toEqual(IDENTITY);
expect(data.scheme).toEqual(EntityAuthenticationScheme.NONE);
var authdata;
runs(function() {
data.getAuthData(encoder, ENCODER_FORMAT, {
result: function(x) { authdata = x; },
error: function(e) { expect(function() { throw e; }).not.toThrow(); },
});
});
waitsFor(function() { return authdata; }, "authdata", MslTestConstants.TIMEOUT);
var encode;
runs(function() {
expect(authdata).not.toBeNull();
data.toMslEncoding(encoder, ENCODER_FORMAT, {
result: function(x) { encode = x; },
error: function(e) { expect(function() { throw e; }).not.toThrow(); }
});
});
waitsFor(function() { return encode; }, "encode", MslTestConstants.TIMEOUT);
var moData, moAuthdata;
runs(function() {
expect(encode).not.toBeNull();
moData = UnauthenticatedAuthenticationData.parse(authdata);
expect(moData.getIdentity()).toEqual(data.getIdentity());
expect(moData.scheme).toEqual(data.scheme);
moData.getAuthData(encoder, ENCODER_FORMAT, {
result: function(x) { moAuthdata = x; },
error: function(e) { expect(function() { throw e; }).not.toThrow(); }
});
});
waitsFor(function() { return moAuthdata; }, "moAuthdata", MslTestConstants.TIMEOUT);
var moEncode;
runs(function() {
expect(moAuthdata).not.toBeNull();
expect(moAuthdata).toEqual(authdata);
moData.toMslEncoding(encoder, ENCODER_FORMAT, {
result: function(x) { moEncode = x; },
error: function(e) { expect(function() { throw e; }).not.toThrow(); }
});
});
waitsFor(function() { return moEncode; }, "moEncode", MslTestConstants.TIMEOUT);
runs(function() {
expect(moEncode).not.toBeNull();
expect(moEncode).toEqual(encode);
});
});
it("mslobject is correct", function() {
var data = new UnauthenticatedAuthenticationData(IDENTITY);
var mo;
runs(function() {
MslTestUtils.toMslObject(encoder, data, {
result: function(x) { mo = x; },
error: function(e) { expect(function() { throw e; }).not.toThrow(); }
});
});
waitsFor(function() { return mo; }, "mo", MslTestConstants.TIMEOUT);
runs(function() {
expect(mo.getString(KEY_SCHEME)).toEqual(EntityAuthenticationScheme.NONE.name);
var authdata = mo.getMslObject(KEY_AUTHDATA, encoder);
expect(authdata.getString(KEY_IDENTITY)).toEqual(IDENTITY);
});
});
it("create", function() {
var data = new UnauthenticatedAuthenticationData(IDENTITY);
var encode;
runs(function() {
data.toMslEncoding(encoder, ENCODER_FORMAT, {
result: function(x) { encode = x; },
error: function(e) { expect(function() { throw e; }).not.toThrow(); }
});
});
waitsFor(function() { return encode; }, "encode", MslTestConstants.TIMEOUT);
var mo;
runs(function() {
MslTestUtils.toMslObject(encoder, data, {
result: function(x) { mo = x; },
error: function(e) { expect(function() { throw e; }).not.toThrow(); }
});
});
waitsFor(function() { return mo; }, "mo", MslTestConstants.TIMEOUT);
var entitydata;
runs(function() {
EntityAuthenticationData.parse(ctx, mo, {
result: function(x) { entitydata = x; },
error: function(e) { expect(function() { throw e; }).not.toThrow(); },
});
});
waitsFor(function() { return entitydata; }, "entitydata", MslTestConstants.TIMEOUT);
var moData, moAuthdata;
runs(function() {
expect(entitydata).not.toBeNull();
expect(entitydata instanceof UnauthenticatedAuthenticationData).toBeTruthy();
moData = entitydata;
expect(moData.getIdentity()).toEqual(data.getIdentity());
expect(moData.scheme).toEqual(data.scheme);
moData.getAuthData(encoder, ENCODER_FORMAT, {
result: function(x) { moAuthdata = x; },
error: function(e) { expect(function() { throw e; }).not.toThrow(); }
});
});
waitsFor(function() { return moAuthdata; }, "moAuthdata", MslTestConstants.TIMEOUT);
var authdata;
runs(function() {
data.getAuthData(encoder, ENCODER_FORMAT, {
result: function(x) { authdata = x; },
error: function(e) { expect(function() { throw e; }).not.toThrow(); },
});
});
waitsFor(function() { return authdata; }, "authdata", MslTestConstants.TIMEOUT);
var moEncode;
runs(function() {
expect(moAuthdata).not.toBeNull();
expect(moAuthdata).toEqual(authdata);
moData.toMslEncoding(encoder, ENCODER_FORMAT, {
result: function(x) { moEncode = x; },
error: function(e) { expect(function() { throw e; }).not.toThrow(); }
});
});
waitsFor(function() { return moEncode; }, "moEncode", MslTestConstants.TIMEOUT);
runs(function() {
expect(moEncode).not.toBeNull();
expect(moEncode).toEqual(encode);
});
});
it("missing identity", function() {
var authdata;
runs(function() {
var data = new UnauthenticatedAuthenticationData(IDENTITY);
data.getAuthData(encoder, ENCODER_FORMAT, {
result: function(x) { authdata = x; },
error: function(e) { expect(function() { throw e; }).not.toThrow(); },
});
});
waitsFor(function() { return authdata; }, "authdata", MslTestConstants.TIMEOUT);
runs(function() {
authdata.remove(KEY_IDENTITY);
var f = function() {
UnauthenticatedAuthenticationData.parse(authdata);
};
expect(f).toThrow(new MslEncodingException(MslError.MSL_PARSE_ERROR));
});
});
it("equals identity", function() {
var dataA, dataB, dataA2;
runs(function() {
var identityA = IDENTITY + "A";
var identityB = IDENTITY + "B";
dataA = new UnauthenticatedAuthenticationData(identityA);
dataB = new UnauthenticatedAuthenticationData(identityB);
MslTestUtils.toMslObject(encoder, dataA, {
result: function(mo) {
EntityAuthenticationData.parse(ctx, mo, {
result: function(x) { dataA2 = x; },
error: function(e) { expect(function() { throw e; }).not.toThrow(); }
});
},
error: function(e) { expect(function() { throw e; }).not.toThrow(); }
});
});
waitsFor(function() { return dataA && dataB && dataA2; }, "data", MslTestConstants.TIMEOUT);
runs(function() {
expect(dataA.equals(dataA)).toBeTruthy();
expect(dataA.equals(dataB)).toBeFalsy();
expect(dataB.equals(dataA)).toBeFalsy();
expect(dataA.equals(dataA2)).toBeTruthy();
expect(dataA2.equals(dataA)).toBeTruthy();
});
});
it("equals object", function() {
var data = new UnauthenticatedAuthenticationData(IDENTITY);
expect(data.equals(null)).toBeFalsy();
expect(data.equals(KEY_IDENTITY)).toBeFalsy();
});
});
| Netflix/msl | tests/src/test/javascript/entityauth/UnauthenticatedAuthenticationDataTest.js | JavaScript | apache-2.0 | 10,664 |
'use strict';
describe('Controller: Chapter13Ctrl', function () {
// load the controller's module
beforeEach(module('angularJsProApp'));
var Chapter13Ctrl,
scope;
// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
Chapter13Ctrl = $controller('Chapter13Ctrl', {
$scope: scope
});
}));
});
| johncol/proangularjs | test/spec/controllers/chapter13.js | JavaScript | apache-2.0 | 403 |
import PropTypes from 'prop-types';
import React from 'react';
import _ from 'lodash';
import $ from 'jquery';
export function trackPageView() {
if (!window.ga) return;
var current = location.protocol + '//' + location.hostname +
location.pathname + location.search;
if (current == trackPageView.last) return;
trackPageView.last = current;
ga('send', 'pageview', { location: current });
};
function parseQueryString(queryString) {
if (!queryString) return {};
var result = {};
var pairs = queryString.split('&');
for (var i = 0; i < pairs.length; i++) {
var index = pairs[i].indexOf('=');
if (index == -1) {
index = pairs[i].length;
}
var name = pairs[i].substring(0, index);
var value = pairs[i].substring(index + 1);
result[name] = decodeURIComponent(value.replace(/\+/g, ' '));
}
return result;
}
export var QueryContext = React.createContext();
export function queryConsumer(callback) {
return <QueryContext.Consumer>{callback}</QueryContext.Consumer>;
}
export class Root extends React.Component {
handlePopState = () => {
Votr.appRoot.forceUpdate();
}
componentDidMount() {
window.addEventListener('popstate', this.handlePopState, false);
trackPageView();
}
componentDidUpdate() {
trackPageView();
}
render() {
var queryString = location.search.substring(1);
if (queryString !== this.lastQueryString) {
this.query = parseQueryString(queryString);
this.lastQueryString = queryString;
}
return (
<React.StrictMode>
<QueryContext.Provider value={this.query}>
<this.props.app />
</QueryContext.Provider>
</React.StrictMode>
);
}
}
export function buildUrl(href) {
if (_.isString(href)) return href;
return '?' + $.param(_.omitBy(href, _.isUndefined), true);
};
export function navigate(href) {
Votr.didNavigate = true;
history.pushState(null, '', Votr.settings.url_root + buildUrl(href));
Votr.appRoot.forceUpdate();
};
export class Link extends React.Component {
handleClick = (event) => {
// Chrome fires onclick on middle click. Firefox only fires it on document,
// see <http://lists.w3.org/Archives/Public/www-dom/2013JulSep/0203.html>,
// but React adds event listeners to document so we still see a click event.
if (event.button != 0) return;
event.preventDefault();
navigate(this.props.href);
}
render() {
return <a {...this.props} href={buildUrl(this.props.href)}
onClick={this.handleClick} />;
}
}
// Looks and acts like a link, but doesn't have a href and cannot be opened in
// a new tab when middle-clicked or ctrl-clicked.
export class FakeLink extends React.Component {
static propTypes = {
onClick: PropTypes.func.isRequired
};
// Pressing Enter on <a href=...> emits a click event, and the HTML5 spec
// says elements with tabindex should do that too, but they don't.
// <http://www.w3.org/TR/WCAG20-TECHS/SCR29> suggests using a keyup event:
handleKeyUp = (event) => {
if (event.which == 13) {
event.preventDefault();
this.props.onClick(event);
}
}
render() {
return <a {...this.props} onKeyUp={this.handleKeyUp}
tabIndex="0" role="button" />;
}
}
| fmfi-svt/votr | votrfront/js/router.js | JavaScript | apache-2.0 | 3,286 |
/*global QUnit*/
sap.ui.define([
"sap/ui/test/opaQunit",
"sap/ui/Device",
"./pages/Main"
// "./pages/App"
], function (opaTest, Device) {
"use strict";
var oPCIds = {
sCalendarId: "PlanningCalendar",
sFragmentId: "PlanningCalendar",
sSelectorId: "PlanningCalendarTeamSelector",
sLegendButtonId: "PlanningCalendarLegendButton",
sCreateButtonId: "PlanningCalendarCreateAppointmentButton"
},
oSPCIds = {
sCalendarId: "SinglePlanningCalendar",
sFragmentId: "SinglePlanningCalendar",
sSelectorId: "SinglePlanningCalendarTeamSelector",
sLegendButtonId: "SinglePlanningCalendarLegendButton",
sCreateButtonId: "SinglePlanningCalendarCreateAppointmentButton"
};
QUnit.module("Team Calendar");
opaTest("Should see the Planning Calendar initially set", function (Given, When, Then) {
// Arrangements
Given.iStartMyApp();
// Assertions
Then.onTheMainPage.thePlanningCalendarShouldHaveAllTeamMembers(oPCIds).
and.theTeamSelectorHaveAllTeamMembers(oPCIds).
and.theCalendarViewIsProperlySet(oPCIds);
});
opaTest("Open a Legend when Planning Calendar is displayed", function (Given, When, Then) {
// Actions
Given.onTheMainPage.iClickOnALegendButton(oPCIds);
// Assertions
Then.onTheMainPage.theCalendarLegendIsOpened();
});
opaTest("Select a view from the Planning Calendar View Selector", function (Given, When, Then) {
// Actions
Given.onTheMainPage.iSelectACalendarView(oPCIds, "Day");
// Assertions
Then.onTheMainPage.theCalendarViewIsProperlySet(oPCIds, "Day");
});
opaTest("Click on the Planning Calendar Create Button", function (Given, When, Then) {
// Actions
Given.onTheMainPage.iClickOnCreateButton(oPCIds);
// Assertions
Then.onTheMainPage.theMessageToastAppears();
});
opaTest("Switch to the Single Planning Calendar", function (Given, When, Then) {
// Actions
Given.onTheMainPage.iSelectATeamMember(oPCIds, 1); // select the item with index=1
// Assertions
Then.onTheMainPage.theSinglePlanningCalendarIsLoaded(oSPCIds, 1).
and.theTeamSelectorHaveAllTeamMembers(oSPCIds).
and.theCalendarViewIsProperlySet(oSPCIds, "Day");
});
opaTest("Open a Legend when Single Planning Calendar is displayed", function (Given, When, Then) {
// Actions
Given.onTheMainPage.iClickOnALegendButton(oSPCIds);
// Assertions
Then.onTheMainPage.theCalendarLegendIsOpened();
});
opaTest("Select a view from the Single Planning Calendar View Selector", function (Given, When, Then) {
// Actions
Given.onTheMainPage.iSelectACalendarView(oSPCIds, "Week");
// Assertions
Then.onTheMainPage.theCalendarViewIsProperlySet(oSPCIds, "Week");
});
opaTest("Click on the Single Planning Calendar Create Button", function (Given, When, Then) {
// Actions
Given.onTheMainPage.iClickOnCreateButton(oSPCIds);
// Assertions
Then.onTheMainPage.theMessageToastAppears();
});
opaTest("Switch back to the Planning Calendar", function (Given, When, Then) {
// Actions
Given.onTheMainPage.iSelectATeamMember(oSPCIds, 0); // select the item with index=0 - Team
// Assertions
Then.onTheMainPage.thePlanningCalendarShouldHaveAllTeamMembers(oPCIds).
and.theTeamSelectorHaveAllTeamMembers(oPCIds).
and.theCalendarViewIsProperlySet(oPCIds, "Week");
// Cleanup
Then.iTeardownMyApp();
});
}); | SAP/openui5 | src/sap.m/test/sap/m/demokit/teamCalendar/webapp/test/integration/MainJourney.js | JavaScript | apache-2.0 | 3,309 |
/**
* Copyright 2018 The AMP HTML Authors. 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.
*/
import {CONSENT_ITEM_STATE, ConsentStateManager} from './consent-state-manager';
import {CONSENT_POLICY_STATE} from '../../../src/consent-state';
import {CSS} from '../../../build/amp-consent-0.1.css';
import {ConsentPolicyManager} from './consent-policy-manager';
import {Deferred} from '../../../src/utils/promise';
import {
NOTIFICATION_UI_MANAGER,
NotificationUiManager,
} from '../../../src/service/notification-ui-manager';
import {Services} from '../../../src/services';
import {
assertHttpsUrl,
getSourceUrl,
resolveRelativeUrl,
} from '../../../src/url';
import {
childElementsByTag,
isJsonScriptTag,
scopedQuerySelectorAll,
} from '../../../src/dom';
import {dev, user} from '../../../src/log';
import {dict, map} from '../../../src/utils/object';
import {getData} from '../../../src/event-helper';
import {getServicePromiseForDoc} from '../../../src/service';
import {isEnumValue} from '../../../src/types';
import {setImportantStyles, toggle} from '../../../src/style';
import {tryParseJson} from '../../../src/json';
const CONSENT_STATE_MANAGER = 'consentStateManager';
const CONSENT_POLICY_MANAGER = 'consentPolicyManager';
const TAG = 'amp-consent';
/**
* @enum {string}
* @visibleForTesting
*/
export const ACTION_TYPE = {
ACCEPT: 'accept',
REJECT: 'reject',
DISMISS: 'dismiss',
};
export class AmpConsent extends AMP.BaseElement {
/** @param {!AmpElement} element */
constructor(element) {
super(element);
/** @private {?ConsentStateManager} */
this.consentStateManager_ = null;
/** @private {?ConsentPolicyManager} */
this.consentPolicyManager_ = null;
/** @private {?NotificationUiManager} */
this.notificationUiManager_ = null;
/** @private {!Object<string, !Element>} */
this.consentUI_ = map();
/** @private {!JsonObject} */
this.consentConfig_ = dict();
/** @private {!JsonObject} */
this.policyConfig_ = dict();
/** @private {!Object} */
this.consentRequired_ = map();
/** @private {boolean} */
this.uiInit_ = false;
/** @private {?string} */
this.currentDisplayInstance_ = null;
/** @private {?Element} */
this.postPromptUI_ = null;
/** @private {!Object<string, ?function()>} */
this.dialogResolver_ = map();
/** @private {!Object<string, boolean>} */
this.consentUIPendingMap_ = map();
/** @private {boolean} */
this.isMultiSupported_ = false;
/** @const @private {!../../../src/service/vsync-impl.Vsync} */
this.vsync_ = this.getVsync();
/** @private {boolean} */
this.isPostPromptUIRequired_ = false;
}
/** @override */
getConsentPolicy() {
// amp-consent should not be blocked by itself
return null;
}
/**
* Handles the revoke action.
* Display consent UI.
* @param {string} consentId
*/
handlePostPrompt_(consentId) {
user().assert(this.consentConfig_[consentId],
`consent with id ${consentId} not found`);
// toggle the UI for this consent
this.scheduleDisplay_(consentId);
}
/** @override */
buildCallback() {
this.isMultiSupported_ = ConsentPolicyManager.isMultiSupported(this.win);
user().assert(this.element.getAttribute('id'),
'amp-consent should have an id');
// TODO: Decide what to do with incorrect configuration.
this.assertAndParseConfig_();
const children = this.getRealChildren();
for (let i = 0; i < children.length; i++) {
// <amp-consent> will manualy schedule layout for its children.
this.setAsOwner(children[i]);
}
const consentPolicyManagerPromise =
getServicePromiseForDoc(this.getAmpDoc(), CONSENT_POLICY_MANAGER)
.then(manager => {
this.consentPolicyManager_ = /** @type {!ConsentPolicyManager} */ (
manager);
this.generateDefaultPolicy_();
const policyKeys = Object.keys(this.policyConfig_);
for (let i = 0; i < policyKeys.length; i++) {
this.consentPolicyManager_.registerConsentPolicyInstance(
policyKeys[i], this.policyConfig_[policyKeys[i]]);
}
});
const consentStateManagerPromise =
getServicePromiseForDoc(this.getAmpDoc(), CONSENT_STATE_MANAGER)
.then(manager => {
this.consentStateManager_ = /** @type {!ConsentStateManager} */ (
manager);
});
const notificationUiManagerPromise =
getServicePromiseForDoc(this.getAmpDoc(), NOTIFICATION_UI_MANAGER)
.then(manager => {
this.notificationUiManager_ = /** @type {!NotificationUiManager} */ (
manager);
});
Promise.all([
consentStateManagerPromise,
notificationUiManagerPromise,
consentPolicyManagerPromise])
.then(() => {
this.init_();
});
}
/**
* Register a list of user action functions
*/
enableInteractions_() {
this.registerAction('accept', () => this.handleAction_(ACTION_TYPE.ACCEPT));
this.registerAction('reject', () => this.handleAction_(ACTION_TYPE.REJECT));
this.registerAction('dismiss',
() => this.handleAction_(ACTION_TYPE.DISMISS));
this.registerAction('prompt', invocation => {
const {args} = invocation;
let consentId = args && args['consent'];
if (!this.isMultiSupported_) {
consentId = Object.keys(this.consentConfig_)[0];
}
this.handlePostPrompt_(consentId || '');
});
this.enableExternalInteractions_();
}
/**
* Listen to external consent flow iframe's response
*/
enableExternalInteractions_() {
this.win.addEventListener('message', event => {
if (!this.currentDisplayInstance_) {
return;
}
const data = getData(event);
if (!data || data['type'] != 'consent-response') {
return;
}
if (!data['action']) {
user().error(TAG, 'consent-response message missing required info');
return;
}
const iframes = scopedQuerySelectorAll(this.element, 'amp-iframe iframe');
for (let i = 0; i < iframes.length; i++) {
if (iframes[i].contentWindow === event.source) {
const action = data['action'];
this.handleAction_(action);
return;
}
}
});
}
/**
* Returns a promise that attempt to show prompt UI for instanceId
* @param {string} instanceId
*/
scheduleDisplay_(instanceId) {
if (!this.notificationUiManager_) {
dev().error(TAG, 'notification ui manager not found');
}
if (this.consentUIPendingMap_[instanceId]) {
// Already pending to be shown. Do nothing.
return;
}
if (!this.consentUI_[instanceId]) {
// If consent UI not found. Do nothing.
return;
}
this.consentUIPendingMap_[instanceId] = true;
this.notificationUiManager_.registerUI(this.show_.bind(this, instanceId));
}
/**
* To show prompt UI for instanceId
* @param {string} instanceId
* @return {!Promise}
*/
show_(instanceId) {
if (this.currentDisplayInstance_) {
dev().error(TAG,
`other consent instance on display ${this.currentDisplayInstance_}`);
}
this.vsync_.mutate(() => {
if (!this.uiInit_) {
this.uiInit_ = true;
toggle(this.element, true);
}
this.element.classList.remove('amp-hidden');
this.element.classList.add('amp-active');
this.getViewport().addToFixedLayer(this.element);
// Display the current instance
this.currentDisplayInstance_ = instanceId;
const uiElement = this.consentUI_[this.currentDisplayInstance_];
setImportantStyles(uiElement, {display: 'block'});
// scheduleLayout is required everytime because some AMP element may
// get un laid out after toggle display (#unlayoutOnPause)
// for example <amp-iframe>
this.scheduleLayout(uiElement);
});
const deferred = new Deferred();
this.dialogResolver_[instanceId] = deferred.resolve;
return deferred.promise;
}
/**
* Hide current prompt UI
*/
hide_() {
const uiToHide = this.currentDisplayInstance_ &&
this.consentUI_[this.currentDisplayInstance_];
this.vsync_.mutate(() => {
this.element.classList.add('amp-hidden');
this.element.classList.remove('amp-active');
// Need to remove from fixed layer and add it back to update element's top
this.getViewport().removeFromFixedLayer(this.element);
if (!uiToHide) {
dev().error(TAG,
`${this.currentDisplayInstance_} no consent ui to hide`);
}
// Cannot use #toggle() because Safari bug with version older than 10.3
// element.style['display] = 'none' cannot overwrite style set with
// !important.
setImportantStyles(dev().assertElement(uiToHide), {display: 'none'});
});
const displayInstance = /** @type {string} */ (
this.currentDisplayInstance_);
if (this.dialogResolver_[displayInstance]) {
this.dialogResolver_[displayInstance]();
this.dialogResolver_[displayInstance] = null;
}
this.consentUIPendingMap_[displayInstance] = false;
this.currentDisplayInstance_ = null;
}
/**
* Handler User action
* @param {string} action
*/
handleAction_(action) {
if (!isEnumValue(ACTION_TYPE, action)) {
// Unrecognized action
return;
}
if (!this.currentDisplayInstance_) {
// No consent instance to act to
return;
}
if (!this.consentStateManager_) {
dev().error(TAG, 'No consent state manager');
return;
}
if (action == ACTION_TYPE.ACCEPT) {
//accept
this.consentStateManager_.updateConsentInstanceState(
this.currentDisplayInstance_, CONSENT_ITEM_STATE.ACCEPTED);
} else if (action == ACTION_TYPE.REJECT) {
// reject
this.consentStateManager_.updateConsentInstanceState(
this.currentDisplayInstance_, CONSENT_ITEM_STATE.REJECTED);
} else if (action == ACTION_TYPE.DISMISS) {
this.consentStateManager_.updateConsentInstanceState(
this.currentDisplayInstance_, CONSENT_ITEM_STATE.DISMISSED);
}
// Hide current dialog
this.hide_();
}
/**
* Init the amp-consent by registering and initiate consent instance.
*/
init_() {
const instanceKeys = Object.keys(this.consentConfig_);
const initPromptPromises = [];
for (let i = 0; i < instanceKeys.length; i++) {
const instanceId = instanceKeys[i];
this.consentStateManager_.registerConsentInstance(
instanceId, this.consentConfig_[instanceId]);
const isConsentRequiredPromise = this.getConsentRequiredPromise_(
instanceId, this.consentConfig_[instanceId]);
const handlePromptPromise = isConsentRequiredPromise.then(() => {
return this.initPromptUI_(instanceId);
}).catch(unusedError => {
// TODO: Handle errors
});
initPromptPromises.push(handlePromptPromise);
}
Promise.all(initPromptPromises).then(() => {
this.handlePostPromptUI_();
this.consentPolicyManager_.enableTimeout();
});
this.enableInteractions_();
}
/**
* Returns a promise that resolve when amp-consent knows
* if the consent is required.
* @param {string} instanceId
* @param {!JsonObject} config
* @return {!Promise}
*/
getConsentRequiredPromise_(instanceId, config) {
user().assert(config['checkConsentHref'] ||
config['promptIfUnknownForGeoGroup'],
'neither checkConsentHref nor ' +
'promptIfUnknownForGeoGroup is defined');
let remoteConfigPromise = Promise.resolve(null);
if (config['checkConsentHref']) {
remoteConfigPromise = this.getConsentRemote_(instanceId);
this.passSharedData_(instanceId, remoteConfigPromise);
}
let geoPromise = Promise.resolve();
if (config['promptIfUnknownForGeoGroup']) {
const geoGroup = config['promptIfUnknownForGeoGroup'];
geoPromise = this.isConsentRequiredGeo_(geoGroup);
}
return geoPromise.then(promptIfUnknown => {
return remoteConfigPromise.then(response => {
this.consentRequired_[instanceId] =
this.isPromptRequired_(instanceId, response, promptIfUnknown);
});
});
}
/**
* Blindly pass sharedData
* @param {string} instanceId
* @param {!Promise<!JsonObject>} responsePromise
*/
passSharedData_(instanceId, responsePromise) {
const sharedDataPromise = responsePromise.then(response => {
if (!response || response['sharedData'] === undefined) {
return null;
}
return response['sharedData'];
});
this.consentStateManager_.setConsentInstanceSharedData(
instanceId, sharedDataPromise);
}
/**
* Returns a promise that if user is in the given geoGroup
* @param {string} geoGroup
* @return {Promise<boolean>}
*/
isConsentRequiredGeo_(geoGroup) {
return Services.geoForDocOrNull(this.element).then(geo => {
user().assert(geo,
'requires <amp-geo> to use promptIfUnknownForGeoGroup');
return (geo.ISOCountryGroups.indexOf(geoGroup) >= 0);
});
}
/**
* Generate default consent policy if not defined
*/
generateDefaultPolicy_() {
// Generate default policy
const instanceKeys = Object.keys(this.consentConfig_);
const defaultWaitForItems = {};
for (let i = 0; i < instanceKeys.length; i++) {
// TODO: Need to support an array.
defaultWaitForItems[instanceKeys[i]] = undefined;
}
const defaultPolicy = {
'waitFor': defaultWaitForItems,
};
// TODO(@zhouyx): unblockOn is internal now.
const unblockOnAll = [
CONSENT_POLICY_STATE.UNKNOWN,
CONSENT_POLICY_STATE.SUFFICIENT,
CONSENT_POLICY_STATE.INSUFFICIENT,
CONSENT_POLICY_STATE.UNKNOWN_NOT_REQUIRED,
];
const predefinedNone = {
'waitFor': defaultWaitForItems,
// Experimental config, do not expose
'unblockOn': unblockOnAll,
};
const rejectAllOnZero = {
'waitFor': defaultWaitForItems,
'timeout': {
'seconds': 0,
'fallbackAction': 'reject',
},
'unblockOn': unblockOnAll,
};
this.policyConfig_['_till_responded'] = predefinedNone;
this.policyConfig_['_till_accepted'] = defaultPolicy;
this.policyConfig_['_auto_reject'] = rejectAllOnZero;
if (this.policyConfig_ && this.policyConfig_['default']) {
return;
}
this.policyConfig_['default'] = defaultPolicy;
}
/**
* Get localStored consent info, and send request to get consent from endpoint
* @param {string} instanceId
* @return {!Promise<!JsonObject>}
*/
getConsentRemote_(instanceId) {
// Note: Expect the request to look different in following versions.
const request = /** @type {!JsonObject} */ ({
'consentInstanceId': instanceId,
});
const init = {
credentials: 'include',
method: 'POST',
body: request,
requireAmpResponseSourceOrigin: false,
};
const href =
this.consentConfig_[instanceId]['checkConsentHref'];
assertHttpsUrl(href, this.element);
const ampdoc = this.getAmpDoc();
const sourceBase = getSourceUrl(ampdoc.getUrl());
const resolvedHref = resolveRelativeUrl(href, sourceBase);
const viewer = Services.viewerForDoc(ampdoc);
return viewer.whenFirstVisible().then(() => {
return Services.xhrFor(this.win)
.fetchJson(resolvedHref, init)
.then(res => res.json());
});
}
/**
* Read and parse consent instance config
* An example valid config json looks like
* {
* "consents": {
* "consentABC": {
* "checkConsentHref": "https://fake.com"
* }
* }
* }
* TODO: Add support for policy config
*/
assertAndParseConfig_() {
// All consent config within the amp-consent component. There will be only
// one single amp-consent allowed in page.
// TODO: Make this a shared helper method.
const scripts = childElementsByTag(this.element, 'script');
user().assert(scripts.length == 1,
`${TAG} should have (only) one <script> child`);
const script = scripts[0];
user().assert(isJsonScriptTag(script),
`${TAG} consent instance config should be put in a <script>` +
'tag with type= "application/json"');
const config = tryParseJson(script.textContent, () => {
user().assert(false, `${TAG}: Error parsing config`);
});
const consents = config['consents'];
user().assert(consents, `${TAG}: consents config is required`);
user().assert(Object.keys(consents).length != 0,
`${TAG}: can't find consent instance`);
if (!this.isMultiSupported_) {
// Assert single consent instance
user().assert(Object.keys(consents).length <= 1,
`${TAG}: only single consent instance is supported`);
if (config['policy']) {
// Only respect 'default' consent policy;
const keys = Object.keys(config['policy']);
for (let i = 0; i < keys.length; i++) {
if (keys[i] != 'default') {
user().warn(TAG, `policy ${keys[i]} is currently not supported` +
'and will be ignored');
delete config['policy'][keys[i]];
}
}
}
}
this.consentConfig_ = consents;
if (config['postPromptUI']) {
const postPromptUI = config['postPromptUI'];
this.postPromptUI_ = this.getAmpDoc().getElementById(postPromptUI);
if (!this.postPromptUI_) {
this.user().error(TAG, 'postPromptUI element with ' +
`id=${postPromptUI} not found`);
}
}
this.policyConfig_ = config['policy'] || this.policyConfig_;
}
/**
* Parse response from server endpoint
* The response format example:
* {
* "promptIfUnknown": true/false
* }
* TODO: Support vendor lists
* @param {string} instanceId
* @param {?JsonObject} response
* @param {boolean=} opt_initValue
* @return {boolean}
*/
isPromptRequired_(instanceId, response, opt_initValue) {
let promptIfUnknown = opt_initValue;
if (response && response['promptIfUnknown'] == true) {
promptIfUnknown = true;
} else if (response && response['promptIfUnknown'] == false) {
promptIfUnknown = false;
} else if (promptIfUnknown == undefined) {
// Set to false if not defined
promptIfUnknown = false;
}
return promptIfUnknown;
}
/**
* Handle Prompt UI.
* @param {string} instanceId
* @return {Promise}
*/
initPromptUI_(instanceId) {
const promptUI = this.consentConfig_[instanceId]['promptUI'];
if (promptUI) {
let element = this.getAmpDoc().getElementById(promptUI);
if (!element || !this.element.contains(element)) {
element = null;
this.user().error(TAG, 'child element of <amp-consent> with ' +
`promptUI id ${promptUI} not found`);
}
this.consentUI_[instanceId] = dev().assertElement(element);
}
// Get current consent state
return this.consentStateManager_.getConsentInstanceState(instanceId)
.then(state => {
if (state == CONSENT_ITEM_STATE.ACCEPTED ||
state == CONSENT_ITEM_STATE.REJECTED) {
// Need to display post prompt ui if user previous made a decision
this.isPostPromptUIRequired_ = true;
}
if (state == CONSENT_ITEM_STATE.UNKNOWN) {
if (!this.consentRequired_[instanceId]) {
this.consentStateManager_.updateConsentInstanceState(
instanceId, CONSENT_ITEM_STATE.NOT_REQUIRED);
return;
}
this.isPostPromptUIRequired_ = true;
// TODO(@zhouyx):
// 1. Race condition on consent state change between schedule to
// display and display. Add one more check before display
// 2. Should not schedule display with DISMISSED UNKNOWN state
this.scheduleDisplay_(instanceId);
}
});
}
/**
* Handles the display of postPromptUI
*/
handlePostPromptUI_() {
if (!this.isPostPromptUIRequired_) {
return;
}
const {classList} = this.element;
this.notificationUiManager_.onQueueEmpty(() => {
if (!this.postPromptUI_) {
return;
}
this.vsync_.mutate(() => {
if (!this.uiInit_) {
this.uiInit_ = true;
toggle(this.element, true);
}
classList.add('amp-active');
classList.remove('amp-hidden');
this.getViewport().addToFixedLayer(this.element);
setImportantStyles(dev().assertElement(this.postPromptUI_),
{display: 'block'});
// Will need to scheduleLayout for postPromptUI
// upon request for using AMP component.
});
});
this.notificationUiManager_.onQueueNotEmpty(() => {
if (!this.postPromptUI_) {
return;
}
this.vsync_.mutate(() => {
if (!this.currentDisplayInstance_) {
classList.add('amp-hidden');
classList.remove('amp-active');
}
this.getViewport().removeFromFixedLayer(this.element);
// Cannot use #toggle() because Safari bug with version older than 10.3
// element.style['display] = 'none' cannot overwrite style set with
// !important.
setImportantStyles(dev().assertElement(this.postPromptUI_),
{display: 'none'});
});
});
}
}
AMP.extension('amp-consent', '0.1', AMP => {
AMP.registerElement('amp-consent', AmpConsent, CSS);
AMP.registerServiceForDoc(NOTIFICATION_UI_MANAGER, NotificationUiManager);
AMP.registerServiceForDoc(CONSENT_STATE_MANAGER, ConsentStateManager);
AMP.registerServiceForDoc(CONSENT_POLICY_MANAGER, ConsentPolicyManager);
});
| aghassemi/amphtml | extensions/amp-consent/0.1/amp-consent.js | JavaScript | apache-2.0 | 22,474 |
import React from 'react';
import { Route, IndexRoute } from 'react-router';
import App from 'containers/App';
import Home from 'containers/Home';
import Imprint from 'containers/Imprint';
import About from 'containers/About';
import Terms from 'containers/Terms';
import LoginPage from 'containers/Login';
import Logout from 'containers/Logout';
import Petitions from 'containers/Petitions';
import NewPetition from 'containers/NewPetition';
import Petition from 'containers/Petition';
import EditPetition from 'containers/EditPetition';
import PreviewPetition from 'containers/PreviewPetition';
import TrustSupport from 'containers/TrustSupport';
import TrustSupportConfirmation from 'containers/TrustSupportConfirmation';
import TrustPublish from 'containers/TrustPublish';
import TrustPublishConfirmation from 'containers/TrustPublishConfirmation';
import RespondToPetition from 'containers/RespondToPetition';
import EmailConfirmationContainer from 'containers/EmailConfirmationContainer';
import Error404 from 'containers/Error404';
// Redirect handlers for restricting routes
import ProtectRejectedPetition from 'server/redirects/ProtectRejectedPetition';
import ProtectUnsupportablePetition from 'server/redirects/ProtectUnsupportablePetition';
import ProtectPublishedPetition from 'server/redirects/ProtectPublishedPetition';
// Restrictive higher-order components (client-side)
import RedirectIfSupported from 'containers/RedirectIfSupported';
export default (
<Route path='/' component={App}>
<IndexRoute component={Home} />
<Route path='imprint' component={Imprint} />
<Route path='about' component={About} />
<Route path='terms' component={Terms} />
<Route path='auth/login' component={LoginPage} />
<Route path='auth/logout' component={Logout} />
<Route path='petitions'>
{/* Nest these 3 to support proper `activeClassName` behavior. */}
<IndexRoute component={Petitions} />
<Route path=':cityName-:city(/page(/:page))' component={Petitions} />
<Route path='page/:page' component={Petitions} />
</Route>
<Route
path='petitions/new'
component={NewPetition}
/>
<Route
path='petitions/:id'
onEnter={ProtectRejectedPetition}
component={Petition}
/>
<Route
path='petitions/:id/edit'
onEnter={ProtectPublishedPetition}
component={EditPetition}
/>
<Route
path='petitions/:id/preview'
onEnter={ProtectPublishedPetition}
component={PreviewPetition}
/>
<Route
path='trust/publish/:id'
onEnter={ProtectPublishedPetition}
component={TrustPublish}
/>
<Route
path='trust/publish/:id/confirm'
onEnter={ProtectPublishedPetition}
component={TrustPublishConfirmation}
/>
<Route
path='trust/support/:id'
onEnter={ProtectUnsupportablePetition}
component={RedirectIfSupported(TrustSupport)}
/>
<Route
path='trust/support/:id/confirm'
onEnter={ProtectUnsupportablePetition}
component={RedirectIfSupported(TrustSupportConfirmation)}
/>
<Route
path='respond/:token'
component={RespondToPetition}
/>
<Route
path='confirm/email/:action'
component={EmailConfirmationContainer}
/>
<Route path='*' component={Error404} status={404} />
</Route>
);
| iris-dni/iris-frontend | src/routers/client.js | JavaScript | apache-2.0 | 3,341 |
//
// Copyright (c) Microsoft Corporation. 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.
//
local __extends = function(sub, base)
setmetatable(sub, base)
base.__index = base
end;
local __new = function(class, ...)
local new={}
__extends(new, class)
if new.constructor ~= nil then
new:constructor(...)
end
return new
end;
var _this = this;local _this = this;
/// <reference path='services.ts' />
/* @internal */
local debugObjectHost = this;
/* @internal */
local ts;
(function (ts) {
number;
string;
/** Gets the length of this script snapshot. */
getLength();
number;
/**
* Returns a JSON-encoded value of the type:
* { span: { start: number; length: number }; newLength: number }
*
* Or undefined value if there was no change.
*/
getChangeRange(oldSnapshot, ScriptSnapshotShim);
string;
end)(ts || (ts = {}));
number, options;
string; /*Services.FormatCodeOptions*/
string;
getFormattingEditsForDocument(fileName, string, options, string /*Services.FormatCodeOptions*/);
string;
getFormattingEditsAfterKeystroke(fileName, string, position, number, key, string, options, string /*Services.FormatCodeOptions*/);
string;
getEmitOutput(fileName, string);
string;
function logInternalError(logger, err)
if (logger) {
logger.log("*INTERNAL ERROR* - Exception in typescript services: " + err.message);
end
end
local ScriptSnapshotShimAdapter = (function ()
local ScriptSnapshotShimAdapter = {}
ScriptSnapshotShimAdapter.constructor = function (this, scriptSnapshotShim)
this.scriptSnapshotShim = scriptSnapshotShim;
this.lineStartPositions = null;
end;
return ScriptSnapshotShimAdapter;
end)();
number;
string;
{
return this.scriptSnapshotShim.getText(start);
end
;
getLength();
number;
{
return this.scriptSnapshotShim.getLength();
end
getChangeRange(oldSnapshot, IScriptSnapshot);
TextChangeRange;
{
local oldSnapshotShim = oldSnapshot;
local encoded = this.scriptSnapshotShim.getChangeRange(oldSnapshotShim.scriptSnapshotShim);
if (encoded == null) {
return null;
end
local decoded = JSON.parse(encoded);
return createTextChangeRange(createTextSpan(decoded.span.start, decoded.span.length), decoded.newLength);
end
local LanguageServiceShimHostAdapter = (function ()
local LanguageServiceShimHostAdapter = {}
LanguageServiceShimHostAdapter.constructor = function (this, shimHost)
this.shimHost = shimHost;
end;
LanguageServiceShimHostAdapter.log = function (this, s)
this.shimHost.log(s);
end;
LanguageServiceShimHostAdapter.trace = function (this, s)
this.shimHost.trace(s);
end;
LanguageServiceShimHostAdapter.error = function (this, s)
this.shimHost.error(s);
end;
LanguageServiceShimHostAdapter.getProjectVersion = function (this)
if (!this.shimHost.getProjectVersion) {
// shimmed host does not support getProjectVersion
return undefined;
end
return this.shimHost.getProjectVersion();
end;
LanguageServiceShimHostAdapter.getCompilationSettings = function (this)
local settingsJson = this.shimHost.getCompilationSettings();
if (settingsJson == null || settingsJson == "") {
throw Error("LanguageServiceShimHostAdapter.getCompilationSettings: empty compilationSettings");
return null;
end
return JSON.parse(settingsJson);
end;
LanguageServiceShimHostAdapter.getScriptFileNames = function (this)
local encoded = this.shimHost.getScriptFileNames();
return this.files = JSON.parse(encoded);
end;
LanguageServiceShimHostAdapter.getScriptSnapshot = function (this, fileName)
// Shim the API changes for 1.5 release. This should be removed once
// TypeScript 1.5 has shipped.
if (this.files && this.files.indexOf(fileName) < 0) {
return undefined;
end
local scriptSnapshot = this.shimHost.getScriptSnapshot(fileName);
return scriptSnapshot && new ScriptSnapshotShimAdapter(scriptSnapshot);
end;
LanguageServiceShimHostAdapter.getScriptVersion = function (this, fileName)
return this.shimHost.getScriptVersion(fileName);
end;
LanguageServiceShimHostAdapter.getLocalizedDiagnosticMessages = function (this)
local diagnosticMessagesJson = this.shimHost.getLocalizedDiagnosticMessages();
if (diagnosticMessagesJson == null || diagnosticMessagesJson == "") {
return null;
end
try {
return JSON.parse(diagnosticMessagesJson);
end
catch (e) {
this:log(e.description || "diagnosticMessages.generated.json has invalid JSON format");
return null;
end
end;
LanguageServiceShimHostAdapter.getCancellationToken = function (this)
return this.shimHost.getCancellationToken();
end;
LanguageServiceShimHostAdapter.getCurrentDirectory = function (this)
return this.shimHost.getCurrentDirectory();
end;
LanguageServiceShimHostAdapter.getDefaultLibFileName = function (this, options)
// Wrap the API changes for 1.5 release. This try/catch
// should be removed once TypeScript 1.5 has shipped.
try {
return this.shimHost.getDefaultLibFileName(JSON.stringify(options));
end
catch (e) {
return "";
end
end;
return LanguageServiceShimHostAdapter;
end)();
exports.LanguageServiceShimHostAdapter = LanguageServiceShimHostAdapter;
local CoreServicesShimHostAdapter = (function ()
local CoreServicesShimHostAdapter = {}
CoreServicesShimHostAdapter.constructor = function (this, shimHost)
this.shimHost = shimHost;
end;
CoreServicesShimHostAdapter.readDirectory = function (this, rootDir, extension)
local encoded = this.shimHost.readDirectory(rootDir, extension);
return JSON.parse(encoded);
end;
return CoreServicesShimHostAdapter;
end)();
exports.CoreServicesShimHostAdapter = CoreServicesShimHostAdapter;
function simpleForwardCall(logger, actionDescription, action, noPerfLogging)
if (!noPerfLogging) {
logger.log(actionDescription);
local start = Date.now();
end
local result = action();
if (!noPerfLogging) {
local ;
end
Date.now();
logger.log(actionDescription + " completed in " + ());
end
-start;
+" msec";
;
if (typeof (result) === "string") {
local str = result;
if (str.length > 128) {
str = str.substring(0, 128) + "...";
end
logger.log(" result.length=" + str.length + ", result='" + JSON.stringify(str) + "'");
end
return result;
function forwardJSONCall(logger, actionDescription, action, noPerfLogging)
try {
local result = simpleForwardCall(logger, actionDescription, action, noPerfLogging);
return JSON.stringify({ result: result });
end
catch (err) {
if (err instanceof OperationCanceledException) {
return JSON.stringify({ canceled: true });
end
logInternalError(logger, err);
err.description = actionDescription;
return JSON.stringify({ error: err });
end
end
local ShimBase = (function ()
local ShimBase = {}
ShimBase.constructor = function (this, factory)
this.factory = factory;
factory.registerShim(this);
end;
ShimBase.dispose = function (this, dummy)
this.factory.unregisterShim(this);
end;
return ShimBase;
end)();
function realizeDiagnostics(diagnostics, newLine)
return diagnostics.map(function (d) { return realizeDiagnostic(d, newLine); });
end
exports.realizeDiagnostics = realizeDiagnostics;
function realizeDiagnostic(diagnostic, newLine)
return {
message: flattenDiagnosticMessageText(diagnostic.messageText, newLine),
start: diagnostic.start,
length: diagnostic.length,
/// TODO: no need for the tolowerCase call
category: DiagnosticCategory[diagnostic.category].toLowerCase(),
code: diagnostic.code
};
end
local LanguageServiceShimObject = (function (_super)
local LanguageServiceShimObject = {}
LanguageServiceShimObject.constructor = function (this, factory, host, languageService)
_super.call(this, factory);
this.host = host;
this.languageService = languageService;
this.logger = this.host;
end;
__extends(LanguageServiceShimObject, _super);
LanguageServiceShimObject.forwardJSONCall = function (this, actionDescription, action)
return forwardJSONCall(this.logger, actionDescription, action, false);
end;
/// DISPOSE
/**
* Ensure (almost) deterministic release of internal Javascript resources when
* some external native objects holds onto us (e.g. Com/Interop).
*/
LanguageServiceShimObject.dispose = function (this, dummy)
this.logger.log("dispose()");
this.languageService.dispose();
this.languageService = null;
// force a GC
if (debugObjectHost && debugObjectHost.CollectGarbage) {
debugObjectHost.CollectGarbage();
this.logger.log("CollectGarbage()");
end
this.logger = null;
_super.prototype.dispose.call(this, dummy);
end;
/// REFRESH
/**
* Update the list of scripts known to the compiler
*/
LanguageServiceShimObject.refresh = function (this, throwOnError)
this:forwardJSONCall("refresh(" + throwOnError + ")", function ()
return null;
end);
end;
LanguageServiceShimObject.cleanupSemanticCache = function (this)
var _this = this;local _this = this;
this:forwardJSONCall("cleanupSemanticCache()", function ()
_this.languageService.cleanupSemanticCache();
return null;
end);
end;
LanguageServiceShimObject.realizeDiagnostics = function (this, diagnostics)
local newLine = this:getNewLine();
return ts.realizeDiagnostics(diagnostics, newLine);
end;
LanguageServiceShimObject.getSyntacticClassifications = function (this, fileName, start, length)
var _this = this;local _this = this;
return this:forwardJSONCall("getSyntacticClassifications('" + fileName + "', " + start + ", " + length + ")", function ()
local classifications = _this.languageService.getSyntacticClassifications(fileName, createTextSpan(start, length));
return classifications;
end);
end;
LanguageServiceShimObject.getSemanticClassifications = function (this, fileName, start, length)
var _this = this;local _this = this;
return this:forwardJSONCall("getSemanticClassifications('" + fileName + "', " + start + ", " + length + ")", function ()
local classifications = _this.languageService.getSemanticClassifications(fileName, createTextSpan(start, length));
return classifications;
end);
end;
LanguageServiceShimObject.getEncodedSyntacticClassifications = function (this, fileName, start, length)
var _this = this;local _this = this;
return this:forwardJSONCall("getEncodedSyntacticClassifications('" + fileName + "', " + start + ", " + length + ")", function ()
// directly serialize the spans out to a string. This is much faster to decode
// on the managed side versus a full JSON array.
return convertClassifications(_this.languageService.getEncodedSyntacticClassifications(fileName, createTextSpan(start, length)));
end);
end;
LanguageServiceShimObject.getEncodedSemanticClassifications = function (this, fileName, start, length)
var _this = this;local _this = this;
return this:forwardJSONCall("getEncodedSemanticClassifications('" + fileName + "', " + start + ", " + length + ")", function ()
// directly serialize the spans out to a string. This is much faster to decode
// on the managed side versus a full JSON array.
return convertClassifications(_this.languageService.getEncodedSemanticClassifications(fileName, createTextSpan(start, length)));
end);
end;
LanguageServiceShimObject.getNewLine = function (this)
return this.host.getNewLine ? this.host.getNewLine() : "\r\n";
end;
LanguageServiceShimObject.getSyntacticDiagnostics = function (this, fileName)
var _this = this;local _this = this;
return this:forwardJSONCall("getSyntacticDiagnostics('" + fileName + "')", function ()
local diagnostics = _this.languageService.getSyntacticDiagnostics(fileName);
return _this:realizeDiagnostics(diagnostics);
end);
end;
LanguageServiceShimObject.getSemanticDiagnostics = function (this, fileName)
var _this = this;local _this = this;
return this:forwardJSONCall("getSemanticDiagnostics('" + fileName + "')", function ()
local diagnostics = _this.languageService.getSemanticDiagnostics(fileName);
return _this:realizeDiagnostics(diagnostics);
end);
end;
LanguageServiceShimObject.getCompilerOptionsDiagnostics = function (this)
var _this = this;local _this = this;
return this:forwardJSONCall("getCompilerOptionsDiagnostics()", function ()
local diagnostics = _this.languageService.getCompilerOptionsDiagnostics();
return _this:realizeDiagnostics(diagnostics);
end);
end;
/// QUICKINFO
/**
* Computes a string representation of the type at the requested position
* in the active file.
*/
LanguageServiceShimObject.getQuickInfoAtPosition = function (this, fileName, position)
var _this = this;local _this = this;
return this:forwardJSONCall("getQuickInfoAtPosition('" + fileName + "', " + position + ")", function ()
local quickInfo = _this.languageService.getQuickInfoAtPosition(fileName, position);
return quickInfo;
end);
end;
/// NAMEORDOTTEDNAMESPAN
/**
* Computes span information of the name or dotted name at the requested position
* in the active file.
*/
LanguageServiceShimObject.getNameOrDottedNameSpan = function (this, fileName, startPos, endPos)
var _this = this;local _this = this;
return this:forwardJSONCall("getNameOrDottedNameSpan('" + fileName + "', " + startPos + ", " + endPos + ")", function ()
local spanInfo = _this.languageService.getNameOrDottedNameSpan(fileName, startPos, endPos);
return spanInfo;
end);
end;
/**
* STATEMENTSPAN
* Computes span information of statement at the requested position in the active file.
*/
LanguageServiceShimObject.getBreakpointStatementAtPosition = function (this, fileName, position)
var _this = this;local _this = this;
return this:forwardJSONCall("getBreakpointStatementAtPosition('" + fileName + "', " + position + ")", function ()
local spanInfo = _this.languageService.getBreakpointStatementAtPosition(fileName, position);
return spanInfo;
end);
end;
/// SIGNATUREHELP
LanguageServiceShimObject.getSignatureHelpItems = function (this, fileName, position)
var _this = this;local _this = this;
return this:forwardJSONCall("getSignatureHelpItems('" + fileName + "', " + position + ")", function ()
local signatureInfo = _this.languageService.getSignatureHelpItems(fileName, position);
return signatureInfo;
end);
end;
/// GOTO DEFINITION
/**
* Computes the definition location and file for the symbol
* at the requested position.
*/
LanguageServiceShimObject.getDefinitionAtPosition = function (this, fileName, position)
var _this = this;local _this = this;
return this:forwardJSONCall("getDefinitionAtPosition('" + fileName + "', " + position + ")", function ()
return _this.languageService.getDefinitionAtPosition(fileName, position);
end);
end;
/// GOTO Type
/**
* Computes the definition location of the type of the symbol
* at the requested position.
*/
LanguageServiceShimObject.getTypeDefinitionAtPosition = function (this, fileName, position)
var _this = this;local _this = this;
return this:forwardJSONCall("getTypeDefinitionAtPosition('" + fileName + "', " + position + ")", function ()
return _this.languageService.getTypeDefinitionAtPosition(fileName, position);
end);
end;
LanguageServiceShimObject.getRenameInfo = function (this, fileName, position)
var _this = this;local _this = this;
return this:forwardJSONCall("getRenameInfo('" + fileName + "', " + position + ")", function ()
return _this.languageService.getRenameInfo(fileName, position);
end);
end;
LanguageServiceShimObject.findRenameLocations = function (this, fileName, position, findInStrings, findInComments)
var _this = this;local _this = this;
return this:forwardJSONCall("findRenameLocations('" + fileName + "', " + position + ", " + findInStrings + ", " + findInComments + ")", function ()
return _this.languageService.findRenameLocations(fileName, position, findInStrings, findInComments);
end);
end;
/// GET BRACE MATCHING
LanguageServiceShimObject.getBraceMatchingAtPosition = function (this, fileName, position)
var _this = this;local _this = this;
return this:forwardJSONCall("getBraceMatchingAtPosition('" + fileName + "', " + position + ")", function ()
local textRanges = _this.languageService.getBraceMatchingAtPosition(fileName, position);
return textRanges;
end);
end;
/// GET SMART INDENT
LanguageServiceShimObject.getIndentationAtPosition = function (this, fileName, position, options /*Services.EditorOptions*/)
var _this = this;local _this = this;
return this:forwardJSONCall("getIndentationAtPosition('" + fileName + "', " + position + ")", function ()
local localOptions = JSON.parse(options);
return _this.languageService.getIndentationAtPosition(fileName, position, localOptions);
end);
end;
/// GET REFERENCES
LanguageServiceShimObject.getReferencesAtPosition = function (this, fileName, position)
var _this = this;local _this = this;
return this:forwardJSONCall("getReferencesAtPosition('" + fileName + "', " + position + ")", function ()
return _this.languageService.getReferencesAtPosition(fileName, position);
end);
end;
LanguageServiceShimObject.findReferences = function (this, fileName, position)
var _this = this;local _this = this;
return this:forwardJSONCall("findReferences('" + fileName + "', " + position + ")", function ()
return _this.languageService.findReferences(fileName, position);
end);
end;
LanguageServiceShimObject.getOccurrencesAtPosition = function (this, fileName, position)
var _this = this;local _this = this;
return this:forwardJSONCall("getOccurrencesAtPosition('" + fileName + "', " + position + ")", function ()
return _this.languageService.getOccurrencesAtPosition(fileName, position);
end);
end;
LanguageServiceShimObject.getDocumentHighlights = function (this, fileName, position, filesToSearch)
var _this = this;local _this = this;
return this:forwardJSONCall("getDocumentHighlights('" + fileName + "', " + position + ")", function ()
return _this.languageService.getDocumentHighlights(fileName, position, JSON.parse(filesToSearch));
end);
end;
/// COMPLETION LISTS
/**
* Get a string based representation of the completions
* to provide at the given source position and providing a member completion
* list if requested.
*/
LanguageServiceShimObject.getCompletionsAtPosition = function (this, fileName, position)
var _this = this;local _this = this;
return this:forwardJSONCall("getCompletionsAtPosition('" + fileName + "', " + position + ")", function ()
local completion = _this.languageService.getCompletionsAtPosition(fileName, position);
return completion;
end);
end;
/** Get a string based representation of a completion list entry details */
LanguageServiceShimObject.getCompletionEntryDetails = function (this, fileName, position, entryName)
var _this = this;local _this = this;
return this:forwardJSONCall("getCompletionEntryDetails('" + fileName + "', " + position + ", " + entryName + ")", function ()
local details = _this.languageService.getCompletionEntryDetails(fileName, position, entryName);
return details;
end);
end;
return LanguageServiceShimObject;
end)(ShimBase);
number, options;
string; /*Services.FormatCodeOptions*/
string;
{
return this.forwardJSONCall("getFormattingEditsForRange('" + fileName + "', " + start + ", " + );
end
+")",
function ()
local localOptions = JSON.parse(options);
local edits = _this.languageService.getFormattingEditsForRange(fileName, start);
end, localOptions;
;
return edits;
;
getFormattingEditsForDocument(fileName, string, options, string /*Services.FormatCodeOptions*/);
string;
{
return this.forwardJSONCall("getFormattingEditsForDocument('" + fileName + "')", function ()
local localOptions = JSON.parse(options);
local edits = _this.languageService.getFormattingEditsForDocument(fileName, localOptions);
return edits;
end);
end
getFormattingEditsAfterKeystroke(fileName, string, position, number, key, string, options, string /*Services.FormatCodeOptions*/);
string;
{
return this.forwardJSONCall("getFormattingEditsAfterKeystroke('" + fileName + "', " + position + ", '" + key + "')", function ()
local localOptions = JSON.parse(options);
local edits = _this.languageService.getFormattingEditsAfterKeystroke(fileName, position, key, localOptions);
return edits;
end);
end
getNavigateToItems(searchValue, string, maxResultCount ? : number);
string;
{
return this.forwardJSONCall("getNavigateToItems('" + searchValue + "', " + maxResultCount + ")", function ()
local items = _this.languageService.getNavigateToItems(searchValue, maxResultCount);
return items;
end);
end
getNavigationBarItems(fileName, string);
string;
{
return this.forwardJSONCall("getNavigationBarItems('" + fileName + "')", function ()
local items = _this.languageService.getNavigationBarItems(fileName);
return items;
end);
end
getOutliningSpans(fileName, string);
string;
{
return this.forwardJSONCall("getOutliningSpans('" + fileName + "')", function ()
local items = _this.languageService.getOutliningSpans(fileName);
return items;
end);
end
getTodoComments(fileName, string, descriptors, string);
string;
{
return this.forwardJSONCall("getTodoComments('" + fileName + "')", function ()
local items = _this.languageService.getTodoComments(fileName, JSON.parse(descriptors));
return items;
end);
end
getEmitOutput(fileName, string);
string;
{
return this.forwardJSONCall("getEmitOutput('" + fileName + "')", function ()
local output = _this.languageService.getEmitOutput(fileName);
// Shim the API changes for 1.5 release. This should be removed once
// TypeScript 1.5 has shipped.
output.emitOutputStatus = output.emitSkipped ? 1 : 0;
return output;
end);
end
function convertClassifications(classifications)
return { spans: classifications.spans.join(","), endOfLineState: classifications.endOfLineState };
end
local ClassifierShimObject = (function (_super)
local ClassifierShimObject = {}
ClassifierShimObject.constructor = function (this, factory, logger)
_super.call(this, factory);
this.logger = logger;
this.classifier = createClassifier();
end;
__extends(ClassifierShimObject, _super);
ClassifierShimObject.getEncodedLexicalClassifications = function (this, text, lexState, syntacticClassifierAbsent)
var _this = this;local _this = this;
return forwardJSONCall(this.logger, "getEncodedLexicalClassifications", function () { return convertClassifications(_this.classifier.getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent)); },
/*noPerfLogging:*/ true);
end;
/// COLORIZATION
ClassifierShimObject.getClassificationsForLine = function (this, text, lexState, classifyKeywordsInGenerics)
local classification = this.classifier.getClassificationsForLine(text, lexState, classifyKeywordsInGenerics);
local items = classification.entries;
local result = "";
for (var i = 0; i < items.length; i++) {
result += items[i].length + "\n";
result += items[i].classification + "\n";
end
result += classification.finalLexState;
return result;
end;
return ClassifierShimObject;
end)(ShimBase);
local CoreServicesShimObject = (function (_super)
local CoreServicesShimObject = {}
CoreServicesShimObject.constructor = function (this, factory, logger, host)
_super.call(this, factory);
this.logger = logger;
this.host = host;
end;
__extends(CoreServicesShimObject, _super);
CoreServicesShimObject.forwardJSONCall = function (this, actionDescription, action)
return forwardJSONCall(this.logger, actionDescription, action, false);
end;
CoreServicesShimObject.getPreProcessedFileInfo = function (this, fileName, sourceTextSnapshot)
return this:forwardJSONCall("getPreProcessedFileInfo('" + fileName + "')", function ()
local result = preProcessFile(sourceTextSnapshot.getText(0, sourceTextSnapshot.getLength()));
local convertResult = {
referencedFiles: [],
importedFiles: [],
isLibFile: result.isLibFile
};
forEach(result.referencedFiles, function (refFile)
convertResult.referencedFiles.push({
path: normalizePath(refFile.fileName),
position: refFile.pos,
length: refFile. } - refFile.pos);
end);
end);
forEach(result.importedFiles, function (importedFile)
convertResult.importedFiles.push({
path: normalizeSlashes(importedFile.fileName),
position: importedFile.pos,
length: importedFile. } - importedFile.pos);
end);
end;
;
return CoreServicesShimObject;
end)(ShimBase);
return convertResult;
;
getTSConfigFileInfo(fileName, string, sourceTextSnapshot, IScriptSnapshot);
string;
{
return this.forwardJSONCall("getTSConfigFileInfo('" + fileName + "')", function ()
local text = sourceTextSnapshot.getText(0, sourceTextSnapshot.getLength());
local result = parseConfigFileText(fileName, text);
if (result.error) {
return {
options: {},
files: [],
errors: [realizeDiagnostic(result.error, '\r\n')]
};
end
local configFile = parseConfigFile(result.config, _this.host, getDirectoryPath(normalizeSlashes(fileName)));
return {
options: configFile.options,
files: configFile.fileNames,
errors: realizeDiagnostics(configFile.errors, '\r\n')
};
end);
end
getDefaultCompilationSettings();
string;
{
return this.forwardJSONCall("getDefaultCompilationSettings()", function ()
return getDefaultCompilerOptions();
end);
end
local TypeScriptServicesFactory = (function ()
local TypeScriptServicesFactory = {}
TypeScriptServicesFactory.constructor = function (this)
this._shims = [];
this.documentRegistry = createDocumentRegistry();
end;
/*
* Returns script API version.
*/
TypeScriptServicesFactory.getServicesVersion = function (this)
return servicesVersion;
end;
TypeScriptServicesFactory.createLanguageServiceShim = function (this, host)
try {
local hostAdapter = new LanguageServiceShimHostAdapter(host);
local languageService = createLanguageService(hostAdapter, this.documentRegistry);
return new LanguageServiceShimObject(this, host, languageService);
end
catch (err) {
logInternalError(host, err);
throw err;
end
end;
TypeScriptServicesFactory.createClassifierShim = function (this, logger)
try {
return new ClassifierShimObject(this, logger);
end
catch (err) {
logInternalError(logger, err);
throw err;
end
end;
TypeScriptServicesFactory.createCoreServicesShim = function (this, host)
try {
local adapter = new CoreServicesShimHostAdapter(host);
return new CoreServicesShimObject(this, host, adapter);
end
catch (err) {
logInternalError(host, err);
throw err;
end
end;
TypeScriptServicesFactory.close = function (this)
// Forget all the registered shims
this._shims = [];
this.documentRegistry = createDocumentRegistry();
end;
TypeScriptServicesFactory.registerShim = function (this, shim)
this._shims.push(shim);
end;
TypeScriptServicesFactory.unregisterShim = function (this, shim)
for (var i = 0, n = this._shims.length; i < n; i++) {
if (this._shims[i] === shim) {
delete this._shims[i];
return;
end
end
throw new Error("Invalid operation");
end;
return TypeScriptServicesFactory;
end)();
exports.TypeScriptServicesFactory = TypeScriptServicesFactory;
if (typeof module !== "undefined" && module.exports) {
module.exports = ts;
end
/// TODO: this is used by VS, clean this up on both sides of the interface
/* @internal */
local TypeScript;
(function (TypeScript) {
local Services;
(function (Services) {
Services.TypeScriptServicesFactory = ts.TypeScriptServicesFactory;
end)(Services = TypeScript.Services || (TypeScript.Services = {}));
end)(TypeScript || (TypeScript = {}));
/* @internal */
local toolsVersion = "1.4";
//# sourceMappingURL=file:///C:/Users/qujianbiao/Downloads/TypeScript-master/built/local/services/shims.js.map | freedot/tstolua | src/services/shims.js | JavaScript | apache-2.0 | 31,251 |
/*--------------------------------------------------|
| dTree 2.05 | www.destroydrop.com/javascript/tree/ |
|---------------------------------------------------|
| Copyright (c) 2002-2003 Geir Landrö |
| |
| This script can be used freely as long as all |
| copyright messages are intact. |
| |
| Updated: 17.04.2003 |
| 06.01.2005 |
|--------------------------------------------------*/
myMenu = null;
function hideMyMenu(){
if(myMenu){
myMenu.style.display = 'none';
myMenu = null;
}
}
function clickMenu(tree, url, frame) {
//parent.mainFrame.location.href=url;
if (frame == '_self')
self.location.href=url;
else if (frame == '_parent')
parent.location.href=url;
else {
var foundIndex;
for (var i = 0, found = false; i < parent.frames.length && found == false; i++) {
if (parent.frames[i].name == frame) {
found = true;
foundIndex = i;
}
}
//parent.frames[foundIndex].location.href=url + "?node=" + tree.getSelected();
parent.frames[foundIndex].location.href=url + "?node=" + tree.selectedNode;
}
}
function switchMenu() {
el=event.srcElement;
if (el.className=="menuItem") {
el.className="highlightItem";
} else if (el.className=="highlightItem") {
el.className="menuItem";
}
}
function findMax()
{
var argv = findMax.arguments;
var argc = argv.length;
var max = 0;
for (var i = 0; i < argc; i++) {
var aDiv = document.getElementById(argv[i]);
var len = aDiv.offsetWidth;
if (len > max) max = len;
}
return max;
}
// Node object
function Node(id, pid, name, url, title, target, icon, iconOpen, open, cid) {
this.id = id;
this.pid = pid;
this.name = name;
this.url = url;
this.title = title;
this.target = target;
this.icon = icon;
this.iconOpen = iconOpen;
this.cid = cid;
this._io = open || false;
this._is = false;
this._ls = false;
this._hc = false;
this._ai = 0;
this._p;
};
// Tree object
function dTree(objName, imgFolder, inFrame) {
this.config = {
target : null,
folderLinks : true,
useSelection : true,
useCookies : true,
useLines : true,
useIcons : true,
useStatusText : false,
closeSameLevel : false,
inOrder : false
}
this.icon = {
root : imgFolder + '/base.gif',
folder : imgFolder + '/folder.gif',
folderOpen : imgFolder + '/folderopen.gif',
node : imgFolder + '/page.gif',
empty : imgFolder + '/empty.gif',
line : imgFolder + '/line.gif',
join : imgFolder + '/join.gif',
joinBottom : imgFolder + '/joinbottom.gif',
plus : imgFolder + '/plus.gif',
plusBottom : imgFolder + '/plusbottom.gif',
minus : imgFolder + '/minus.gif',
minusBottom : imgFolder + '/minusbottom.gif',
nlPlus : imgFolder + '/nolines_plus.gif',
nlMinus : imgFolder + '/nolines_minus.gif'
};
this.obj = objName;
this.aNodes = [];
this.aIndent = [];
this.root = new Node(-1);
this.selectedNode = null;
this.selectedFound = false;
this.completed = false;
this.contextNode = null;
this.inFrame = inFrame;
};
// Adds a new node to the node array
dTree.prototype.add = function(id, pid, name, url, title, target, icon, iconOpen, open, cid) {
this.aNodes[this.aNodes.length] = new Node(id, pid, name, url, title, target, icon, iconOpen, open, cid);
};
// Open/close all nodes
dTree.prototype.openAll = function() {
this.oAll(true);
};
dTree.prototype.closeAll = function() {
this.oAll(false);
};
// Outputs the tree to the page
dTree.prototype.toString = function() {
var str = '<div class="dtree">\n';
if (document.getElementById) {
if (this.config.useCookies) this.selectedNode = this.getSelected();
str += this.addNode(this.root);
} else str += 'Browser not supported.';
str += '</div>';
if (!this.selectedFound) this.selectedNode = null;
this.completed = true;
return str;
};
// Creates the tree structure
dTree.prototype.addNode = function(pNode) {
var str = '';
var n=0;
if (this.config.inOrder) n = pNode._ai;
for (n; n<this.aNodes.length; n++) {
if (this.aNodes[n].pid == pNode.id) {
var cn = this.aNodes[n];
cn._p = pNode;
cn._ai = n;
this.setCS(cn);
if (!cn.target && this.config.target) cn.target = this.config.target;
if (cn._hc && !cn._io && this.config.useCookies) cn._io = this.isOpen(cn.id);
if (!this.config.folderLinks && cn._hc) cn.url = null;
if (this.config.useSelection && cn.id == this.selectedNode && !this.selectedFound) {
cn._is = true;
this.selectedNode = n;
this.selectedFound = true;
}
str += this.node(cn, n);
if (cn._ls) break;
}
}
return str;
};
// Creates the node icon, url and text
dTree.prototype.node = function(node, nodeId) {
var str = '<div class="dTreeNode">' + this.indent(node, nodeId);
if (this.config.useIcons) {
if (!node.icon) node.icon = (this.root.id == node.pid) ? this.icon.root : ((node._hc) ? this.icon.folder : this.icon.node);
if (!node.iconOpen) node.iconOpen = (node._hc) ? this.icon.folderOpen : this.icon.node;
if (this.root.id == node.pid) {
node.icon = this.icon.root;
node.iconOpen = this.icon.root;
}
str += '<img id="i' + this.obj + nodeId + '" src="' + ((node._io) ? node.iconOpen : node.icon) + '" alt="" />';
}
if (node.url) {
str += '<a id="s' + this.obj + nodeId + '" class="' + ((this.config.useSelection) ? ((node._is ? 'nodeSel' : 'node')) : 'node') + '" href="' + node.url + '"';
if (node.title) str += ' title="' + node.title + '"';
if (node.target) str += ' target="' + node.target + '"';
if (this.config.useStatusText) str += ' onmouseover="window.status=\'' + node.name + '\';return true;" onmouseout="window.status=\'\';return true;" ';
if (this.config.useSelection && ((node._hc && this.config.folderLinks) || !node._hc))
str += ' onclick="javascript: ' + this.obj + '.s(' + nodeId + ');"';
if (node.cid)
str += ' oncontextmenu="javascript: ' + this.obj + '.s(' + nodeId + ');javascript: ' + this.obj + '.popup(event,' + nodeId + ');return false;"';
str += '>';
}
else if ((!this.config.folderLinks || !node.url) && node._hc && node.pid != this.root.id)
str += '<a href="javascript: ' + this.obj + '.o(' + nodeId + ');" class="node">';
str += node.name;
if (node.url || ((!this.config.folderLinks || !node.url) && node._hc)) str += '</a>';
str += '</div>';
if (node._hc) {
str += '<div id="d' + this.obj + nodeId + '" class="clip" style="display:' + ((this.root.id == node.pid || node._io) ? 'block' : 'none') + ';">';
str += this.addNode(node);
str += '</div>';
}
this.aIndent.pop();
return str;
};
// Adds the empty and line icons
dTree.prototype.indent = function(node, nodeId) {
var str = '';
if (this.root.id != node.pid) {
for (var n=0; n<this.aIndent.length; n++)
str += '<img src="' + ( (this.aIndent[n] == 1 && this.config.useLines) ? this.icon.line : this.icon.empty ) + '" alt="" />';
(node._ls) ? this.aIndent.push(0) : this.aIndent.push(1);
if (node._hc) {
str += '<a href="javascript: ' + this.obj + '.o(' + nodeId + ');"><img id="j' + this.obj + nodeId + '" src="';
if (!this.config.useLines) str += (node._io) ? this.icon.nlMinus : this.icon.nlPlus;
else str += ( (node._io) ? ((node._ls && this.config.useLines) ? this.icon.minusBottom : this.icon.minus) : ((node._ls && this.config.useLines) ? this.icon.plusBottom : this.icon.plus ) );
str += '" alt="" /></a>';
} else str += '<img src="' + ( (this.config.useLines) ? ((node._ls) ? this.icon.joinBottom : this.icon.join ) : this.icon.empty) + '" alt="" />';
}
return str;
};
// Checks if a node has any children and if it is the last sibling
dTree.prototype.setCS = function(node) {
var lastId;
for (var n=0; n<this.aNodes.length; n++) {
if (this.aNodes[n].pid == node.id) node._hc = true;
if (this.aNodes[n].pid == node.pid) lastId = this.aNodes[n].id;
}
if (lastId==node.id) node._ls = true;
};
// Returns the selected node
dTree.prototype.getSelected = function() {
var sn = this.getCookie('cs' + this.obj);
return (sn) ? sn : null;
};
// Highlights the selected node
dTree.prototype.s = function(id) {
if (!this.config.useSelection) return;
var cn = this.aNodes[id];
if (cn._hc && !this.config.folderLinks) return;
if (this.selectedNode != id) {
if (this.selectedNode || this.selectedNode==0) {
eOld = document.getElementById("s" + this.obj + this.selectedNode);
eOld.className = "node";
}
eNew = document.getElementById("s" + this.obj + id);
eNew.className = "nodeSel";
this.selectedNode = id;
if (this.config.useCookies) this.setCookie('cs' + this.obj, cn.id);
}
};
// Remembers the context node
dTree.prototype.popup = function(e, id) {
var cn = this.aNodes[id];
if(document.all) e=window.event;
e.cancelBubble=true;
hideMyMenu();
if(!document.all){
myMenu = document.getElementById(cn.cid);
myMenu.style.left = e.pageX+'px';
myMenu.style.top = e.pageY+'px';
myMenu.style.display = 'block';
}
else {
myMenu = document.getElementById(cn.cid);
if (this.inFrame) {
myMenu.style.left = (e.clientX-15)+'px';
myMenu.style.top = (e.clientY-18)+'px';
}
else {
myMenu.style.left = (e.clientX+document.body.scrollLeft)+'px';
myMenu.style.top = (e.clientY+document.body.scrollTop)+'px';
}
myMenu.style.display = 'block';
}
if (this.contextNode != id) {
this.contextNode = id;
}
return false;
};
// Toggle Open or close
dTree.prototype.o = function(id) {
var cn = this.aNodes[id];
this.nodeStatus(!cn._io, id, cn._ls);
cn._io = !cn._io;
if (this.config.closeSameLevel) this.closeLevel(cn);
if (this.config.useCookies) this.updateCookie();
};
// Open or close all nodes
dTree.prototype.oAll = function(status) {
for (var n=0; n<this.aNodes.length; n++) {
if (this.aNodes[n]._hc && this.aNodes[n].pid != this.root.id) {
this.nodeStatus(status, n, this.aNodes[n]._ls)
this.aNodes[n]._io = status;
}
}
if (this.config.useCookies) this.updateCookie();
};
// Opens the tree to a specific node
dTree.prototype.openTo = function(nId, bSelect, bFirst) {
if (!bFirst) {
for (var n=0; n<this.aNodes.length; n++) {
if (this.aNodes[n].id == nId) {
nId=n;
break;
}
}
}
var cn=this.aNodes[nId];
if (cn.pid==this.root.id || !cn._p) return;
cn._io = true;
cn._is = bSelect;
if (this.completed && cn._hc) this.nodeStatus(true, cn._ai, cn._ls);
if (this.completed && bSelect) this.s(cn._ai);
else if (bSelect) this._sn=cn._ai;
this.openTo(cn._p._ai, false, true);
};
// Closes all nodes on the same level as certain node
dTree.prototype.closeLevel = function(node) {
for (var n=0; n<this.aNodes.length; n++) {
if (this.aNodes[n].pid == node.pid && this.aNodes[n].id != node.id && this.aNodes[n]._hc) {
this.nodeStatus(false, n, this.aNodes[n]._ls);
this.aNodes[n]._io = false;
this.closeAllChildren(this.aNodes[n]);
}
}
}
// Closes all children of a node
dTree.prototype.closeAllChildren = function(node) {
for (var n=0; n<this.aNodes.length; n++) {
if (this.aNodes[n].pid == node.id && this.aNodes[n]._hc) {
if (this.aNodes[n]._io) this.nodeStatus(false, n, this.aNodes[n]._ls);
this.aNodes[n]._io = false;
this.closeAllChildren(this.aNodes[n]);
}
}
}
// Change the status of a node(open or closed)
dTree.prototype.nodeStatus = function(status, id, bottom) {
eDiv = document.getElementById('d' + this.obj + id);
eJoin = document.getElementById('j' + this.obj + id);
if (this.config.useIcons) {
eIcon = document.getElementById('i' + this.obj + id);
eIcon.src = (status) ? this.aNodes[id].iconOpen : this.aNodes[id].icon;
}
eJoin.src = (this.config.useLines)?
((status)?((bottom)?this.icon.minusBottom:this.icon.minus):((bottom)?this.icon.plusBottom:this.icon.plus)):
((status)?this.icon.nlMinus:this.icon.nlPlus);
eDiv.style.display = (status) ? 'block': 'none';
};
// [Cookie] Clears a cookie
dTree.prototype.clearCookie = function() {
var now = new Date();
var yesterday = new Date(now.getTime() - 1000 * 60 * 60 * 24);
this.setCookie('co'+this.obj, 'cookieValue', yesterday);
this.setCookie('cs'+this.obj, 'cookieValue', yesterday);
};
// [Cookie] Sets value in a cookie
dTree.prototype.setCookie = function(cookieName, cookieValue, expires, path, domain, secure) {
document.cookie =
escape(cookieName) + '=' + escape(cookieValue)
+ (expires ? '; expires=' + expires.toGMTString() : '')
+ (path ? '; path=' + path : '')
+ (domain ? '; domain=' + domain : '')
+ (secure ? '; secure' : '');
};
// [Cookie] Gets a value from a cookie
dTree.prototype.getCookie = function(cookieName) {
var cookieValue = '';
var posName = document.cookie.indexOf(escape(cookieName) + '=');
if (posName != -1) {
var posValue = posName + (escape(cookieName) + '=').length;
var endPos = document.cookie.indexOf(';', posValue);
if (endPos != -1) cookieValue = unescape(document.cookie.substring(posValue, endPos));
else cookieValue = unescape(document.cookie.substring(posValue));
}
return (cookieValue);
};
// [Cookie] Returns ids of open nodes as a string
dTree.prototype.updateCookie = function() {
var str = '';
for (var n=0; n<this.aNodes.length; n++) {
if (this.aNodes[n]._io && this.aNodes[n].pid != this.root.id) {
if (str) str += '.';
str += this.aNodes[n].id;
}
}
this.setCookie('co' + this.obj, str);
};
// [Cookie] Checks if a node id is in a cookie
dTree.prototype.isOpen = function(id) {
var aOpen = this.getCookie('co' + this.obj).split('.');
for (var n=0; n<aOpen.length; n++)
if (aOpen[n] == id) return true;
return false;
};
// If Push and pop is not implemented by the browser
if (!Array.prototype.push) {
Array.prototype.push = function array_push() {
for(var i=0;i<arguments.length;i++)
this[this.length]=arguments[i];
return this.length;
}
};
if (!Array.prototype.pop) {
Array.prototype.pop = function array_pop() {
lastElement = this[this.length-1];
this.length = Math.max(this.length-1,0);
return lastElement;
}
}; | tomrose/singularity | component/admin/WebRoot/pragmatic-internals/js/tree/tree.js | JavaScript | apache-2.0 | 15,227 |
/*!
* reveal.js
* http://lab.hakim.se/reveal-js
* MIT licensed
*
* Copyright (C) 2017 Hakim El Hattab, http://hakim.se
*/
(function( root, factory ) {
if( typeof define === 'function' && define.amd ) {
// AMD. Register as an anonymous module.
define( function() {
root.Reveal = factory();
return root.Reveal;
} );
} else if( typeof exports === 'object' ) {
// Node. Does not work with strict CommonJS.
module.exports = factory();
} else {
// Browser globals.
root.Reveal = factory();
}
}( this, function() {
'use strict';
var Reveal;
// The reveal.js version
var VERSION = '3.5.0';
var SLIDES_SELECTOR = '.slides section',
HORIZONTAL_SLIDES_SELECTOR = '.slides>section',
VERTICAL_SLIDES_SELECTOR = '.slides>section.present>section',
HOME_SLIDE_SELECTOR = '.slides>section:first-of-type',
UA = navigator.userAgent,
// Configuration defaults, can be overridden at initialization time
config = {
// The "normal" size of the presentation, aspect ratio will be preserved
// when the presentation is scaled to fit different resolutions
width: 960,
height: 700,
// Factor of the display size that should remain empty around the content
margin: 0.04,
// Bounds for smallest/largest possible scale to apply to content
minScale: 0.2,
maxScale: 2.0,
// Display presentation control arrows
controls: true,
// Help the user learn the controls by providing hints, for example by
// bouncing the down arrow when they first encounter a vertical slide
controlsTutorial: true,
// Determines where controls appear, "edges" or "bottom-right"
controlsLayout: 'bottom-right',
// Visibility rule for backwards navigation arrows; "faded", "hidden"
// or "visible"
controlsBackArrows: 'faded',
// Display a presentation progress bar
progress: true,
// Display the page number of the current slide
slideNumber: false,
// Determine which displays to show the slide number on
showSlideNumber: 'all',
// Push each slide change to the browser history
history: false,
// Enable keyboard shortcuts for navigation
keyboard: true,
// Optional function that blocks keyboard events when retuning false
keyboardCondition: null,
// Enable the slide overview mode
overview: true,
// Vertical centering of slides
center: true,
// Enables touch navigation on devices with touch input
touch: true,
// Loop the presentation
loop: false,
// Change the presentation direction to be RTL
rtl: false,
// Randomizes the order of slides each time the presentation loads
shuffle: false,
// Turns fragments on and off globally
fragments: true,
// Flags if the presentation is running in an embedded mode,
// i.e. contained within a limited portion of the screen
embedded: false,
// Flags if we should show a help overlay when the question-mark
// key is pressed
help: true,
// Flags if it should be possible to pause the presentation (blackout)
pause: true,
// Flags if speaker notes should be visible to all viewers
showNotes: false,
// Global override for autolaying embedded media (video/audio/iframe)
// - null: Media will only autoplay if data-autoplay is present
// - true: All media will autoplay, regardless of individual setting
// - false: No media will autoplay, regardless of individual setting
autoPlayMedia: null,
// Number of milliseconds between automatically proceeding to the
// next slide, disabled when set to 0, this value can be overwritten
// by using a data-autoslide attribute on your slides
autoSlide: 0,
// Stop auto-sliding after user input
autoSlideStoppable: true,
// Use this method for navigation when auto-sliding (defaults to navigateNext)
autoSlideMethod: null,
// Enable slide navigation via mouse wheel
mouseWheel: false,
// Apply a 3D roll to links on hover
rollingLinks: false,
// Hides the address bar on mobile devices
hideAddressBar: true,
// Opens links in an iframe preview overlay
previewLinks: false,
// Exposes the reveal.js API through window.postMessage
postMessage: true,
// Dispatches all reveal.js events to the parent window through postMessage
postMessageEvents: false,
// Focuses body when page changes visibility to ensure keyboard shortcuts work
focusBodyOnPageVisibilityChange: true,
// Transition style
transition: 'slide', // none/fade/slide/convex/concave/zoom
// Transition speed
transitionSpeed: 'default', // default/fast/slow
// Transition style for full page slide backgrounds
backgroundTransition: 'fade', // none/fade/slide/convex/concave/zoom
// Parallax background image
parallaxBackgroundImage: '', // CSS syntax, e.g. "a.jpg"
// Parallax background size
parallaxBackgroundSize: '', // CSS syntax, e.g. "3000px 2000px"
// Amount of pixels to move the parallax background per slide step
parallaxBackgroundHorizontal: null,
parallaxBackgroundVertical: null,
// The maximum number of pages a single slide can expand onto when printing
// to PDF, unlimited by default
pdfMaxPagesPerSlide: Number.POSITIVE_INFINITY,
// Offset used to reduce the height of content within exported PDF pages.
// This exists to account for environment differences based on how you
// print to PDF. CLI printing options, like phantomjs and wkpdf, can end
// on precisely the total height of the document whereas in-browser
// printing has to end one pixel before.
pdfPageHeightOffset: -1,
// Number of slides away from the current that are visible
viewDistance: 3,
// The display mode that will be used to show slides
display: 'block',
// Script dependencies to load
dependencies: []
},
// Flags if Reveal.initialize() has been called
initialized = false,
// Flags if reveal.js is loaded (has dispatched the 'ready' event)
loaded = false,
// Flags if the overview mode is currently active
overview = false,
// Holds the dimensions of our overview slides, including margins
overviewSlideWidth = null,
overviewSlideHeight = null,
// The horizontal and vertical index of the currently active slide
indexh,
indexv,
// The previous and current slide HTML elements
previousSlide,
currentSlide,
previousBackground,
// Remember which directions that the user has navigated towards
hasNavigatedRight = false,
hasNavigatedDown = false,
// Slides may hold a data-state attribute which we pick up and apply
// as a class to the body. This list contains the combined state of
// all current slides.
state = [],
// The current scale of the presentation (see width/height config)
scale = 1,
// CSS transform that is currently applied to the slides container,
// split into two groups
slidesTransform = { layout: '', overview: '' },
// Cached references to DOM elements
dom = {},
// Features supported by the browser, see #checkCapabilities()
features = {},
// Client is a mobile device, see #checkCapabilities()
isMobileDevice,
// Client is a desktop Chrome, see #checkCapabilities()
isChrome,
// Throttles mouse wheel navigation
lastMouseWheelStep = 0,
// Delays updates to the URL due to a Chrome thumbnailer bug
writeURLTimeout = 0,
// Flags if the interaction event listeners are bound
eventsAreBound = false,
// The current auto-slide duration
autoSlide = 0,
// Auto slide properties
autoSlidePlayer,
autoSlideTimeout = 0,
autoSlideStartTime = -1,
autoSlidePaused = false,
// Holds information about the currently ongoing touch input
touch = {
startX: 0,
startY: 0,
startSpan: 0,
startCount: 0,
captured: false,
threshold: 40
},
// Holds information about the keyboard shortcuts
keyboardShortcuts = {
'N , SPACE': 'Next slide',
'P': 'Previous slide',
'← , H': 'Navigate left',
'→ , L': 'Navigate right',
'↑ , K': 'Navigate up',
'↓ , J': 'Navigate down',
'Home': 'First slide',
'End': 'Last slide',
'B , .': 'Pause',
'F': 'Fullscreen',
'ESC, O': 'Slide overview'
};
/**
* Starts up the presentation if the client is capable.
*/
function initialize( options ) {
// Make sure we only initialize once
if( initialized === true ) return;
initialized = true;
checkCapabilities();
if( !features.transforms2d && !features.transforms3d ) {
document.body.setAttribute( 'class', 'no-transforms' );
// Since JS won't be running any further, we load all lazy
// loading elements upfront
var images = toArray( document.getElementsByTagName( 'img' ) ),
iframes = toArray( document.getElementsByTagName( 'iframe' ) );
var lazyLoadable = images.concat( iframes );
for( var i = 0, len = lazyLoadable.length; i < len; i++ ) {
var element = lazyLoadable[i];
if( element.getAttribute( 'data-src' ) ) {
element.setAttribute( 'src', element.getAttribute( 'data-src' ) );
element.removeAttribute( 'data-src' );
}
}
// If the browser doesn't support core features we won't be
// using JavaScript to control the presentation
return;
}
// Cache references to key DOM elements
dom.wrapper = document.querySelector( '.reveal' );
dom.slides = document.querySelector( '.reveal .slides' );
// Force a layout when the whole page, incl fonts, has loaded
window.addEventListener( 'load', layout, false );
var query = Reveal.getQueryHash();
// Do not accept new dependencies via query config to avoid
// the potential of malicious script injection
if( typeof query['dependencies'] !== 'undefined' ) delete query['dependencies'];
// Copy options over to our config object
extend( config, options );
extend( config, query );
// Hide the address bar in mobile browsers
hideAddressBar();
// Loads the dependencies and continues to #start() once done
load();
}
/**
* Inspect the client to see what it's capable of, this
* should only happens once per runtime.
*/
function checkCapabilities() {
isMobileDevice = /(iphone|ipod|ipad|android)/gi.test( UA );
isChrome = /chrome/i.test( UA ) && !/edge/i.test( UA );
var testElement = document.createElement( 'div' );
features.transforms3d = 'WebkitPerspective' in testElement.style ||
'MozPerspective' in testElement.style ||
'msPerspective' in testElement.style ||
'OPerspective' in testElement.style ||
'perspective' in testElement.style;
features.transforms2d = 'WebkitTransform' in testElement.style ||
'MozTransform' in testElement.style ||
'msTransform' in testElement.style ||
'OTransform' in testElement.style ||
'transform' in testElement.style;
features.requestAnimationFrameMethod = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame;
features.requestAnimationFrame = typeof features.requestAnimationFrameMethod === 'function';
features.canvas = !!document.createElement( 'canvas' ).getContext;
// Transitions in the overview are disabled in desktop and
// Safari due to lag
features.overviewTransitions = !/Version\/[\d\.]+.*Safari/.test( UA );
// Flags if we should use zoom instead of transform to scale
// up slides. Zoom produces crisper results but has a lot of
// xbrowser quirks so we only use it in whitelsited browsers.
features.zoom = 'zoom' in testElement.style && !isMobileDevice &&
( isChrome || /Version\/[\d\.]+.*Safari/.test( UA ) );
}
/**
* Loads the dependencies of reveal.js. Dependencies are
* defined via the configuration option 'dependencies'
* and will be loaded prior to starting/binding reveal.js.
* Some dependencies may have an 'async' flag, if so they
* will load after reveal.js has been started up.
*/
function load() {
var scripts = [],
scriptsAsync = [],
scriptsToPreload = 0;
// Called once synchronous scripts finish loading
function proceed() {
if( scriptsAsync.length ) {
// Load asynchronous scripts
head.js.apply( null, scriptsAsync );
}
start();
}
function loadScript( s ) {
head.ready( s.src.match( /([\w\d_\-]*)\.?js$|[^\\\/]*$/i )[0], function() {
// Extension may contain callback functions
if( typeof s.callback === 'function' ) {
s.callback.apply( this );
}
if( --scriptsToPreload === 0 ) {
proceed();
}
});
}
for( var i = 0, len = config.dependencies.length; i < len; i++ ) {
var s = config.dependencies[i];
// Load if there's no condition or the condition is truthy
if( !s.condition || s.condition() ) {
if( s.async ) {
scriptsAsync.push( s.src );
}
else {
scripts.push( s.src );
}
loadScript( s );
}
}
if( scripts.length ) {
scriptsToPreload = scripts.length;
// Load synchronous scripts
head.js.apply( null, scripts );
}
else {
proceed();
}
}
/**
* Starts up reveal.js by binding input events and navigating
* to the current URL deeplink if there is one.
*/
function start() {
// Make sure we've got all the DOM elements we need
setupDOM();
// Listen to messages posted to this window
setupPostMessage();
// Prevent the slides from being scrolled out of view
setupScrollPrevention();
// Resets all vertical slides so that only the first is visible
resetVerticalSlides();
// Updates the presentation to match the current configuration values
configure();
// Read the initial hash
readURL();
// Update all backgrounds
updateBackground( true );
// Notify listeners that the presentation is ready but use a 1ms
// timeout to ensure it's not fired synchronously after #initialize()
setTimeout( function() {
// Enable transitions now that we're loaded
dom.slides.classList.remove( 'no-transition' );
loaded = true;
dom.wrapper.classList.add( 'ready' );
dispatchEvent( 'ready', {
'indexh': indexh,
'indexv': indexv,
'currentSlide': currentSlide
} );
}, 1 );
// Special setup and config is required when printing to PDF
if( isPrintingPDF() ) {
removeEventListeners();
// The document needs to have loaded for the PDF layout
// measurements to be accurate
if( document.readyState === 'complete' ) {
setupPDF();
}
else {
window.addEventListener( 'load', setupPDF );
}
}
}
/**
* Finds and stores references to DOM elements which are
* required by the presentation. If a required element is
* not found, it is created.
*/
function setupDOM() {
// Prevent transitions while we're loading
dom.slides.classList.add( 'no-transition' );
if( isMobileDevice ) {
dom.wrapper.classList.add( 'no-hover' );
}
else {
dom.wrapper.classList.remove( 'no-hover' );
}
// Background element
dom.background = createSingletonNode( dom.wrapper, 'div', 'backgrounds', null );
// Progress bar
dom.progress = createSingletonNode( dom.wrapper, 'div', 'progress', '<span></span>' );
dom.progressbar = dom.progress.querySelector( 'span' );
// Arrow controls
dom.controls = createSingletonNode( dom.wrapper, 'aside', 'controls',
'<button class="navigate-left" aria-label="previous slide"><div class="controls-arrow"></div></button>' +
'<button class="navigate-right" aria-label="next slide"><div class="controls-arrow"></div></button>' +
'<button class="navigate-up" aria-label="above slide"><div class="controls-arrow"></div></button>' +
'<button class="navigate-down" aria-label="below slide"><div class="controls-arrow"></div></button>' );
// Slide number
dom.slideNumber = createSingletonNode( dom.wrapper, 'div', 'slide-number', '' );
// Element containing notes that are visible to the audience
dom.speakerNotes = createSingletonNode( dom.wrapper, 'div', 'speaker-notes', null );
dom.speakerNotes.setAttribute( 'data-prevent-swipe', '' );
dom.speakerNotes.setAttribute( 'tabindex', '0' );
// Overlay graphic which is displayed during the paused mode
createSingletonNode( dom.wrapper, 'div', 'pause-overlay', null );
dom.wrapper.setAttribute( 'role', 'application' );
// There can be multiple instances of controls throughout the page
dom.controlsLeft = toArray( document.querySelectorAll( '.navigate-left' ) );
dom.controlsRight = toArray( document.querySelectorAll( '.navigate-right' ) );
dom.controlsUp = toArray( document.querySelectorAll( '.navigate-up' ) );
dom.controlsDown = toArray( document.querySelectorAll( '.navigate-down' ) );
dom.controlsPrev = toArray( document.querySelectorAll( '.navigate-prev' ) );
dom.controlsNext = toArray( document.querySelectorAll( '.navigate-next' ) );
// The right and down arrows in the standard reveal.js controls
dom.controlsRightArrow = dom.controls.querySelector( '.navigate-right' );
dom.controlsDownArrow = dom.controls.querySelector( '.navigate-down' );
dom.statusDiv = createStatusDiv();
}
/**
* Creates a hidden div with role aria-live to announce the
* current slide content. Hide the div off-screen to make it
* available only to Assistive Technologies.
*
* @return {HTMLElement}
*/
function createStatusDiv() {
var statusDiv = document.getElementById( 'aria-status-div' );
if( !statusDiv ) {
statusDiv = document.createElement( 'div' );
statusDiv.style.position = 'absolute';
statusDiv.style.height = '1px';
statusDiv.style.width = '1px';
statusDiv.style.overflow = 'hidden';
statusDiv.style.clip = 'rect( 1px, 1px, 1px, 1px )';
statusDiv.setAttribute( 'id', 'aria-status-div' );
statusDiv.setAttribute( 'aria-live', 'polite' );
statusDiv.setAttribute( 'aria-atomic','true' );
dom.wrapper.appendChild( statusDiv );
}
return statusDiv;
}
/**
* Converts the given HTML element into a string of text
* that can be announced to a screen reader. Hidden
* elements are excluded.
*/
function getStatusText( node ) {
var text = '';
// Text node
if( node.nodeType === 3 ) {
text += node.textContent;
}
// Element node
else if( node.nodeType === 1 ) {
var isAriaHidden = node.getAttribute( 'aria-hidden' );
var isDisplayHidden = window.getComputedStyle( node )['display'] === 'none';
if( isAriaHidden !== 'true' && !isDisplayHidden ) {
toArray( node.childNodes ).forEach( function( child ) {
text += getStatusText( child );
} );
}
}
return text;
}
/**
* Configures the presentation for printing to a static
* PDF.
*/
function setupPDF() {
var slideSize = getComputedSlideSize( window.innerWidth, window.innerHeight );
// Dimensions of the PDF pages
var pageWidth = Math.floor( slideSize.width * ( 1 + config.margin ) ),
pageHeight = Math.floor( slideSize.height * ( 1 + config.margin ) );
// Dimensions of slides within the pages
var slideWidth = slideSize.width,
slideHeight = slideSize.height;
// Let the browser know what page size we want to print
injectStyleSheet( '@page{size:'+ pageWidth +'px '+ pageHeight +'px; margin: 0px;}' );
// Limit the size of certain elements to the dimensions of the slide
injectStyleSheet( '.reveal section>img, .reveal section>video, .reveal section>iframe{max-width: '+ slideWidth +'px; max-height:'+ slideHeight +'px}' );
document.body.classList.add( 'print-pdf' );
document.body.style.width = pageWidth + 'px';
document.body.style.height = pageHeight + 'px';
// Make sure stretch elements fit on slide
layoutSlideContents( slideWidth, slideHeight );
// Add each slide's index as attributes on itself, we need these
// indices to generate slide numbers below
toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ).forEach( function( hslide, h ) {
hslide.setAttribute( 'data-index-h', h );
if( hslide.classList.contains( 'stack' ) ) {
toArray( hslide.querySelectorAll( 'section' ) ).forEach( function( vslide, v ) {
vslide.setAttribute( 'data-index-h', h );
vslide.setAttribute( 'data-index-v', v );
} );
}
} );
// Slide and slide background layout
toArray( dom.wrapper.querySelectorAll( SLIDES_SELECTOR ) ).forEach( function( slide ) {
// Vertical stacks are not centred since their section
// children will be
if( slide.classList.contains( 'stack' ) === false ) {
// Center the slide inside of the page, giving the slide some margin
var left = ( pageWidth - slideWidth ) / 2,
top = ( pageHeight - slideHeight ) / 2;
var contentHeight = slide.scrollHeight;
var numberOfPages = Math.max( Math.ceil( contentHeight / pageHeight ), 1 );
// Adhere to configured pages per slide limit
numberOfPages = Math.min( numberOfPages, config.pdfMaxPagesPerSlide );
// Center slides vertically
if( numberOfPages === 1 && config.center || slide.classList.contains( 'center' ) ) {
top = Math.max( ( pageHeight - contentHeight ) / 2, 0 );
}
// Wrap the slide in a page element and hide its overflow
// so that no page ever flows onto another
var page = document.createElement( 'div' );
page.className = 'pdf-page';
page.style.height = ( ( pageHeight + config.pdfPageHeightOffset ) * numberOfPages ) + 'px';
slide.parentNode.insertBefore( page, slide );
page.appendChild( slide );
// Position the slide inside of the page
slide.style.left = left + 'px';
slide.style.top = top + 'px';
slide.style.width = slideWidth + 'px';
if( slide.slideBackgroundElement ) {
page.insertBefore( slide.slideBackgroundElement, slide );
}
// Inject notes if `showNotes` is enabled
if( config.showNotes ) {
// Are there notes for this slide?
var notes = getSlideNotes( slide );
if( notes ) {
var notesSpacing = 8;
var notesLayout = typeof config.showNotes === 'string' ? config.showNotes : 'inline';
var notesElement = document.createElement( 'div' );
notesElement.classList.add( 'speaker-notes' );
notesElement.classList.add( 'speaker-notes-pdf' );
notesElement.setAttribute( 'data-layout', notesLayout );
notesElement.innerHTML = notes;
if( notesLayout === 'separate-page' ) {
page.parentNode.insertBefore( notesElement, page.nextSibling );
}
else {
notesElement.style.left = notesSpacing + 'px';
notesElement.style.bottom = notesSpacing + 'px';
notesElement.style.width = ( pageWidth - notesSpacing*2 ) + 'px';
page.appendChild( notesElement );
}
}
}
// Inject slide numbers if `slideNumbers` are enabled
if( config.slideNumber && /all|print/i.test( config.showSlideNumber ) ) {
var slideNumberH = parseInt( slide.getAttribute( 'data-index-h' ), 10 ) + 1,
slideNumberV = parseInt( slide.getAttribute( 'data-index-v' ), 10 ) + 1;
var numberElement = document.createElement( 'div' );
numberElement.classList.add( 'slide-number' );
numberElement.classList.add( 'slide-number-pdf' );
numberElement.innerHTML = formatSlideNumber( slideNumberH, '.', slideNumberV );
page.appendChild( numberElement );
}
}
} );
// Show all fragments
toArray( dom.wrapper.querySelectorAll( SLIDES_SELECTOR + ' .fragment' ) ).forEach( function( fragment ) {
fragment.classList.add( 'visible' );
} );
// Notify subscribers that the PDF layout is good to go
dispatchEvent( 'pdf-ready' );
}
/**
* This is an unfortunate necessity. Some actions – such as
* an input field being focused in an iframe or using the
* keyboard to expand text selection beyond the bounds of
* a slide – can trigger our content to be pushed out of view.
* This scrolling can not be prevented by hiding overflow in
* CSS (we already do) so we have to resort to repeatedly
* checking if the slides have been offset :(
*/
function setupScrollPrevention() {
setInterval( function() {
if( dom.wrapper.scrollTop !== 0 || dom.wrapper.scrollLeft !== 0 ) {
dom.wrapper.scrollTop = 0;
dom.wrapper.scrollLeft = 0;
}
}, 1000 );
}
/**
* Creates an HTML element and returns a reference to it.
* If the element already exists the existing instance will
* be returned.
*
* @param {HTMLElement} container
* @param {string} tagname
* @param {string} classname
* @param {string} innerHTML
*
* @return {HTMLElement}
*/
function createSingletonNode( container, tagname, classname, innerHTML ) {
// Find all nodes matching the description
var nodes = container.querySelectorAll( '.' + classname );
// Check all matches to find one which is a direct child of
// the specified container
for( var i = 0; i < nodes.length; i++ ) {
var testNode = nodes[i];
if( testNode.parentNode === container ) {
return testNode;
}
}
// If no node was found, create it now
var node = document.createElement( tagname );
node.className = classname;
if( typeof innerHTML === 'string' ) {
node.innerHTML = innerHTML;
}
container.appendChild( node );
return node;
}
/**
* Creates the slide background elements and appends them
* to the background container. One element is created per
* slide no matter if the given slide has visible background.
*/
function createBackgrounds() {
var printMode = isPrintingPDF();
// Clear prior backgrounds
dom.background.innerHTML = '';
dom.background.classList.add( 'no-transition' );
// Iterate over all horizontal slides
toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ).forEach( function( slideh ) {
var backgroundStack = createBackground( slideh, dom.background );
// Iterate over all vertical slides
toArray( slideh.querySelectorAll( 'section' ) ).forEach( function( slidev ) {
createBackground( slidev, backgroundStack );
backgroundStack.classList.add( 'stack' );
} );
} );
// Add parallax background if specified
if( config.parallaxBackgroundImage ) {
dom.background.style.backgroundImage = 'url("' + config.parallaxBackgroundImage + '")';
dom.background.style.backgroundSize = config.parallaxBackgroundSize;
// Make sure the below properties are set on the element - these properties are
// needed for proper transitions to be set on the element via CSS. To remove
// annoying background slide-in effect when the presentation starts, apply
// these properties after short time delay
setTimeout( function() {
dom.wrapper.classList.add( 'has-parallax-background' );
}, 1 );
}
else {
dom.background.style.backgroundImage = '';
dom.wrapper.classList.remove( 'has-parallax-background' );
}
}
/**
* Creates a background for the given slide.
*
* @param {HTMLElement} slide
* @param {HTMLElement} container The element that the background
* should be appended to
* @return {HTMLElement} New background div
*/
function createBackground( slide, container ) {
var data = {
background: slide.getAttribute( 'data-background' ),
backgroundSize: slide.getAttribute( 'data-background-size' ),
backgroundImage: slide.getAttribute( 'data-background-image' ),
backgroundVideo: slide.getAttribute( 'data-background-video' ),
backgroundIframe: slide.getAttribute( 'data-background-iframe' ),
backgroundColor: slide.getAttribute( 'data-background-color' ),
backgroundRepeat: slide.getAttribute( 'data-background-repeat' ),
backgroundPosition: slide.getAttribute( 'data-background-position' ),
backgroundTransition: slide.getAttribute( 'data-background-transition' )
};
var element = document.createElement( 'div' );
// Carry over custom classes from the slide to the background
element.className = 'slide-background ' + slide.className.replace( /present|past|future/, '' );
if( data.background ) {
// Auto-wrap image urls in url(...)
if( /^(http|file|\/\/)/gi.test( data.background ) || /\.(svg|png|jpg|jpeg|gif|bmp)([?#]|$)/gi.test( data.background ) ) {
slide.setAttribute( 'data-background-image', data.background );
}
else {
element.style.background = data.background;
}
}
// Create a hash for this combination of background settings.
// This is used to determine when two slide backgrounds are
// the same.
if( data.background || data.backgroundColor || data.backgroundImage || data.backgroundVideo || data.backgroundIframe ) {
element.setAttribute( 'data-background-hash', data.background +
data.backgroundSize +
data.backgroundImage +
data.backgroundVideo +
data.backgroundIframe +
data.backgroundColor +
data.backgroundRepeat +
data.backgroundPosition +
data.backgroundTransition );
}
// Additional and optional background properties
if( data.backgroundSize ) element.style.backgroundSize = data.backgroundSize;
if( data.backgroundSize ) element.setAttribute( 'data-background-size', data.backgroundSize );
if( data.backgroundColor ) element.style.backgroundColor = data.backgroundColor;
if( data.backgroundRepeat ) element.style.backgroundRepeat = data.backgroundRepeat;
if( data.backgroundPosition ) element.style.backgroundPosition = data.backgroundPosition;
if( data.backgroundTransition ) element.setAttribute( 'data-background-transition', data.backgroundTransition );
container.appendChild( element );
// If backgrounds are being recreated, clear old classes
slide.classList.remove( 'has-dark-background' );
slide.classList.remove( 'has-light-background' );
slide.slideBackgroundElement = element;
// If this slide has a background color, add a class that
// signals if it is light or dark. If the slide has no background
// color, no class will be set
var computedBackgroundStyle = window.getComputedStyle( element );
if( computedBackgroundStyle && computedBackgroundStyle.backgroundColor ) {
var rgb = colorToRgb( computedBackgroundStyle.backgroundColor );
// Ignore fully transparent backgrounds. Some browsers return
// rgba(0,0,0,0) when reading the computed background color of
// an element with no background
if( rgb && rgb.a !== 0 ) {
if( colorBrightness( computedBackgroundStyle.backgroundColor ) < 128 ) {
slide.classList.add( 'has-dark-background' );
}
else {
slide.classList.add( 'has-light-background' );
}
}
}
return element;
}
/**
* Registers a listener to postMessage events, this makes it
* possible to call all reveal.js API methods from another
* window. For example:
*
* revealWindow.postMessage( JSON.stringify({
* method: 'slide',
* args: [ 2 ]
* }), '*' );
*/
function setupPostMessage() {
if( config.postMessage ) {
window.addEventListener( 'message', function ( event ) {
var data = event.data;
// Make sure we're dealing with JSON
if( typeof data === 'string' && data.charAt( 0 ) === '{' && data.charAt( data.length - 1 ) === '}' ) {
data = JSON.parse( data );
// Check if the requested method can be found
if( data.method && typeof Reveal[data.method] === 'function' ) {
Reveal[data.method].apply( Reveal, data.args );
}
}
}, false );
}
}
/**
* Applies the configuration settings from the config
* object. May be called multiple times.
*
* @param {object} options
*/
function configure( options ) {
var numberOfSlides = dom.wrapper.querySelectorAll( SLIDES_SELECTOR ).length;
dom.wrapper.classList.remove( config.transition );
// New config options may be passed when this method
// is invoked through the API after initialization
if( typeof options === 'object' ) extend( config, options );
// Force linear transition based on browser capabilities
if( features.transforms3d === false ) config.transition = 'linear';
dom.wrapper.classList.add( config.transition );
dom.wrapper.setAttribute( 'data-transition-speed', config.transitionSpeed );
dom.wrapper.setAttribute( 'data-background-transition', config.backgroundTransition );
dom.controls.style.display = config.controls ? 'block' : 'none';
dom.progress.style.display = config.progress ? 'block' : 'none';
dom.controls.setAttribute( 'data-controls-layout', config.controlsLayout );
dom.controls.setAttribute( 'data-controls-back-arrows', config.controlsBackArrows );
if( config.shuffle ) {
shuffle();
}
if( config.rtl ) {
dom.wrapper.classList.add( 'rtl' );
}
else {
dom.wrapper.classList.remove( 'rtl' );
}
if( config.center ) {
dom.wrapper.classList.add( 'center' );
}
else {
dom.wrapper.classList.remove( 'center' );
}
// Exit the paused mode if it was configured off
if( config.pause === false ) {
resume();
}
if( config.showNotes ) {
dom.speakerNotes.setAttribute( 'data-layout', typeof config.showNotes === 'string' ? config.showNotes : 'inline' );
}
if( config.mouseWheel ) {
document.addEventListener( 'DOMMouseScroll', onDocumentMouseScroll, false ); // FF
document.addEventListener( 'mousewheel', onDocumentMouseScroll, false );
}
else {
document.removeEventListener( 'DOMMouseScroll', onDocumentMouseScroll, false ); // FF
document.removeEventListener( 'mousewheel', onDocumentMouseScroll, false );
}
// Rolling 3D links
if( config.rollingLinks ) {
enableRollingLinks();
}
else {
disableRollingLinks();
}
// Iframe link previews
if( config.previewLinks ) {
enablePreviewLinks();
disablePreviewLinks( '[data-preview-link=false]' );
}
else {
disablePreviewLinks();
enablePreviewLinks( '[data-preview-link]:not([data-preview-link=false])' );
}
// Remove existing auto-slide controls
if( autoSlidePlayer ) {
autoSlidePlayer.destroy();
autoSlidePlayer = null;
}
// Generate auto-slide controls if needed
if( numberOfSlides > 1 && config.autoSlide && config.autoSlideStoppable && features.canvas && features.requestAnimationFrame ) {
autoSlidePlayer = new Playback( dom.wrapper, function() {
return Math.min( Math.max( ( Date.now() - autoSlideStartTime ) / autoSlide, 0 ), 1 );
} );
autoSlidePlayer.on( 'click', onAutoSlidePlayerClick );
autoSlidePaused = false;
}
// When fragments are turned off they should be visible
if( config.fragments === false ) {
toArray( dom.slides.querySelectorAll( '.fragment' ) ).forEach( function( element ) {
element.classList.add( 'visible' );
element.classList.remove( 'current-fragment' );
} );
}
// Slide numbers
var slideNumberDisplay = 'none';
if( config.slideNumber && !isPrintingPDF() ) {
if( config.showSlideNumber === 'all' ) {
slideNumberDisplay = 'block';
}
else if( config.showSlideNumber === 'speaker' && isSpeakerNotes() ) {
slideNumberDisplay = 'block';
}
}
dom.slideNumber.style.display = slideNumberDisplay;
sync();
}
/**
* Binds all event listeners.
*/
function addEventListeners() {
eventsAreBound = true;
window.addEventListener( 'hashchange', onWindowHashChange, false );
window.addEventListener( 'resize', onWindowResize, false );
if( config.touch ) {
dom.wrapper.addEventListener( 'touchstart', onTouchStart, false );
dom.wrapper.addEventListener( 'touchmove', onTouchMove, false );
dom.wrapper.addEventListener( 'touchend', onTouchEnd, false );
// Support pointer-style touch interaction as well
if( window.navigator.pointerEnabled ) {
// IE 11 uses un-prefixed version of pointer events
dom.wrapper.addEventListener( 'pointerdown', onPointerDown, false );
dom.wrapper.addEventListener( 'pointermove', onPointerMove, false );
dom.wrapper.addEventListener( 'pointerup', onPointerUp, false );
}
else if( window.navigator.msPointerEnabled ) {
// IE 10 uses prefixed version of pointer events
dom.wrapper.addEventListener( 'MSPointerDown', onPointerDown, false );
dom.wrapper.addEventListener( 'MSPointerMove', onPointerMove, false );
dom.wrapper.addEventListener( 'MSPointerUp', onPointerUp, false );
}
}
if( config.keyboard ) {
document.addEventListener( 'keydown', onDocumentKeyDown, false );
document.addEventListener( 'keypress', onDocumentKeyPress, false );
}
if( config.progress && dom.progress ) {
dom.progress.addEventListener( 'click', onProgressClicked, false );
}
if( config.focusBodyOnPageVisibilityChange ) {
var visibilityChange;
if( 'hidden' in document ) {
visibilityChange = 'visibilitychange';
}
else if( 'msHidden' in document ) {
visibilityChange = 'msvisibilitychange';
}
else if( 'webkitHidden' in document ) {
visibilityChange = 'webkitvisibilitychange';
}
if( visibilityChange ) {
document.addEventListener( visibilityChange, onPageVisibilityChange, false );
}
}
// Listen to both touch and click events, in case the device
// supports both
var pointerEvents = [ 'touchstart', 'click' ];
// Only support touch for Android, fixes double navigations in
// stock browser
if( UA.match( /android/gi ) ) {
pointerEvents = [ 'touchstart' ];
}
pointerEvents.forEach( function( eventName ) {
dom.controlsLeft.forEach( function( el ) { el.addEventListener( eventName, onNavigateLeftClicked, false ); } );
dom.controlsRight.forEach( function( el ) { el.addEventListener( eventName, onNavigateRightClicked, false ); } );
dom.controlsUp.forEach( function( el ) { el.addEventListener( eventName, onNavigateUpClicked, false ); } );
dom.controlsDown.forEach( function( el ) { el.addEventListener( eventName, onNavigateDownClicked, false ); } );
dom.controlsPrev.forEach( function( el ) { el.addEventListener( eventName, onNavigatePrevClicked, false ); } );
dom.controlsNext.forEach( function( el ) { el.addEventListener( eventName, onNavigateNextClicked, false ); } );
} );
}
/**
* Unbinds all event listeners.
*/
function removeEventListeners() {
eventsAreBound = false;
document.removeEventListener( 'keydown', onDocumentKeyDown, false );
document.removeEventListener( 'keypress', onDocumentKeyPress, false );
window.removeEventListener( 'hashchange', onWindowHashChange, false );
window.removeEventListener( 'resize', onWindowResize, false );
dom.wrapper.removeEventListener( 'touchstart', onTouchStart, false );
dom.wrapper.removeEventListener( 'touchmove', onTouchMove, false );
dom.wrapper.removeEventListener( 'touchend', onTouchEnd, false );
// IE11
if( window.navigator.pointerEnabled ) {
dom.wrapper.removeEventListener( 'pointerdown', onPointerDown, false );
dom.wrapper.removeEventListener( 'pointermove', onPointerMove, false );
dom.wrapper.removeEventListener( 'pointerup', onPointerUp, false );
}
// IE10
else if( window.navigator.msPointerEnabled ) {
dom.wrapper.removeEventListener( 'MSPointerDown', onPointerDown, false );
dom.wrapper.removeEventListener( 'MSPointerMove', onPointerMove, false );
dom.wrapper.removeEventListener( 'MSPointerUp', onPointerUp, false );
}
if ( config.progress && dom.progress ) {
dom.progress.removeEventListener( 'click', onProgressClicked, false );
}
[ 'touchstart', 'click' ].forEach( function( eventName ) {
dom.controlsLeft.forEach( function( el ) { el.removeEventListener( eventName, onNavigateLeftClicked, false ); } );
dom.controlsRight.forEach( function( el ) { el.removeEventListener( eventName, onNavigateRightClicked, false ); } );
dom.controlsUp.forEach( function( el ) { el.removeEventListener( eventName, onNavigateUpClicked, false ); } );
dom.controlsDown.forEach( function( el ) { el.removeEventListener( eventName, onNavigateDownClicked, false ); } );
dom.controlsPrev.forEach( function( el ) { el.removeEventListener( eventName, onNavigatePrevClicked, false ); } );
dom.controlsNext.forEach( function( el ) { el.removeEventListener( eventName, onNavigateNextClicked, false ); } );
} );
}
/**
* Extend object a with the properties of object b.
* If there's a conflict, object b takes precedence.
*
* @param {object} a
* @param {object} b
*/
function extend( a, b ) {
for( var i in b ) {
a[ i ] = b[ i ];
}
}
/**
* Converts the target object to an array.
*
* @param {object} o
* @return {object[]}
*/
function toArray( o ) {
return Array.prototype.slice.call( o );
}
/**
* Utility for deserializing a value.
*
* @param {*} value
* @return {*}
*/
function deserialize( value ) {
if( typeof value === 'string' ) {
if( value === 'null' ) return null;
else if( value === 'true' ) return true;
else if( value === 'false' ) return false;
else if( value.match( /^[\d\.]+$/ ) ) return parseFloat( value );
}
return value;
}
/**
* Measures the distance in pixels between point a
* and point b.
*
* @param {object} a point with x/y properties
* @param {object} b point with x/y properties
*
* @return {number}
*/
function distanceBetween( a, b ) {
var dx = a.x - b.x,
dy = a.y - b.y;
return Math.sqrt( dx*dx + dy*dy );
}
/**
* Applies a CSS transform to the target element.
*
* @param {HTMLElement} element
* @param {string} transform
*/
function transformElement( element, transform ) {
element.style.WebkitTransform = transform;
element.style.MozTransform = transform;
element.style.msTransform = transform;
element.style.transform = transform;
}
/**
* Applies CSS transforms to the slides container. The container
* is transformed from two separate sources: layout and the overview
* mode.
*
* @param {object} transforms
*/
function transformSlides( transforms ) {
// Pick up new transforms from arguments
if( typeof transforms.layout === 'string' ) slidesTransform.layout = transforms.layout;
if( typeof transforms.overview === 'string' ) slidesTransform.overview = transforms.overview;
// Apply the transforms to the slides container
if( slidesTransform.layout ) {
transformElement( dom.slides, slidesTransform.layout + ' ' + slidesTransform.overview );
}
else {
transformElement( dom.slides, slidesTransform.overview );
}
}
/**
* Injects the given CSS styles into the DOM.
*
* @param {string} value
*/
function injectStyleSheet( value ) {
var tag = document.createElement( 'style' );
tag.type = 'text/css';
if( tag.styleSheet ) {
tag.styleSheet.cssText = value;
}
else {
tag.appendChild( document.createTextNode( value ) );
}
document.getElementsByTagName( 'head' )[0].appendChild( tag );
}
/**
* Find the closest parent that matches the given
* selector.
*
* @param {HTMLElement} target The child element
* @param {String} selector The CSS selector to match
* the parents against
*
* @return {HTMLElement} The matched parent or null
* if no matching parent was found
*/
function closestParent( target, selector ) {
var parent = target.parentNode;
while( parent ) {
// There's some overhead doing this each time, we don't
// want to rewrite the element prototype but should still
// be enough to feature detect once at startup...
var matchesMethod = parent.matches || parent.matchesSelector || parent.msMatchesSelector;
// If we find a match, we're all set
if( matchesMethod && matchesMethod.call( parent, selector ) ) {
return parent;
}
// Keep searching
parent = parent.parentNode;
}
return null;
}
/**
* Converts various color input formats to an {r:0,g:0,b:0} object.
*
* @param {string} color The string representation of a color
* @example
* colorToRgb('#000');
* @example
* colorToRgb('#000000');
* @example
* colorToRgb('rgb(0,0,0)');
* @example
* colorToRgb('rgba(0,0,0)');
*
* @return {{r: number, g: number, b: number, [a]: number}|null}
*/
function colorToRgb( color ) {
var hex3 = color.match( /^#([0-9a-f]{3})$/i );
if( hex3 && hex3[1] ) {
hex3 = hex3[1];
return {
r: parseInt( hex3.charAt( 0 ), 16 ) * 0x11,
g: parseInt( hex3.charAt( 1 ), 16 ) * 0x11,
b: parseInt( hex3.charAt( 2 ), 16 ) * 0x11
};
}
var hex6 = color.match( /^#([0-9a-f]{6})$/i );
if( hex6 && hex6[1] ) {
hex6 = hex6[1];
return {
r: parseInt( hex6.substr( 0, 2 ), 16 ),
g: parseInt( hex6.substr( 2, 2 ), 16 ),
b: parseInt( hex6.substr( 4, 2 ), 16 )
};
}
var rgb = color.match( /^rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/i );
if( rgb ) {
return {
r: parseInt( rgb[1], 10 ),
g: parseInt( rgb[2], 10 ),
b: parseInt( rgb[3], 10 )
};
}
var rgba = color.match( /^rgba\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\,\s*([\d]+|[\d]*.[\d]+)\s*\)$/i );
if( rgba ) {
return {
r: parseInt( rgba[1], 10 ),
g: parseInt( rgba[2], 10 ),
b: parseInt( rgba[3], 10 ),
a: parseFloat( rgba[4] )
};
}
return null;
}
/**
* Calculates brightness on a scale of 0-255.
*
* @param {string} color See colorToRgb for supported formats.
* @see {@link colorToRgb}
*/
function colorBrightness( color ) {
if( typeof color === 'string' ) color = colorToRgb( color );
if( color ) {
return ( color.r * 299 + color.g * 587 + color.b * 114 ) / 1000;
}
return null;
}
/**
* Returns the remaining height within the parent of the
* target element.
*
* remaining height = [ configured parent height ] - [ current parent height ]
*
* @param {HTMLElement} element
* @param {number} [height]
*/
function getRemainingHeight( element, height ) {
height = height || 0;
if( element ) {
var newHeight, oldHeight = element.style.height;
// Change the .stretch element height to 0 in order find the height of all
// the other elements
element.style.height = '0px';
newHeight = height - element.parentNode.offsetHeight;
// Restore the old height, just in case
element.style.height = oldHeight + 'px';
return newHeight;
}
return height;
}
/**
* Checks if this instance is being used to print a PDF.
*/
function isPrintingPDF() {
return ( /print-pdf/gi ).test( window.location.search );
}
/**
* Hides the address bar if we're on a mobile device.
*/
function hideAddressBar() {
if( config.hideAddressBar && isMobileDevice ) {
// Events that should trigger the address bar to hide
window.addEventListener( 'load', removeAddressBar, false );
window.addEventListener( 'orientationchange', removeAddressBar, false );
}
}
/**
* Causes the address bar to hide on mobile devices,
* more vertical space ftw.
*/
function removeAddressBar() {
setTimeout( function() {
window.scrollTo( 0, 1 );
}, 10 );
}
/**
* Dispatches an event of the specified type from the
* reveal DOM element.
*/
function dispatchEvent( type, args ) {
var event = document.createEvent( 'HTMLEvents', 1, 2 );
event.initEvent( type, true, true );
extend( event, args );
dom.wrapper.dispatchEvent( event );
// If we're in an iframe, post each reveal.js event to the
// parent window. Used by the notes plugin
if( config.postMessageEvents && window.parent !== window.self ) {
window.parent.postMessage( JSON.stringify({ namespace: 'reveal', eventName: type, state: getState() }), '*' );
}
}
/**
* Wrap all links in 3D goodness.
*/
function enableRollingLinks() {
if( features.transforms3d && !( 'msPerspective' in document.body.style ) ) {
var anchors = dom.wrapper.querySelectorAll( SLIDES_SELECTOR + ' a' );
for( var i = 0, len = anchors.length; i < len; i++ ) {
var anchor = anchors[i];
if( anchor.textContent && !anchor.querySelector( '*' ) && ( !anchor.className || !anchor.classList.contains( anchor, 'roll' ) ) ) {
var span = document.createElement('span');
span.setAttribute('data-title', anchor.text);
span.innerHTML = anchor.innerHTML;
anchor.classList.add( 'roll' );
anchor.innerHTML = '';
anchor.appendChild(span);
}
}
}
}
/**
* Unwrap all 3D links.
*/
function disableRollingLinks() {
var anchors = dom.wrapper.querySelectorAll( SLIDES_SELECTOR + ' a.roll' );
for( var i = 0, len = anchors.length; i < len; i++ ) {
var anchor = anchors[i];
var span = anchor.querySelector( 'span' );
if( span ) {
anchor.classList.remove( 'roll' );
anchor.innerHTML = span.innerHTML;
}
}
}
/**
* Bind preview frame links.
*
* @param {string} [selector=a] - selector for anchors
*/
function enablePreviewLinks( selector ) {
var anchors = toArray( document.querySelectorAll( selector ? selector : 'a' ) );
anchors.forEach( function( element ) {
if( /^(http|www)/gi.test( element.getAttribute( 'href' ) ) ) {
element.addEventListener( 'click', onPreviewLinkClicked, false );
}
} );
}
/**
* Unbind preview frame links.
*/
function disablePreviewLinks( selector ) {
var anchors = toArray( document.querySelectorAll( selector ? selector : 'a' ) );
anchors.forEach( function( element ) {
if( /^(http|www)/gi.test( element.getAttribute( 'href' ) ) ) {
element.removeEventListener( 'click', onPreviewLinkClicked, false );
}
} );
}
/**
* Opens a preview window for the target URL.
*
* @param {string} url - url for preview iframe src
*/
function showPreview( url ) {
closeOverlay();
dom.overlay = document.createElement( 'div' );
dom.overlay.classList.add( 'overlay' );
dom.overlay.classList.add( 'overlay-preview' );
dom.wrapper.appendChild( dom.overlay );
dom.overlay.innerHTML = [
'<header>',
'<a class="close" href="#"><span class="icon"></span></a>',
'<a class="external" href="'+ url +'" target="_blank"><span class="icon"></span></a>',
'</header>',
'<div class="spinner"></div>',
'<div class="viewport">',
'<iframe src="'+ url +'"></iframe>',
'<small class="viewport-inner">',
'<span class="x-frame-error">Unable to load iframe. This is likely due to the site\'s policy (x-frame-options).</span>',
'</small>',
'</div>'
].join('');
dom.overlay.querySelector( 'iframe' ).addEventListener( 'load', function( event ) {
dom.overlay.classList.add( 'loaded' );
}, false );
dom.overlay.querySelector( '.close' ).addEventListener( 'click', function( event ) {
closeOverlay();
event.preventDefault();
}, false );
dom.overlay.querySelector( '.external' ).addEventListener( 'click', function( event ) {
closeOverlay();
}, false );
setTimeout( function() {
dom.overlay.classList.add( 'visible' );
}, 1 );
}
/**
* Open or close help overlay window.
*
* @param {Boolean} [override] Flag which overrides the
* toggle logic and forcibly sets the desired state. True means
* help is open, false means it's closed.
*/
function toggleHelp( override ){
if( typeof override === 'boolean' ) {
override ? showHelp() : closeOverlay();
}
else {
if( dom.overlay ) {
closeOverlay();
}
else {
showHelp();
}
}
}
/**
* Opens an overlay window with help material.
*/
function showHelp() {
if( config.help ) {
closeOverlay();
dom.overlay = document.createElement( 'div' );
dom.overlay.classList.add( 'overlay' );
dom.overlay.classList.add( 'overlay-help' );
dom.wrapper.appendChild( dom.overlay );
var html = '<p class="title">Keyboard Shortcuts</p><br/>';
html += '<table><th>KEY</th><th>ACTION</th>';
for( var key in keyboardShortcuts ) {
html += '<tr><td>' + key + '</td><td>' + keyboardShortcuts[ key ] + '</td></tr>';
}
html += '</table>';
dom.overlay.innerHTML = [
'<header>',
'<a class="close" href="#"><span class="icon"></span></a>',
'</header>',
'<div class="viewport">',
'<div class="viewport-inner">'+ html +'</div>',
'</div>'
].join('');
dom.overlay.querySelector( '.close' ).addEventListener( 'click', function( event ) {
closeOverlay();
event.preventDefault();
}, false );
setTimeout( function() {
dom.overlay.classList.add( 'visible' );
}, 1 );
}
}
/**
* Closes any currently open overlay.
*/
function closeOverlay() {
if( dom.overlay ) {
dom.overlay.parentNode.removeChild( dom.overlay );
dom.overlay = null;
}
}
/**
* Applies JavaScript-controlled layout rules to the
* presentation.
*/
function layout() {
if( dom.wrapper && !isPrintingPDF() ) {
var size = getComputedSlideSize();
// Layout the contents of the slides
layoutSlideContents( config.width, config.height );
dom.slides.style.width = size.width + 'px';
dom.slides.style.height = size.height + 'px';
// Determine scale of content to fit within available space
scale = Math.min( size.presentationWidth / size.width, size.presentationHeight / size.height );
// Respect max/min scale settings
scale = Math.max( scale, config.minScale );
scale = Math.min( scale, config.maxScale );
// Don't apply any scaling styles if scale is 1
if( scale === 1 ) {
dom.slides.style.zoom = '';
dom.slides.style.left = '';
dom.slides.style.top = '';
dom.slides.style.bottom = '';
dom.slides.style.right = '';
transformSlides( { layout: '' } );
}
else {
// Prefer zoom for scaling up so that content remains crisp.
// Don't use zoom to scale down since that can lead to shifts
// in text layout/line breaks.
if( scale > 1 && features.zoom ) {
dom.slides.style.zoom = scale;
dom.slides.style.left = '';
dom.slides.style.top = '';
dom.slides.style.bottom = '';
dom.slides.style.right = '';
transformSlides( { layout: '' } );
}
// Apply scale transform as a fallback
else {
dom.slides.style.zoom = '';
dom.slides.style.left = '50%';
dom.slides.style.top = '50%';
dom.slides.style.bottom = 'auto';
dom.slides.style.right = 'auto';
transformSlides( { layout: 'translate(-50%, -50%) scale('+ scale +')' } );
}
}
// Select all slides, vertical and horizontal
var slides = toArray( dom.wrapper.querySelectorAll( SLIDES_SELECTOR ) );
for( var i = 0, len = slides.length; i < len; i++ ) {
var slide = slides[ i ];
// Don't bother updating invisible slides
if( slide.style.display === 'none' ) {
continue;
}
if( config.center || slide.classList.contains( 'center' ) ) {
// Vertical stacks are not centred since their section
// children will be
if( slide.classList.contains( 'stack' ) ) {
slide.style.top = 0;
}
else {
slide.style.top = Math.max( ( size.height - slide.scrollHeight ) / 2, 0 ) + 'px';
}
}
else {
slide.style.top = '';
}
}
updateProgress();
updateParallax();
if( isOverview() ) {
updateOverview();
}
}
}
/**
* Applies layout logic to the contents of all slides in
* the presentation.
*
* @param {string|number} width
* @param {string|number} height
*/
function layoutSlideContents( width, height ) {
// Handle sizing of elements with the 'stretch' class
toArray( dom.slides.querySelectorAll( 'section > .stretch' ) ).forEach( function( element ) {
// Determine how much vertical space we can use
var remainingHeight = getRemainingHeight( element, height );
// Consider the aspect ratio of media elements
if( /(img|video)/gi.test( element.nodeName ) ) {
var nw = element.naturalWidth || element.videoWidth,
nh = element.naturalHeight || element.videoHeight;
var es = Math.min( width / nw, remainingHeight / nh );
element.style.width = ( nw * es ) + 'px';
element.style.height = ( nh * es ) + 'px';
}
else {
element.style.width = width + 'px';
element.style.height = remainingHeight + 'px';
}
} );
}
/**
* Calculates the computed pixel size of our slides. These
* values are based on the width and height configuration
* options.
*
* @param {number} [presentationWidth=dom.wrapper.offsetWidth]
* @param {number} [presentationHeight=dom.wrapper.offsetHeight]
*/
function getComputedSlideSize( presentationWidth, presentationHeight ) {
var size = {
// Slide size
width: config.width,
height: config.height,
// Presentation size
presentationWidth: presentationWidth || dom.wrapper.offsetWidth,
presentationHeight: presentationHeight || dom.wrapper.offsetHeight
};
// Reduce available space by margin
size.presentationWidth -= ( size.presentationWidth * config.margin );
size.presentationHeight -= ( size.presentationHeight * config.margin );
// Slide width may be a percentage of available width
if( typeof size.width === 'string' && /%$/.test( size.width ) ) {
size.width = parseInt( size.width, 10 ) / 100 * size.presentationWidth;
}
// Slide height may be a percentage of available height
if( typeof size.height === 'string' && /%$/.test( size.height ) ) {
size.height = parseInt( size.height, 10 ) / 100 * size.presentationHeight;
}
return size;
}
/**
* Stores the vertical index of a stack so that the same
* vertical slide can be selected when navigating to and
* from the stack.
*
* @param {HTMLElement} stack The vertical stack element
* @param {string|number} [v=0] Index to memorize
*/
function setPreviousVerticalIndex( stack, v ) {
if( typeof stack === 'object' && typeof stack.setAttribute === 'function' ) {
stack.setAttribute( 'data-previous-indexv', v || 0 );
}
}
/**
* Retrieves the vertical index which was stored using
* #setPreviousVerticalIndex() or 0 if no previous index
* exists.
*
* @param {HTMLElement} stack The vertical stack element
*/
function getPreviousVerticalIndex( stack ) {
if( typeof stack === 'object' && typeof stack.setAttribute === 'function' && stack.classList.contains( 'stack' ) ) {
// Prefer manually defined start-indexv
var attributeName = stack.hasAttribute( 'data-start-indexv' ) ? 'data-start-indexv' : 'data-previous-indexv';
return parseInt( stack.getAttribute( attributeName ) || 0, 10 );
}
return 0;
}
/**
* Displays the overview of slides (quick nav) by scaling
* down and arranging all slide elements.
*/
function activateOverview() {
// Only proceed if enabled in config
if( config.overview && !isOverview() ) {
overview = true;
dom.wrapper.classList.add( 'overview' );
dom.wrapper.classList.remove( 'overview-deactivating' );
if( features.overviewTransitions ) {
setTimeout( function() {
dom.wrapper.classList.add( 'overview-animated' );
}, 1 );
}
// Don't auto-slide while in overview mode
cancelAutoSlide();
// Move the backgrounds element into the slide container to
// that the same scaling is applied
dom.slides.appendChild( dom.background );
// Clicking on an overview slide navigates to it
toArray( dom.wrapper.querySelectorAll( SLIDES_SELECTOR ) ).forEach( function( slide ) {
if( !slide.classList.contains( 'stack' ) ) {
slide.addEventListener( 'click', onOverviewSlideClicked, true );
}
} );
// Calculate slide sizes
var margin = 70;
var slideSize = getComputedSlideSize();
overviewSlideWidth = slideSize.width + margin;
overviewSlideHeight = slideSize.height + margin;
// Reverse in RTL mode
if( config.rtl ) {
overviewSlideWidth = -overviewSlideWidth;
}
updateSlidesVisibility();
layoutOverview();
updateOverview();
layout();
// Notify observers of the overview showing
dispatchEvent( 'overviewshown', {
'indexh': indexh,
'indexv': indexv,
'currentSlide': currentSlide
} );
}
}
/**
* Uses CSS transforms to position all slides in a grid for
* display inside of the overview mode.
*/
function layoutOverview() {
// Layout slides
toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ).forEach( function( hslide, h ) {
hslide.setAttribute( 'data-index-h', h );
transformElement( hslide, 'translate3d(' + ( h * overviewSlideWidth ) + 'px, 0, 0)' );
if( hslide.classList.contains( 'stack' ) ) {
toArray( hslide.querySelectorAll( 'section' ) ).forEach( function( vslide, v ) {
vslide.setAttribute( 'data-index-h', h );
vslide.setAttribute( 'data-index-v', v );
transformElement( vslide, 'translate3d(0, ' + ( v * overviewSlideHeight ) + 'px, 0)' );
} );
}
} );
// Layout slide backgrounds
toArray( dom.background.childNodes ).forEach( function( hbackground, h ) {
transformElement( hbackground, 'translate3d(' + ( h * overviewSlideWidth ) + 'px, 0, 0)' );
toArray( hbackground.querySelectorAll( '.slide-background' ) ).forEach( function( vbackground, v ) {
transformElement( vbackground, 'translate3d(0, ' + ( v * overviewSlideHeight ) + 'px, 0)' );
} );
} );
}
/**
* Moves the overview viewport to the current slides.
* Called each time the current slide changes.
*/
function updateOverview() {
var vmin = Math.min( window.innerWidth, window.innerHeight );
var scale = Math.max( vmin / 5, 150 ) / vmin;
transformSlides( {
overview: [
'scale('+ scale +')',
'translateX('+ ( -indexh * overviewSlideWidth ) +'px)',
'translateY('+ ( -indexv * overviewSlideHeight ) +'px)'
].join( ' ' )
} );
}
/**
* Exits the slide overview and enters the currently
* active slide.
*/
function deactivateOverview() {
// Only proceed if enabled in config
if( config.overview ) {
overview = false;
dom.wrapper.classList.remove( 'overview' );
dom.wrapper.classList.remove( 'overview-animated' );
// Temporarily add a class so that transitions can do different things
// depending on whether they are exiting/entering overview, or just
// moving from slide to slide
dom.wrapper.classList.add( 'overview-deactivating' );
setTimeout( function () {
dom.wrapper.classList.remove( 'overview-deactivating' );
}, 1 );
// Move the background element back out
dom.wrapper.appendChild( dom.background );
// Clean up changes made to slides
toArray( dom.wrapper.querySelectorAll( SLIDES_SELECTOR ) ).forEach( function( slide ) {
transformElement( slide, '' );
slide.removeEventListener( 'click', onOverviewSlideClicked, true );
} );
// Clean up changes made to backgrounds
toArray( dom.background.querySelectorAll( '.slide-background' ) ).forEach( function( background ) {
transformElement( background, '' );
} );
transformSlides( { overview: '' } );
slide( indexh, indexv );
layout();
cueAutoSlide();
// Notify observers of the overview hiding
dispatchEvent( 'overviewhidden', {
'indexh': indexh,
'indexv': indexv,
'currentSlide': currentSlide
} );
}
}
/**
* Toggles the slide overview mode on and off.
*
* @param {Boolean} [override] Flag which overrides the
* toggle logic and forcibly sets the desired state. True means
* overview is open, false means it's closed.
*/
function toggleOverview( override ) {
if( typeof override === 'boolean' ) {
override ? activateOverview() : deactivateOverview();
}
else {
isOverview() ? deactivateOverview() : activateOverview();
}
}
/**
* Checks if the overview is currently active.
*
* @return {Boolean} true if the overview is active,
* false otherwise
*/
function isOverview() {
return overview;
}
/**
* Checks if the current or specified slide is vertical
* (nested within another slide).
*
* @param {HTMLElement} [slide=currentSlide] The slide to check
* orientation of
* @return {Boolean}
*/
function isVerticalSlide( slide ) {
// Prefer slide argument, otherwise use current slide
slide = slide ? slide : currentSlide;
return slide && slide.parentNode && !!slide.parentNode.nodeName.match( /section/i );
}
/**
* Handling the fullscreen functionality via the fullscreen API
*
* @see http://fullscreen.spec.whatwg.org/
* @see https://developer.mozilla.org/en-US/docs/DOM/Using_fullscreen_mode
*/
function enterFullscreen() {
var element = document.documentElement;
// Check which implementation is available
var requestMethod = element.requestFullscreen ||
element.webkitRequestFullscreen ||
element.webkitRequestFullScreen ||
element.mozRequestFullScreen ||
element.msRequestFullscreen;
if( requestMethod ) {
requestMethod.apply( element );
}
}
/**
* Enters the paused mode which fades everything on screen to
* black.
*/
function pause() {
if( config.pause ) {
var wasPaused = dom.wrapper.classList.contains( 'paused' );
cancelAutoSlide();
dom.wrapper.classList.add( 'paused' );
if( wasPaused === false ) {
dispatchEvent( 'paused' );
}
}
}
/**
* Exits from the paused mode.
*/
function resume() {
var wasPaused = dom.wrapper.classList.contains( 'paused' );
dom.wrapper.classList.remove( 'paused' );
cueAutoSlide();
if( wasPaused ) {
dispatchEvent( 'resumed' );
}
}
/**
* Toggles the paused mode on and off.
*/
function togglePause( override ) {
if( typeof override === 'boolean' ) {
override ? pause() : resume();
}
else {
isPaused() ? resume() : pause();
}
}
/**
* Checks if we are currently in the paused mode.
*
* @return {Boolean}
*/
function isPaused() {
return dom.wrapper.classList.contains( 'paused' );
}
/**
* Toggles the auto slide mode on and off.
*
* @param {Boolean} [override] Flag which sets the desired state.
* True means autoplay starts, false means it stops.
*/
function toggleAutoSlide( override ) {
if( typeof override === 'boolean' ) {
override ? resumeAutoSlide() : pauseAutoSlide();
}
else {
autoSlidePaused ? resumeAutoSlide() : pauseAutoSlide();
}
}
/**
* Checks if the auto slide mode is currently on.
*
* @return {Boolean}
*/
function isAutoSliding() {
return !!( autoSlide && !autoSlidePaused );
}
/**
* Steps from the current point in the presentation to the
* slide which matches the specified horizontal and vertical
* indices.
*
* @param {number} [h=indexh] Horizontal index of the target slide
* @param {number} [v=indexv] Vertical index of the target slide
* @param {number} [f] Index of a fragment within the
* target slide to activate
* @param {number} [o] Origin for use in multimaster environments
*/
function slide( h, v, f, o ) {
// Remember where we were at before
previousSlide = currentSlide;
// Query all horizontal slides in the deck
var horizontalSlides = dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR );
// Abort if there are no slides
if( horizontalSlides.length === 0 ) return;
// If no vertical index is specified and the upcoming slide is a
// stack, resume at its previous vertical index
if( v === undefined && !isOverview() ) {
v = getPreviousVerticalIndex( horizontalSlides[ h ] );
}
// If we were on a vertical stack, remember what vertical index
// it was on so we can resume at the same position when returning
if( previousSlide && previousSlide.parentNode && previousSlide.parentNode.classList.contains( 'stack' ) ) {
setPreviousVerticalIndex( previousSlide.parentNode, indexv );
}
// Remember the state before this slide
var stateBefore = state.concat();
// Reset the state array
state.length = 0;
var indexhBefore = indexh || 0,
indexvBefore = indexv || 0;
// Activate and transition to the new slide
indexh = updateSlides( HORIZONTAL_SLIDES_SELECTOR, h === undefined ? indexh : h );
indexv = updateSlides( VERTICAL_SLIDES_SELECTOR, v === undefined ? indexv : v );
// Update the visibility of slides now that the indices have changed
updateSlidesVisibility();
layout();
// Apply the new state
stateLoop: for( var i = 0, len = state.length; i < len; i++ ) {
// Check if this state existed on the previous slide. If it
// did, we will avoid adding it repeatedly
for( var j = 0; j < stateBefore.length; j++ ) {
if( stateBefore[j] === state[i] ) {
stateBefore.splice( j, 1 );
continue stateLoop;
}
}
document.documentElement.classList.add( state[i] );
// Dispatch custom event matching the state's name
dispatchEvent( state[i] );
}
// Clean up the remains of the previous state
while( stateBefore.length ) {
document.documentElement.classList.remove( stateBefore.pop() );
}
// Update the overview if it's currently active
if( isOverview() ) {
updateOverview();
}
// Find the current horizontal slide and any possible vertical slides
// within it
var currentHorizontalSlide = horizontalSlides[ indexh ],
currentVerticalSlides = currentHorizontalSlide.querySelectorAll( 'section' );
// Store references to the previous and current slides
currentSlide = currentVerticalSlides[ indexv ] || currentHorizontalSlide;
// Show fragment, if specified
if( typeof f !== 'undefined' ) {
navigateFragment( f );
}
// Dispatch an event if the slide changed
var slideChanged = ( indexh !== indexhBefore || indexv !== indexvBefore );
if( slideChanged ) {
dispatchEvent( 'slidechanged', {
'indexh': indexh,
'indexv': indexv,
'previousSlide': previousSlide,
'currentSlide': currentSlide,
'origin': o
} );
}
else {
// Ensure that the previous slide is never the same as the current
previousSlide = null;
}
// Solves an edge case where the previous slide maintains the
// 'present' class when navigating between adjacent vertical
// stacks
if( previousSlide ) {
previousSlide.classList.remove( 'present' );
previousSlide.setAttribute( 'aria-hidden', 'true' );
// Reset all slides upon navigate to home
// Issue: #285
if ( dom.wrapper.querySelector( HOME_SLIDE_SELECTOR ).classList.contains( 'present' ) ) {
// Launch async task
setTimeout( function () {
var slides = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR + '.stack') ), i;
for( i in slides ) {
if( slides[i] ) {
// Reset stack
setPreviousVerticalIndex( slides[i], 0 );
}
}
}, 0 );
}
}
// Handle embedded content
if( slideChanged || !previousSlide ) {
stopEmbeddedContent( previousSlide );
startEmbeddedContent( currentSlide );
}
// Announce the current slide contents, for screen readers
dom.statusDiv.textContent = getStatusText( currentSlide );
updateControls();
updateProgress();
updateBackground();
updateParallax();
updateSlideNumber();
updateNotes();
// Update the URL hash
writeURL();
cueAutoSlide();
}
/**
* Syncs the presentation with the current DOM. Useful
* when new slides or control elements are added or when
* the configuration has changed.
*/
function sync() {
// Subscribe to input
removeEventListeners();
addEventListeners();
// Force a layout to make sure the current config is accounted for
layout();
// Reflect the current autoSlide value
autoSlide = config.autoSlide;
// Start auto-sliding if it's enabled
cueAutoSlide();
// Re-create the slide backgrounds
createBackgrounds();
// Write the current hash to the URL
writeURL();
sortAllFragments();
updateControls();
updateProgress();
updateSlideNumber();
updateSlidesVisibility();
updateBackground( true );
updateNotesVisibility();
updateNotes();
formatEmbeddedContent();
// Start or stop embedded content depending on global config
if( config.autoPlayMedia === false ) {
stopEmbeddedContent( currentSlide );
}
else {
startEmbeddedContent( currentSlide );
}
if( isOverview() ) {
layoutOverview();
}
}
/**
* Resets all vertical slides so that only the first
* is visible.
*/
function resetVerticalSlides() {
var horizontalSlides = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) );
horizontalSlides.forEach( function( horizontalSlide ) {
var verticalSlides = toArray( horizontalSlide.querySelectorAll( 'section' ) );
verticalSlides.forEach( function( verticalSlide, y ) {
if( y > 0 ) {
verticalSlide.classList.remove( 'present' );
verticalSlide.classList.remove( 'past' );
verticalSlide.classList.add( 'future' );
verticalSlide.setAttribute( 'aria-hidden', 'true' );
}
} );
} );
}
/**
* Sorts and formats all of fragments in the
* presentation.
*/
function sortAllFragments() {
var horizontalSlides = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) );
horizontalSlides.forEach( function( horizontalSlide ) {
var verticalSlides = toArray( horizontalSlide.querySelectorAll( 'section' ) );
verticalSlides.forEach( function( verticalSlide, y ) {
sortFragments( verticalSlide.querySelectorAll( '.fragment' ) );
} );
if( verticalSlides.length === 0 ) sortFragments( horizontalSlide.querySelectorAll( '.fragment' ) );
} );
}
/**
* Randomly shuffles all slides in the deck.
*/
function shuffle() {
var slides = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) );
slides.forEach( function( slide ) {
// Insert this slide next to another random slide. This may
// cause the slide to insert before itself but that's fine.
dom.slides.insertBefore( slide, slides[ Math.floor( Math.random() * slides.length ) ] );
} );
}
/**
* Updates one dimension of slides by showing the slide
* with the specified index.
*
* @param {string} selector A CSS selector that will fetch
* the group of slides we are working with
* @param {number} index The index of the slide that should be
* shown
*
* @return {number} The index of the slide that is now shown,
* might differ from the passed in index if it was out of
* bounds.
*/
function updateSlides( selector, index ) {
// Select all slides and convert the NodeList result to
// an array
var slides = toArray( dom.wrapper.querySelectorAll( selector ) ),
slidesLength = slides.length;
var printMode = isPrintingPDF();
if( slidesLength ) {
// Should the index loop?
if( config.loop ) {
index %= slidesLength;
if( index < 0 ) {
index = slidesLength + index;
}
}
// Enforce max and minimum index bounds
index = Math.max( Math.min( index, slidesLength - 1 ), 0 );
for( var i = 0; i < slidesLength; i++ ) {
var element = slides[i];
var reverse = config.rtl && !isVerticalSlide( element );
element.classList.remove( 'past' );
element.classList.remove( 'present' );
element.classList.remove( 'future' );
// http://www.w3.org/html/wg/drafts/html/master/editing.html#the-hidden-attribute
element.setAttribute( 'hidden', '' );
element.setAttribute( 'aria-hidden', 'true' );
// If this element contains vertical slides
if( element.querySelector( 'section' ) ) {
element.classList.add( 'stack' );
}
// If we're printing static slides, all slides are "present"
if( printMode ) {
element.classList.add( 'present' );
continue;
}
if( i < index ) {
// Any element previous to index is given the 'past' class
element.classList.add( reverse ? 'future' : 'past' );
if( config.fragments ) {
var pastFragments = toArray( element.querySelectorAll( '.fragment' ) );
// Show all fragments on prior slides
while( pastFragments.length ) {
var pastFragment = pastFragments.pop();
pastFragment.classList.add( 'visible' );
pastFragment.classList.remove( 'current-fragment' );
}
}
}
else if( i > index ) {
// Any element subsequent to index is given the 'future' class
element.classList.add( reverse ? 'past' : 'future' );
if( config.fragments ) {
var futureFragments = toArray( element.querySelectorAll( '.fragment.visible' ) );
// No fragments in future slides should be visible ahead of time
while( futureFragments.length ) {
var futureFragment = futureFragments.pop();
futureFragment.classList.remove( 'visible' );
futureFragment.classList.remove( 'current-fragment' );
}
}
}
}
// Mark the current slide as present
slides[index].classList.add( 'present' );
slides[index].removeAttribute( 'hidden' );
slides[index].removeAttribute( 'aria-hidden' );
// If this slide has a state associated with it, add it
// onto the current state of the deck
var slideState = slides[index].getAttribute( 'data-state' );
if( slideState ) {
state = state.concat( slideState.split( ' ' ) );
}
}
else {
// Since there are no slides we can't be anywhere beyond the
// zeroth index
index = 0;
}
return index;
}
/**
* Optimization method; hide all slides that are far away
* from the present slide.
*/
function updateSlidesVisibility() {
// Select all slides and convert the NodeList result to
// an array
var horizontalSlides = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ),
horizontalSlidesLength = horizontalSlides.length,
distanceX,
distanceY;
if( horizontalSlidesLength && typeof indexh !== 'undefined' ) {
// The number of steps away from the present slide that will
// be visible
var viewDistance = isOverview() ? 10 : config.viewDistance;
// Limit view distance on weaker devices
if( isMobileDevice ) {
viewDistance = isOverview() ? 6 : 2;
}
// All slides need to be visible when exporting to PDF
if( isPrintingPDF() ) {
viewDistance = Number.MAX_VALUE;
}
for( var x = 0; x < horizontalSlidesLength; x++ ) {
var horizontalSlide = horizontalSlides[x];
var verticalSlides = toArray( horizontalSlide.querySelectorAll( 'section' ) ),
verticalSlidesLength = verticalSlides.length;
// Determine how far away this slide is from the present
distanceX = Math.abs( ( indexh || 0 ) - x ) || 0;
// If the presentation is looped, distance should measure
// 1 between the first and last slides
if( config.loop ) {
distanceX = Math.abs( ( ( indexh || 0 ) - x ) % ( horizontalSlidesLength - viewDistance ) ) || 0;
}
// Show the horizontal slide if it's within the view distance
if( distanceX < viewDistance ) {
showSlide( horizontalSlide );
}
else {
hideSlide( horizontalSlide );
}
if( verticalSlidesLength ) {
var oy = getPreviousVerticalIndex( horizontalSlide );
for( var y = 0; y < verticalSlidesLength; y++ ) {
var verticalSlide = verticalSlides[y];
distanceY = x === ( indexh || 0 ) ? Math.abs( ( indexv || 0 ) - y ) : Math.abs( y - oy );
if( distanceX + distanceY < viewDistance ) {
showSlide( verticalSlide );
}
else {
hideSlide( verticalSlide );
}
}
}
}
// Flag if there are ANY vertical slides, anywhere in the deck
if( dom.wrapper.querySelectorAll( '.slides>section>section' ).length ) {
dom.wrapper.classList.add( 'has-vertical-slides' );
}
else {
dom.wrapper.classList.remove( 'has-vertical-slides' );
}
// Flag if there are ANY horizontal slides, anywhere in the deck
if( dom.wrapper.querySelectorAll( '.slides>section' ).length > 1 ) {
dom.wrapper.classList.add( 'has-horizontal-slides' );
}
else {
dom.wrapper.classList.remove( 'has-horizontal-slides' );
}
}
}
/**
* Pick up notes from the current slide and display them
* to the viewer.
*
* @see {@link config.showNotes}
*/
function updateNotes() {
if( config.showNotes && dom.speakerNotes && currentSlide && !isPrintingPDF() ) {
dom.speakerNotes.innerHTML = getSlideNotes() || '<span class="notes-placeholder">No notes on this slide.</span>';
}
}
/**
* Updates the visibility of the speaker notes sidebar that
* is used to share annotated slides. The notes sidebar is
* only visible if showNotes is true and there are notes on
* one or more slides in the deck.
*/
function updateNotesVisibility() {
if( config.showNotes && hasNotes() ) {
dom.wrapper.classList.add( 'show-notes' );
}
else {
dom.wrapper.classList.remove( 'show-notes' );
}
}
/**
* Checks if there are speaker notes for ANY slide in the
* presentation.
*/
function hasNotes() {
return dom.slides.querySelectorAll( '[data-notes], aside.notes' ).length > 0;
}
/**
* Updates the progress bar to reflect the current slide.
*/
function updateProgress() {
// Update progress if enabled
if( config.progress && dom.progressbar ) {
dom.progressbar.style.width = getProgress() * dom.wrapper.offsetWidth + 'px';
}
}
/**
* Updates the slide number div to reflect the current slide.
*
* The following slide number formats are available:
* "h.v": horizontal . vertical slide number (default)
* "h/v": horizontal / vertical slide number
* "c": flattened slide number
* "c/t": flattened slide number / total slides
*/
function updateSlideNumber() {
// Update slide number if enabled
if( config.slideNumber && dom.slideNumber ) {
var value = [];
var format = 'h.v';
// Check if a custom number format is available
if( typeof config.slideNumber === 'string' ) {
format = config.slideNumber;
}
switch( format ) {
case 'c':
value.push( getSlidePastCount() + 1 );
break;
case 'c/t':
value.push( getSlidePastCount() + 1, '/', getTotalSlides() );
break;
case 'h/v':
value.push( indexh + 1 );
if( isVerticalSlide() ) value.push( '/', indexv + 1 );
break;
default:
value.push( indexh + 1 );
if( isVerticalSlide() ) value.push( '.', indexv + 1 );
}
dom.slideNumber.innerHTML = formatSlideNumber( value[0], value[1], value[2] );
}
}
/**
* Applies HTML formatting to a slide number before it's
* written to the DOM.
*
* @param {number} a Current slide
* @param {string} delimiter Character to separate slide numbers
* @param {(number|*)} b Total slides
* @return {string} HTML string fragment
*/
function formatSlideNumber( a, delimiter, b ) {
if( typeof b === 'number' && !isNaN( b ) ) {
return '<span class="slide-number-a">'+ a +'</span>' +
'<span class="slide-number-delimiter">'+ delimiter +'</span>' +
'<span class="slide-number-b">'+ b +'</span>';
}
else {
return '<span class="slide-number-a">'+ a +'</span>';
}
}
/**
* Updates the state of all control/navigation arrows.
*/
function updateControls() {
var routes = availableRoutes();
var fragments = availableFragments();
// Remove the 'enabled' class from all directions
dom.controlsLeft.concat( dom.controlsRight )
.concat( dom.controlsUp )
.concat( dom.controlsDown )
.concat( dom.controlsPrev )
.concat( dom.controlsNext ).forEach( function( node ) {
node.classList.remove( 'enabled' );
node.classList.remove( 'fragmented' );
// Set 'disabled' attribute on all directions
node.setAttribute( 'disabled', 'disabled' );
} );
// Add the 'enabled' class to the available routes; remove 'disabled' attribute to enable buttons
if( routes.left ) dom.controlsLeft.forEach( function( el ) { el.classList.add( 'enabled' ); el.removeAttribute( 'disabled' ); } );
if( routes.right ) dom.controlsRight.forEach( function( el ) { el.classList.add( 'enabled' ); el.removeAttribute( 'disabled' ); } );
if( routes.up ) dom.controlsUp.forEach( function( el ) { el.classList.add( 'enabled' ); el.removeAttribute( 'disabled' ); } );
if( routes.down ) dom.controlsDown.forEach( function( el ) { el.classList.add( 'enabled' ); el.removeAttribute( 'disabled' ); } );
// Prev/next buttons
if( routes.left || routes.up ) dom.controlsPrev.forEach( function( el ) { el.classList.add( 'enabled' ); el.removeAttribute( 'disabled' ); } );
if( routes.right || routes.down ) dom.controlsNext.forEach( function( el ) { el.classList.add( 'enabled' ); el.removeAttribute( 'disabled' ); } );
// Highlight fragment directions
if( currentSlide ) {
// Always apply fragment decorator to prev/next buttons
if( fragments.prev ) dom.controlsPrev.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); el.removeAttribute( 'disabled' ); } );
if( fragments.next ) dom.controlsNext.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); el.removeAttribute( 'disabled' ); } );
// Apply fragment decorators to directional buttons based on
// what slide axis they are in
if( isVerticalSlide( currentSlide ) ) {
if( fragments.prev ) dom.controlsUp.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); el.removeAttribute( 'disabled' ); } );
if( fragments.next ) dom.controlsDown.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); el.removeAttribute( 'disabled' ); } );
}
else {
if( fragments.prev ) dom.controlsLeft.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); el.removeAttribute( 'disabled' ); } );
if( fragments.next ) dom.controlsRight.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); el.removeAttribute( 'disabled' ); } );
}
}
if( config.controlsTutorial ) {
// Highlight control arrows with an animation to ensure
// that the viewer knows how to navigate
if( !hasNavigatedDown && routes.down ) {
dom.controlsDownArrow.classList.add( 'highlight' );
}
else {
dom.controlsDownArrow.classList.remove( 'highlight' );
if( !hasNavigatedRight && routes.right && indexv === 0 ) {
dom.controlsRightArrow.classList.add( 'highlight' );
}
else {
dom.controlsRightArrow.classList.remove( 'highlight' );
}
}
}
}
/**
* Updates the background elements to reflect the current
* slide.
*
* @param {boolean} includeAll If true, the backgrounds of
* all vertical slides (not just the present) will be updated.
*/
function updateBackground( includeAll ) {
var currentBackground = null;
// Reverse past/future classes when in RTL mode
var horizontalPast = config.rtl ? 'future' : 'past',
horizontalFuture = config.rtl ? 'past' : 'future';
// Update the classes of all backgrounds to match the
// states of their slides (past/present/future)
toArray( dom.background.childNodes ).forEach( function( backgroundh, h ) {
backgroundh.classList.remove( 'past' );
backgroundh.classList.remove( 'present' );
backgroundh.classList.remove( 'future' );
if( h < indexh ) {
backgroundh.classList.add( horizontalPast );
}
else if ( h > indexh ) {
backgroundh.classList.add( horizontalFuture );
}
else {
backgroundh.classList.add( 'present' );
// Store a reference to the current background element
currentBackground = backgroundh;
}
if( includeAll || h === indexh ) {
toArray( backgroundh.querySelectorAll( '.slide-background' ) ).forEach( function( backgroundv, v ) {
backgroundv.classList.remove( 'past' );
backgroundv.classList.remove( 'present' );
backgroundv.classList.remove( 'future' );
if( v < indexv ) {
backgroundv.classList.add( 'past' );
}
else if ( v > indexv ) {
backgroundv.classList.add( 'future' );
}
else {
backgroundv.classList.add( 'present' );
// Only if this is the present horizontal and vertical slide
if( h === indexh ) currentBackground = backgroundv;
}
} );
}
} );
// Stop content inside of previous backgrounds
if( previousBackground ) {
stopEmbeddedContent( previousBackground );
}
// Start content in the current background
if( currentBackground ) {
startEmbeddedContent( currentBackground );
var backgroundImageURL = currentBackground.style.backgroundImage || '';
// Restart GIFs (doesn't work in Firefox)
if( /\.gif/i.test( backgroundImageURL ) ) {
currentBackground.style.backgroundImage = '';
window.getComputedStyle( currentBackground ).opacity;
currentBackground.style.backgroundImage = backgroundImageURL;
}
// Don't transition between identical backgrounds. This
// prevents unwanted flicker.
var previousBackgroundHash = previousBackground ? previousBackground.getAttribute( 'data-background-hash' ) : null;
var currentBackgroundHash = currentBackground.getAttribute( 'data-background-hash' );
if( currentBackgroundHash && currentBackgroundHash === previousBackgroundHash && currentBackground !== previousBackground ) {
dom.background.classList.add( 'no-transition' );
}
previousBackground = currentBackground;
}
// If there's a background brightness flag for this slide,
// bubble it to the .reveal container
if( currentSlide ) {
[ 'has-light-background', 'has-dark-background' ].forEach( function( classToBubble ) {
if( currentSlide.classList.contains( classToBubble ) ) {
dom.wrapper.classList.add( classToBubble );
}
else {
dom.wrapper.classList.remove( classToBubble );
}
} );
}
// Allow the first background to apply without transition
setTimeout( function() {
dom.background.classList.remove( 'no-transition' );
}, 1 );
}
/**
* Updates the position of the parallax background based
* on the current slide index.
*/
function updateParallax() {
if( config.parallaxBackgroundImage ) {
var horizontalSlides = dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ),
verticalSlides = dom.wrapper.querySelectorAll( VERTICAL_SLIDES_SELECTOR );
var backgroundSize = dom.background.style.backgroundSize.split( ' ' ),
backgroundWidth, backgroundHeight;
if( backgroundSize.length === 1 ) {
backgroundWidth = backgroundHeight = parseInt( backgroundSize[0], 10 );
}
else {
backgroundWidth = parseInt( backgroundSize[0], 10 );
backgroundHeight = parseInt( backgroundSize[1], 10 );
}
var slideWidth = dom.background.offsetWidth,
horizontalSlideCount = horizontalSlides.length,
horizontalOffsetMultiplier,
horizontalOffset;
if( typeof config.parallaxBackgroundHorizontal === 'number' ) {
horizontalOffsetMultiplier = config.parallaxBackgroundHorizontal;
}
else {
horizontalOffsetMultiplier = horizontalSlideCount > 1 ? ( backgroundWidth - slideWidth ) / ( horizontalSlideCount-1 ) : 0;
}
horizontalOffset = horizontalOffsetMultiplier * indexh * -1;
var slideHeight = dom.background.offsetHeight,
verticalSlideCount = verticalSlides.length,
verticalOffsetMultiplier,
verticalOffset;
if( typeof config.parallaxBackgroundVertical === 'number' ) {
verticalOffsetMultiplier = config.parallaxBackgroundVertical;
}
else {
verticalOffsetMultiplier = ( backgroundHeight - slideHeight ) / ( verticalSlideCount-1 );
}
verticalOffset = verticalSlideCount > 0 ? verticalOffsetMultiplier * indexv : 0;
dom.background.style.backgroundPosition = horizontalOffset + 'px ' + -verticalOffset + 'px';
}
}
/**
* Called when the given slide is within the configured view
* distance. Shows the slide element and loads any content
* that is set to load lazily (data-src).
*
* @param {HTMLElement} slide Slide to show
*/
/**
* Called when the given slide is within the configured view
* distance. Shows the slide element and loads any content
* that is set to load lazily (data-src).
*
* @param {HTMLElement} slide Slide to show
*/
function showSlide( slide ) {
// Show the slide element
slide.style.display = config.display;
// Media elements with data-src attributes
toArray( slide.querySelectorAll( 'img[data-src], video[data-src], audio[data-src]' ) ).forEach( function( element ) {
element.setAttribute( 'src', element.getAttribute( 'data-src' ) );
element.removeAttribute( 'data-src' );
} );
// Media elements with <source> children
toArray( slide.querySelectorAll( 'video, audio' ) ).forEach( function( media ) {
var sources = 0;
toArray( media.querySelectorAll( 'source[data-src]' ) ).forEach( function( source ) {
source.setAttribute( 'src', source.getAttribute( 'data-src' ) );
source.removeAttribute( 'data-src' );
sources += 1;
} );
// If we rewrote sources for this video/audio element, we need
// to manually tell it to load from its new origin
if( sources > 0 ) {
media.load();
}
} );
// Show the corresponding background element
var indices = getIndices( slide );
var background = getSlideBackground( indices.h, indices.v );
if( background ) {
background.style.display = 'block';
// If the background contains media, load it
if( background.hasAttribute( 'data-loaded' ) === false ) {
background.setAttribute( 'data-loaded', 'true' );
var backgroundImage = slide.getAttribute( 'data-background-image' ),
backgroundVideo = slide.getAttribute( 'data-background-video' ),
backgroundVideoLoop = slide.hasAttribute( 'data-background-video-loop' ),
backgroundVideoMuted = slide.hasAttribute( 'data-background-video-muted' ),
backgroundIframe = slide.getAttribute( 'data-background-iframe' );
// Images
if( backgroundImage ) {
background.style.backgroundImage = 'url('+ backgroundImage +')';
}
// Videos
else if ( backgroundVideo && !isSpeakerNotes() ) {
var video = document.createElement( 'video' );
if( backgroundVideoLoop ) {
video.setAttribute( 'loop', '' );
}
if( backgroundVideoMuted ) {
video.muted = true;
}
// Inline video playback works (at least in Mobile Safari) as
// long as the video is muted and the `playsinline` attribute is
// present
if( isMobileDevice ) {
video.muted = true;
video.autoplay = true;
video.setAttribute( 'playsinline', '' );
}
// Support comma separated lists of video sources
backgroundVideo.split( ',' ).forEach( function( source ) {
video.innerHTML += '<source src="'+ source +'">';
} );
background.appendChild( video );
}
// Iframes
else if( backgroundIframe ) {
var iframe = document.createElement( 'iframe' );
iframe.setAttribute( 'allowfullscreen', '' );
iframe.setAttribute( 'mozallowfullscreen', '' );
iframe.setAttribute( 'webkitallowfullscreen', '' );
// Only load autoplaying content when the slide is shown to
// avoid having it play in the background
if( /autoplay=(1|true|yes)/gi.test( backgroundIframe ) ) {
iframe.setAttribute( 'data-src', backgroundIframe );
}
else {
iframe.setAttribute( 'src', backgroundIframe );
}
iframe.style.width = '100%';
iframe.style.height = '100%';
iframe.style.maxHeight = '100%';
iframe.style.maxWidth = '100%';
background.appendChild( iframe );
}
}
}
}
/**
* Called when the given slide is moved outside of the
* configured view distance.
*
* @param {HTMLElement} slide
*/
function hideSlide( slide ) {
// Hide the slide element
slide.style.display = 'none';
// Hide the corresponding background element
var indices = getIndices( slide );
var background = getSlideBackground( indices.h, indices.v );
if( background ) {
background.style.display = 'none';
}
}
/**
* Determine what available routes there are for navigation.
*
* @return {{left: boolean, right: boolean, up: boolean, down: boolean}}
*/
function availableRoutes() {
var horizontalSlides = dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ),
verticalSlides = dom.wrapper.querySelectorAll( VERTICAL_SLIDES_SELECTOR );
var routes = {
left: indexh > 0 || config.loop,
right: indexh < horizontalSlides.length - 1 || config.loop,
up: indexv > 0,
down: indexv < verticalSlides.length - 1
};
// reverse horizontal controls for rtl
if( config.rtl ) {
var left = routes.left;
routes.left = routes.right;
routes.right = left;
}
return routes;
}
/**
* Returns an object describing the available fragment
* directions.
*
* @return {{prev: boolean, next: boolean}}
*/
function availableFragments() {
if( currentSlide && config.fragments ) {
var fragments = currentSlide.querySelectorAll( '.fragment' );
var hiddenFragments = currentSlide.querySelectorAll( '.fragment:not(.visible)' );
return {
prev: fragments.length - hiddenFragments.length > 0,
next: !!hiddenFragments.length
};
}
else {
return { prev: false, next: false };
}
}
/**
* Enforces origin-specific format rules for embedded media.
*/
function formatEmbeddedContent() {
var _appendParamToIframeSource = function( sourceAttribute, sourceURL, param ) {
toArray( dom.slides.querySelectorAll( 'iframe['+ sourceAttribute +'*="'+ sourceURL +'"]' ) ).forEach( function( el ) {
var src = el.getAttribute( sourceAttribute );
if( src && src.indexOf( param ) === -1 ) {
el.setAttribute( sourceAttribute, src + ( !/\?/.test( src ) ? '?' : '&' ) + param );
}
});
};
// YouTube frames must include "?enablejsapi=1"
_appendParamToIframeSource( 'src', 'youtube.com/embed/', 'enablejsapi=1' );
_appendParamToIframeSource( 'data-src', 'youtube.com/embed/', 'enablejsapi=1' );
// Vimeo frames must include "?api=1"
_appendParamToIframeSource( 'src', 'player.vimeo.com/', 'api=1' );
_appendParamToIframeSource( 'data-src', 'player.vimeo.com/', 'api=1' );
}
/**
* Start playback of any embedded content inside of
* the given element.
*
* @param {HTMLElement} element
*/
function startEmbeddedContent( element ) {
if( element && !isSpeakerNotes() ) {
// Restart GIFs
toArray( element.querySelectorAll( 'img[src$=".gif"]' ) ).forEach( function( el ) {
// Setting the same unchanged source like this was confirmed
// to work in Chrome, FF & Safari
el.setAttribute( 'src', el.getAttribute( 'src' ) );
} );
// HTML5 media elements
toArray( element.querySelectorAll( 'video, audio' ) ).forEach( function( el ) {
if( closestParent( el, '.fragment' ) && !closestParent( el, '.fragment.visible' ) ) {
return;
}
// Prefer an explicit global autoplay setting
var autoplay = config.autoPlayMedia;
// If no global setting is available, fall back on the element's
// own autoplay setting
if( typeof autoplay !== 'boolean' ) {
autoplay = el.hasAttribute( 'data-autoplay' ) || !!closestParent( el, '.slide-background' );
}
if( autoplay && typeof el.play === 'function' ) {
if( el.readyState > 1 ) {
startEmbeddedMedia( { target: el } );
}
else {
el.removeEventListener( 'loadeddata', startEmbeddedMedia ); // remove first to avoid dupes
el.addEventListener( 'loadeddata', startEmbeddedMedia );
}
}
} );
// Normal iframes
toArray( element.querySelectorAll( 'iframe[src]' ) ).forEach( function( el ) {
if( closestParent( el, '.fragment' ) && !closestParent( el, '.fragment.visible' ) ) {
return;
}
startEmbeddedIframe( { target: el } );
} );
// Lazy loading iframes
toArray( element.querySelectorAll( 'iframe[data-src]' ) ).forEach( function( el ) {
if( closestParent( el, '.fragment' ) && !closestParent( el, '.fragment.visible' ) ) {
return;
}
if( el.getAttribute( 'src' ) !== el.getAttribute( 'data-src' ) ) {
el.removeEventListener( 'load', startEmbeddedIframe ); // remove first to avoid dupes
el.addEventListener( 'load', startEmbeddedIframe );
el.setAttribute( 'src', el.getAttribute( 'data-src' ) );
}
} );
}
}
/**
* Starts playing an embedded video/audio element after
* it has finished loading.
*
* @param {object} event
*/
function startEmbeddedMedia( event ) {
var isAttachedToDOM = !!closestParent( event.target, 'html' ),
isVisible = !!closestParent( event.target, '.present' );
if( isAttachedToDOM && isVisible ) {
event.target.currentTime = 0;
event.target.play();
}
event.target.removeEventListener( 'loadeddata', startEmbeddedMedia );
}
/**
* "Starts" the content of an embedded iframe using the
* postMessage API.
*
* @param {object} event
*/
function startEmbeddedIframe( event ) {
var iframe = event.target;
if( iframe && iframe.contentWindow ) {
var isAttachedToDOM = !!closestParent( event.target, 'html' ),
isVisible = !!closestParent( event.target, '.present' );
if( isAttachedToDOM && isVisible ) {
// Prefer an explicit global autoplay setting
var autoplay = config.autoPlayMedia;
// If no global setting is available, fall back on the element's
// own autoplay setting
if( typeof autoplay !== 'boolean' ) {
autoplay = iframe.hasAttribute( 'data-autoplay' ) || !!closestParent( iframe, '.slide-background' );
}
// YouTube postMessage API
if( /youtube\.com\/embed\//.test( iframe.getAttribute( 'src' ) ) && autoplay ) {
iframe.contentWindow.postMessage( '{"event":"command","func":"playVideo","args":""}', '*' );
}
// Vimeo postMessage API
else if( /player\.vimeo\.com\//.test( iframe.getAttribute( 'src' ) ) && autoplay ) {
iframe.contentWindow.postMessage( '{"method":"play"}', '*' );
}
// Generic postMessage API
else {
iframe.contentWindow.postMessage( 'slide:start', '*' );
}
}
}
}
/**
* Stop playback of any embedded content inside of
* the targeted slide.
*
* @param {HTMLElement} element
*/
function stopEmbeddedContent( element ) {
if( element && element.parentNode ) {
// HTML5 media elements
toArray( element.querySelectorAll( 'video, audio' ) ).forEach( function( el ) {
if( !el.hasAttribute( 'data-ignore' ) && typeof el.pause === 'function' ) {
el.setAttribute('data-paused-by-reveal', '');
el.pause();
}
} );
// Generic postMessage API for non-lazy loaded iframes
toArray( element.querySelectorAll( 'iframe' ) ).forEach( function( el ) {
if( el.contentWindow ) el.contentWindow.postMessage( 'slide:stop', '*' );
el.removeEventListener( 'load', startEmbeddedIframe );
});
// YouTube postMessage API
toArray( element.querySelectorAll( 'iframe[src*="youtube.com/embed/"]' ) ).forEach( function( el ) {
if( !el.hasAttribute( 'data-ignore' ) && el.contentWindow && typeof el.contentWindow.postMessage === 'function' ) {
el.contentWindow.postMessage( '{"event":"command","func":"pauseVideo","args":""}', '*' );
}
});
// Vimeo postMessage API
toArray( element.querySelectorAll( 'iframe[src*="player.vimeo.com/"]' ) ).forEach( function( el ) {
if( !el.hasAttribute( 'data-ignore' ) && el.contentWindow && typeof el.contentWindow.postMessage === 'function' ) {
el.contentWindow.postMessage( '{"method":"pause"}', '*' );
}
});
// Lazy loading iframes
toArray( element.querySelectorAll( 'iframe[data-src]' ) ).forEach( function( el ) {
// Only removing the src doesn't actually unload the frame
// in all browsers (Firefox) so we set it to blank first
el.setAttribute( 'src', 'about:blank' );
el.removeAttribute( 'src' );
} );
}
}
/**
* Returns the number of past slides. This can be used as a global
* flattened index for slides.
*
* @return {number} Past slide count
*/
function getSlidePastCount() {
var horizontalSlides = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) );
// The number of past slides
var pastCount = 0;
// Step through all slides and count the past ones
mainLoop: for( var i = 0; i < horizontalSlides.length; i++ ) {
var horizontalSlide = horizontalSlides[i];
var verticalSlides = toArray( horizontalSlide.querySelectorAll( 'section' ) );
for( var j = 0; j < verticalSlides.length; j++ ) {
// Stop as soon as we arrive at the present
if( verticalSlides[j].classList.contains( 'present' ) ) {
break mainLoop;
}
pastCount++;
}
// Stop as soon as we arrive at the present
if( horizontalSlide.classList.contains( 'present' ) ) {
break;
}
// Don't count the wrapping section for vertical slides
if( horizontalSlide.classList.contains( 'stack' ) === false ) {
pastCount++;
}
}
return pastCount;
}
/**
* Returns a value ranging from 0-1 that represents
* how far into the presentation we have navigated.
*
* @return {number}
*/
function getProgress() {
// The number of past and total slides
var totalCount = getTotalSlides();
var pastCount = getSlidePastCount();
if( currentSlide ) {
var allFragments = currentSlide.querySelectorAll( '.fragment' );
// If there are fragments in the current slide those should be
// accounted for in the progress.
if( allFragments.length > 0 ) {
var visibleFragments = currentSlide.querySelectorAll( '.fragment.visible' );
// This value represents how big a portion of the slide progress
// that is made up by its fragments (0-1)
var fragmentWeight = 0.9;
// Add fragment progress to the past slide count
pastCount += ( visibleFragments.length / allFragments.length ) * fragmentWeight;
}
}
return pastCount / ( totalCount - 1 );
}
/**
* Checks if this presentation is running inside of the
* speaker notes window.
*
* @return {boolean}
*/
function isSpeakerNotes() {
return !!window.location.search.match( /receiver/gi );
}
/**
* Reads the current URL (hash) and navigates accordingly.
*/
function readURL() {
var hash = window.location.hash;
// Attempt to parse the hash as either an index or name
var bits = hash.slice( 2 ).split( '/' ),
name = hash.replace( /#|\//gi, '' );
// If the first bit is invalid and there is a name we can
// assume that this is a named link
if( isNaN( parseInt( bits[0], 10 ) ) && name.length ) {
var element;
// Ensure the named link is a valid HTML ID attribute
if( /^[a-zA-Z][\w:.-]*$/.test( name ) ) {
// Find the slide with the specified ID
element = document.getElementById( name );
}
if( element ) {
// Find the position of the named slide and navigate to it
var indices = Reveal.getIndices( element );
slide( indices.h, indices.v );
}
// If the slide doesn't exist, navigate to the current slide
else {
slide( indexh || 0, indexv || 0 );
}
}
else {
// Read the index components of the hash
var h = parseInt( bits[0], 10 ) || 0,
v = parseInt( bits[1], 10 ) || 0;
if( h !== indexh || v !== indexv ) {
slide( h, v );
}
}
}
/**
* Updates the page URL (hash) to reflect the current
* state.
*
* @param {number} delay The time in ms to wait before
* writing the hash
*/
function writeURL( delay ) {
if( config.history ) {
// Make sure there's never more than one timeout running
clearTimeout( writeURLTimeout );
// If a delay is specified, timeout this call
if( typeof delay === 'number' ) {
writeURLTimeout = setTimeout( writeURL, delay );
}
else if( currentSlide ) {
var url = '/';
// Attempt to create a named link based on the slide's ID
var id = currentSlide.getAttribute( 'id' );
if( id ) {
id = id.replace( /[^a-zA-Z0-9\-\_\:\.]/g, '' );
}
// If the current slide has an ID, use that as a named link
if( typeof id === 'string' && id.length ) {
url = '/' + id;
}
// Otherwise use the /h/v index
else {
if( indexh > 0 || indexv > 0 ) url += indexh;
if( indexv > 0 ) url += '/' + indexv;
}
window.location.hash = url;
}
}
}
/**
* Retrieves the h/v location and fragment of the current,
* or specified, slide.
*
* @param {HTMLElement} [slide] If specified, the returned
* index will be for this slide rather than the currently
* active one
*
* @return {{h: number, v: number, f: number}}
*/
function getIndices( slide ) {
// By default, return the current indices
var h = indexh,
v = indexv,
f;
// If a slide is specified, return the indices of that slide
if( slide ) {
var isVertical = isVerticalSlide( slide );
var slideh = isVertical ? slide.parentNode : slide;
// Select all horizontal slides
var horizontalSlides = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) );
// Now that we know which the horizontal slide is, get its index
h = Math.max( horizontalSlides.indexOf( slideh ), 0 );
// Assume we're not vertical
v = undefined;
// If this is a vertical slide, grab the vertical index
if( isVertical ) {
v = Math.max( toArray( slide.parentNode.querySelectorAll( 'section' ) ).indexOf( slide ), 0 );
}
}
if( !slide && currentSlide ) {
var hasFragments = currentSlide.querySelectorAll( '.fragment' ).length > 0;
if( hasFragments ) {
var currentFragment = currentSlide.querySelector( '.current-fragment' );
if( currentFragment && currentFragment.hasAttribute( 'data-fragment-index' ) ) {
f = parseInt( currentFragment.getAttribute( 'data-fragment-index' ), 10 );
}
else {
f = currentSlide.querySelectorAll( '.fragment.visible' ).length - 1;
}
}
}
return { h: h, v: v, f: f };
}
/**
* Retrieves all slides in this presentation.
*/
function getSlides() {
return toArray( dom.wrapper.querySelectorAll( SLIDES_SELECTOR + ':not(.stack)' ));
}
/**
* Retrieves the total number of slides in this presentation.
*
* @return {number}
*/
function getTotalSlides() {
return getSlides().length;
}
/**
* Returns the slide element matching the specified index.
*
* @return {HTMLElement}
*/
function getSlide( x, y ) {
var horizontalSlide = dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR )[ x ];
var verticalSlides = horizontalSlide && horizontalSlide.querySelectorAll( 'section' );
if( verticalSlides && verticalSlides.length && typeof y === 'number' ) {
return verticalSlides ? verticalSlides[ y ] : undefined;
}
return horizontalSlide;
}
/**
* Returns the background element for the given slide.
* All slides, even the ones with no background properties
* defined, have a background element so as long as the
* index is valid an element will be returned.
*
* @param {number} x Horizontal background index
* @param {number} y Vertical background index
* @return {(HTMLElement[]|*)}
*/
function getSlideBackground( x, y ) {
// When printing to PDF the slide backgrounds are nested
// inside of the slides
if( isPrintingPDF() ) {
var slide = getSlide( x, y );
if( slide ) {
return slide.slideBackgroundElement;
}
return undefined;
}
var horizontalBackground = dom.wrapper.querySelectorAll( '.backgrounds>.slide-background' )[ x ];
var verticalBackgrounds = horizontalBackground && horizontalBackground.querySelectorAll( '.slide-background' );
if( verticalBackgrounds && verticalBackgrounds.length && typeof y === 'number' ) {
return verticalBackgrounds ? verticalBackgrounds[ y ] : undefined;
}
return horizontalBackground;
}
/**
* Retrieves the speaker notes from a slide. Notes can be
* defined in two ways:
* 1. As a data-notes attribute on the slide <section>
* 2. As an <aside class="notes"> inside of the slide
*
* @param {HTMLElement} [slide=currentSlide]
* @return {(string|null)}
*/
function getSlideNotes( slide ) {
// Default to the current slide
slide = slide || currentSlide;
// Notes can be specified via the data-notes attribute...
if( slide.hasAttribute( 'data-notes' ) ) {
return slide.getAttribute( 'data-notes' );
}
// ... or using an <aside class="notes"> element
var notesElement = slide.querySelector( 'aside.notes' );
if( notesElement ) {
return notesElement.innerHTML;
}
return null;
}
/**
* Retrieves the current state of the presentation as
* an object. This state can then be restored at any
* time.
*
* @return {{indexh: number, indexv: number, indexf: number, paused: boolean, overview: boolean}}
*/
function getState() {
var indices = getIndices();
return {
indexh: indices.h,
indexv: indices.v,
indexf: indices.f,
paused: isPaused(),
overview: isOverview()
};
}
/**
* Restores the presentation to the given state.
*
* @param {object} state As generated by getState()
* @see {@link getState} generates the parameter `state`
*/
function setState( state ) {
if( typeof state === 'object' ) {
slide( deserialize( state.indexh ), deserialize( state.indexv ), deserialize( state.indexf ) );
var pausedFlag = deserialize( state.paused ),
overviewFlag = deserialize( state.overview );
if( typeof pausedFlag === 'boolean' && pausedFlag !== isPaused() ) {
togglePause( pausedFlag );
}
if( typeof overviewFlag === 'boolean' && overviewFlag !== isOverview() ) {
toggleOverview( overviewFlag );
}
}
}
/**
* Return a sorted fragments list, ordered by an increasing
* "data-fragment-index" attribute.
*
* Fragments will be revealed in the order that they are returned by
* this function, so you can use the index attributes to control the
* order of fragment appearance.
*
* To maintain a sensible default fragment order, fragments are presumed
* to be passed in document order. This function adds a "fragment-index"
* attribute to each node if such an attribute is not already present,
* and sets that attribute to an integer value which is the position of
* the fragment within the fragments list.
*
* @param {object[]|*} fragments
* @return {object[]} sorted Sorted array of fragments
*/
function sortFragments( fragments ) {
fragments = toArray( fragments );
var ordered = [],
unordered = [],
sorted = [];
// Group ordered and unordered elements
fragments.forEach( function( fragment, i ) {
if( fragment.hasAttribute( 'data-fragment-index' ) ) {
var index = parseInt( fragment.getAttribute( 'data-fragment-index' ), 10 );
if( !ordered[index] ) {
ordered[index] = [];
}
ordered[index].push( fragment );
}
else {
unordered.push( [ fragment ] );
}
} );
// Append fragments without explicit indices in their
// DOM order
ordered = ordered.concat( unordered );
// Manually count the index up per group to ensure there
// are no gaps
var index = 0;
// Push all fragments in their sorted order to an array,
// this flattens the groups
ordered.forEach( function( group ) {
group.forEach( function( fragment ) {
sorted.push( fragment );
fragment.setAttribute( 'data-fragment-index', index );
} );
index ++;
} );
return sorted;
}
/**
* Navigate to the specified slide fragment.
*
* @param {?number} index The index of the fragment that
* should be shown, -1 means all are invisible
* @param {number} offset Integer offset to apply to the
* fragment index
*
* @return {boolean} true if a change was made in any
* fragments visibility as part of this call
*/
function navigateFragment( index, offset ) {
if( currentSlide && config.fragments ) {
var fragments = sortFragments( currentSlide.querySelectorAll( '.fragment' ) );
if( fragments.length ) {
// If no index is specified, find the current
if( typeof index !== 'number' ) {
var lastVisibleFragment = sortFragments( currentSlide.querySelectorAll( '.fragment.visible' ) ).pop();
if( lastVisibleFragment ) {
index = parseInt( lastVisibleFragment.getAttribute( 'data-fragment-index' ) || 0, 10 );
}
else {
index = -1;
}
}
// If an offset is specified, apply it to the index
if( typeof offset === 'number' ) {
index += offset;
}
var fragmentsShown = [],
fragmentsHidden = [];
toArray( fragments ).forEach( function( element, i ) {
if( element.hasAttribute( 'data-fragment-index' ) ) {
i = parseInt( element.getAttribute( 'data-fragment-index' ), 10 );
}
// Visible fragments
if( i <= index ) {
if( !element.classList.contains( 'visible' ) ) fragmentsShown.push( element );
element.classList.add( 'visible' );
element.classList.remove( 'current-fragment' );
// Announce the fragments one by one to the Screen Reader
dom.statusDiv.textContent = getStatusText( element );
if( i === index ) {
element.classList.add( 'current-fragment' );
startEmbeddedContent( element );
}
}
// Hidden fragments
else {
if( element.classList.contains( 'visible' ) ) fragmentsHidden.push( element );
element.classList.remove( 'visible' );
element.classList.remove( 'current-fragment' );
}
} );
if( fragmentsHidden.length ) {
dispatchEvent( 'fragmenthidden', { fragment: fragmentsHidden[0], fragments: fragmentsHidden } );
}
if( fragmentsShown.length ) {
dispatchEvent( 'fragmentshown', { fragment: fragmentsShown[0], fragments: fragmentsShown } );
}
updateControls();
updateProgress();
return !!( fragmentsShown.length || fragmentsHidden.length );
}
}
return false;
}
/**
* Navigate to the next slide fragment.
*
* @return {boolean} true if there was a next fragment,
* false otherwise
*/
function nextFragment() {
return navigateFragment( null, 1 );
}
/**
* Navigate to the previous slide fragment.
*
* @return {boolean} true if there was a previous fragment,
* false otherwise
*/
function previousFragment() {
return navigateFragment( null, -1 );
}
/**
* Cues a new automated slide if enabled in the config.
*/
function cueAutoSlide() {
cancelAutoSlide();
if( currentSlide ) {
var fragment = currentSlide.querySelector( '.current-fragment' );
// When the slide first appears there is no "current" fragment so
// we look for a data-autoslide timing on the first fragment
if( !fragment ) fragment = currentSlide.querySelector( '.fragment' );
var fragmentAutoSlide = fragment ? fragment.getAttribute( 'data-autoslide' ) : null;
var parentAutoSlide = currentSlide.parentNode ? currentSlide.parentNode.getAttribute( 'data-autoslide' ) : null;
var slideAutoSlide = currentSlide.getAttribute( 'data-autoslide' );
// Pick value in the following priority order:
// 1. Current fragment's data-autoslide
// 2. Current slide's data-autoslide
// 3. Parent slide's data-autoslide
// 4. Global autoSlide setting
if( fragmentAutoSlide ) {
autoSlide = parseInt( fragmentAutoSlide, 10 );
}
else if( slideAutoSlide ) {
autoSlide = parseInt( slideAutoSlide, 10 );
}
else if( parentAutoSlide ) {
autoSlide = parseInt( parentAutoSlide, 10 );
}
else {
autoSlide = config.autoSlide;
}
// If there are media elements with data-autoplay,
// automatically set the autoSlide duration to the
// length of that media. Not applicable if the slide
// is divided up into fragments.
// playbackRate is accounted for in the duration.
if( currentSlide.querySelectorAll( '.fragment' ).length === 0 ) {
toArray( currentSlide.querySelectorAll( 'video, audio' ) ).forEach( function( el ) {
if( el.hasAttribute( 'data-autoplay' ) ) {
if( autoSlide && (el.duration * 1000 / el.playbackRate ) > autoSlide ) {
autoSlide = ( el.duration * 1000 / el.playbackRate ) + 1000;
}
}
} );
}
// Cue the next auto-slide if:
// - There is an autoSlide value
// - Auto-sliding isn't paused by the user
// - The presentation isn't paused
// - The overview isn't active
// - The presentation isn't over
if( autoSlide && !autoSlidePaused && !isPaused() && !isOverview() && ( !Reveal.isLastSlide() || availableFragments().next || config.loop === true ) ) {
autoSlideTimeout = setTimeout( function() {
typeof config.autoSlideMethod === 'function' ? config.autoSlideMethod() : navigateNext();
cueAutoSlide();
}, autoSlide );
autoSlideStartTime = Date.now();
}
if( autoSlidePlayer ) {
autoSlidePlayer.setPlaying( autoSlideTimeout !== -1 );
}
}
}
/**
* Cancels any ongoing request to auto-slide.
*/
function cancelAutoSlide() {
clearTimeout( autoSlideTimeout );
autoSlideTimeout = -1;
}
function pauseAutoSlide() {
if( autoSlide && !autoSlidePaused ) {
autoSlidePaused = true;
dispatchEvent( 'autoslidepaused' );
clearTimeout( autoSlideTimeout );
if( autoSlidePlayer ) {
autoSlidePlayer.setPlaying( false );
}
}
}
function resumeAutoSlide() {
if( autoSlide && autoSlidePaused ) {
autoSlidePaused = false;
dispatchEvent( 'autoslideresumed' );
cueAutoSlide();
}
}
function navigateLeft() {
// Reverse for RTL
if( config.rtl ) {
if( ( isOverview() || nextFragment() === false ) && availableRoutes().left ) {
slide( indexh + 1 );
}
}
// Normal navigation
else if( ( isOverview() || previousFragment() === false ) && availableRoutes().left ) {
slide( indexh - 1 );
}
}
function navigateRight() {
hasNavigatedRight = true;
// Reverse for RTL
if( config.rtl ) {
if( ( isOverview() || previousFragment() === false ) && availableRoutes().right ) {
slide( indexh - 1 );
}
}
// Normal navigation
else if( ( isOverview() || nextFragment() === false ) && availableRoutes().right ) {
slide( indexh + 1 );
}
}
function navigateUp() {
// Prioritize hiding fragments
if( ( isOverview() || previousFragment() === false ) && availableRoutes().up ) {
slide( indexh, indexv - 1 );
}
}
function navigateDown() {
hasNavigatedDown = true;
// Prioritize revealing fragments
if( ( isOverview() || nextFragment() === false ) && availableRoutes().down ) {
slide( indexh, indexv + 1 );
}
}
/**
* Navigates backwards, prioritized in the following order:
* 1) Previous fragment
* 2) Previous vertical slide
* 3) Previous horizontal slide
*/
function navigatePrev() {
// Prioritize revealing fragments
if( previousFragment() === false ) {
if( availableRoutes().up ) {
navigateUp();
}
else {
// Fetch the previous horizontal slide, if there is one
var previousSlide;
if( config.rtl ) {
previousSlide = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR + '.future' ) ).pop();
}
else {
previousSlide = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR + '.past' ) ).pop();
}
if( previousSlide ) {
var v = ( previousSlide.querySelectorAll( 'section' ).length - 1 ) || undefined;
var h = indexh - 1;
slide( h, v );
}
}
}
}
/**
* The reverse of #navigatePrev().
*/
function navigateNext() {
hasNavigatedRight = true;
hasNavigatedDown = true;
// Prioritize revealing fragments
if( nextFragment() === false ) {
if( availableRoutes().down ) {
navigateDown();
}
else if( config.rtl ) {
navigateLeft();
}
else {
navigateRight();
}
}
}
/**
* Checks if the target element prevents the triggering of
* swipe navigation.
*/
function isSwipePrevented( target ) {
while( target && typeof target.hasAttribute === 'function' ) {
if( target.hasAttribute( 'data-prevent-swipe' ) ) return true;
target = target.parentNode;
}
return false;
}
// --------------------------------------------------------------------//
// ----------------------------- EVENTS -------------------------------//
// --------------------------------------------------------------------//
/**
* Called by all event handlers that are based on user
* input.
*
* @param {object} [event]
*/
function onUserInput( event ) {
if( config.autoSlideStoppable ) {
pauseAutoSlide();
}
}
/**
* Handler for the document level 'keypress' event.
*
* @param {object} event
*/
function onDocumentKeyPress( event ) {
// Check if the pressed key is question mark
if( event.shiftKey && event.charCode === 63 ) {
toggleHelp();
}
}
/**
* Handler for the document level 'keydown' event.
*
* @param {object} event
*/
function onDocumentKeyDown( event ) {
// If there's a condition specified and it returns false,
// ignore this event
if( typeof config.keyboardCondition === 'function' && config.keyboardCondition() === false ) {
return true;
}
// Remember if auto-sliding was paused so we can toggle it
var autoSlideWasPaused = autoSlidePaused;
onUserInput( event );
// Check if there's a focused element that could be using
// the keyboard
var activeElementIsCE = document.activeElement && document.activeElement.contentEditable !== 'inherit';
var activeElementIsInput = document.activeElement && document.activeElement.tagName && /input|textarea/i.test( document.activeElement.tagName );
var activeElementIsNotes = document.activeElement && document.activeElement.className && /speaker-notes/i.test( document.activeElement.className);
// Disregard the event if there's a focused element or a
// keyboard modifier key is present
if( activeElementIsCE || activeElementIsInput || activeElementIsNotes || (event.shiftKey && event.keyCode !== 32) || event.altKey || event.ctrlKey || event.metaKey ) return;
// While paused only allow resume keyboard events; 'b', 'v', '.'
var resumeKeyCodes = [66,86,190,191];
var key;
// Custom key bindings for togglePause should be able to resume
if( typeof config.keyboard === 'object' ) {
for( key in config.keyboard ) {
if( config.keyboard[key] === 'togglePause' ) {
resumeKeyCodes.push( parseInt( key, 10 ) );
}
}
}
if( isPaused() && resumeKeyCodes.indexOf( event.keyCode ) === -1 ) {
return false;
}
var triggered = false;
// 1. User defined key bindings
if( typeof config.keyboard === 'object' ) {
for( key in config.keyboard ) {
// Check if this binding matches the pressed key
if( parseInt( key, 10 ) === event.keyCode ) {
var value = config.keyboard[ key ];
// Callback function
if( typeof value === 'function' ) {
value.apply( null, [ event ] );
}
// String shortcuts to reveal.js API
else if( typeof value === 'string' && typeof Reveal[ value ] === 'function' ) {
Reveal[ value ].call();
}
triggered = true;
}
}
}
// 2. System defined key bindings
if( triggered === false ) {
// Assume true and try to prove false
triggered = true;
switch( event.keyCode ) {
// p, page up
case 80: case 33: navigatePrev(); break;
// n, page down
case 78: case 34: navigateNext(); break;
// h, left
case 72: case 37: navigateLeft(); break;
// l, right
case 76: case 39: navigateRight(); break;
// k, up
case 75: case 38: navigateUp(); break;
// j, down
case 74: case 40: navigateDown(); break;
// home
case 36: slide( 0 ); break;
// end
case 35: slide( Number.MAX_VALUE ); break;
// space
case 32: isOverview() ? deactivateOverview() : event.shiftKey ? navigatePrev() : navigateNext(); break;
// return
case 13: isOverview() ? deactivateOverview() : triggered = false; break;
// two-spot, semicolon, b, v, period, Logitech presenter tools "black screen" button
case 58: case 59: case 66: case 86: case 190: case 191: togglePause(); break;
// f
case 70: enterFullscreen(); break;
// a
case 65: if ( config.autoSlideStoppable ) toggleAutoSlide( autoSlideWasPaused ); break;
default:
triggered = false;
}
}
// If the input resulted in a triggered action we should prevent
// the browsers default behavior
if( triggered ) {
event.preventDefault && event.preventDefault();
}
// ESC or O key
else if ( ( event.keyCode === 27 || event.keyCode === 79 ) && features.transforms3d ) {
if( dom.overlay ) {
closeOverlay();
}
else {
toggleOverview();
}
event.preventDefault && event.preventDefault();
}
// If auto-sliding is enabled we need to cue up
// another timeout
cueAutoSlide();
}
/**
* Handler for the 'touchstart' event, enables support for
* swipe and pinch gestures.
*
* @param {object} event
*/
function onTouchStart( event ) {
if( isSwipePrevented( event.target ) ) return true;
touch.startX = event.touches[0].clientX;
touch.startY = event.touches[0].clientY;
touch.startCount = event.touches.length;
// If there's two touches we need to memorize the distance
// between those two points to detect pinching
if( event.touches.length === 2 && config.overview ) {
touch.startSpan = distanceBetween( {
x: event.touches[1].clientX,
y: event.touches[1].clientY
}, {
x: touch.startX,
y: touch.startY
} );
}
}
/**
* Handler for the 'touchmove' event.
*
* @param {object} event
*/
function onTouchMove( event ) {
if( isSwipePrevented( event.target ) ) return true;
// Each touch should only trigger one action
if( !touch.captured ) {
onUserInput( event );
var currentX = event.touches[0].clientX;
var currentY = event.touches[0].clientY;
// If the touch started with two points and still has
// two active touches; test for the pinch gesture
if( event.touches.length === 2 && touch.startCount === 2 && config.overview ) {
// The current distance in pixels between the two touch points
var currentSpan = distanceBetween( {
x: event.touches[1].clientX,
y: event.touches[1].clientY
}, {
x: touch.startX,
y: touch.startY
} );
// If the span is larger than the desire amount we've got
// ourselves a pinch
if( Math.abs( touch.startSpan - currentSpan ) > touch.threshold ) {
touch.captured = true;
if( currentSpan < touch.startSpan ) {
activateOverview();
}
else {
deactivateOverview();
}
}
event.preventDefault();
}
// There was only one touch point, look for a swipe
else if( event.touches.length === 1 && touch.startCount !== 2 ) {
var deltaX = currentX - touch.startX,
deltaY = currentY - touch.startY;
if( deltaX > touch.threshold && Math.abs( deltaX ) > Math.abs( deltaY ) ) {
touch.captured = true;
navigateLeft();
}
else if( deltaX < -touch.threshold && Math.abs( deltaX ) > Math.abs( deltaY ) ) {
touch.captured = true;
navigateRight();
}
else if( deltaY > touch.threshold ) {
touch.captured = true;
navigateUp();
}
else if( deltaY < -touch.threshold ) {
touch.captured = true;
navigateDown();
}
// If we're embedded, only block touch events if they have
// triggered an action
if( config.embedded ) {
if( touch.captured || isVerticalSlide( currentSlide ) ) {
event.preventDefault();
}
}
// Not embedded? Block them all to avoid needless tossing
// around of the viewport in iOS
else {
event.preventDefault();
}
}
}
// There's a bug with swiping on some Android devices unless
// the default action is always prevented
else if( UA.match( /android/gi ) ) {
event.preventDefault();
}
}
/**
* Handler for the 'touchend' event.
*
* @param {object} event
*/
function onTouchEnd( event ) {
touch.captured = false;
}
/**
* Convert pointer down to touch start.
*
* @param {object} event
*/
function onPointerDown( event ) {
if( event.pointerType === event.MSPOINTER_TYPE_TOUCH || event.pointerType === "touch" ) {
event.touches = [{ clientX: event.clientX, clientY: event.clientY }];
onTouchStart( event );
}
}
/**
* Convert pointer move to touch move.
*
* @param {object} event
*/
function onPointerMove( event ) {
if( event.pointerType === event.MSPOINTER_TYPE_TOUCH || event.pointerType === "touch" ) {
event.touches = [{ clientX: event.clientX, clientY: event.clientY }];
onTouchMove( event );
}
}
/**
* Convert pointer up to touch end.
*
* @param {object} event
*/
function onPointerUp( event ) {
if( event.pointerType === event.MSPOINTER_TYPE_TOUCH || event.pointerType === "touch" ) {
event.touches = [{ clientX: event.clientX, clientY: event.clientY }];
onTouchEnd( event );
}
}
/**
* Handles mouse wheel scrolling, throttled to avoid skipping
* multiple slides.
*
* @param {object} event
*/
function onDocumentMouseScroll( event ) {
if( Date.now() - lastMouseWheelStep > 600 ) {
lastMouseWheelStep = Date.now();
var delta = event.detail || -event.wheelDelta;
if( delta > 0 ) {
navigateNext();
}
else if( delta < 0 ) {
navigatePrev();
}
}
}
/**
* Clicking on the progress bar results in a navigation to the
* closest approximate horizontal slide using this equation:
*
* ( clickX / presentationWidth ) * numberOfSlides
*
* @param {object} event
*/
function onProgressClicked( event ) {
onUserInput( event );
event.preventDefault();
var slidesTotal = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ).length;
var slideIndex = Math.floor( ( event.clientX / dom.wrapper.offsetWidth ) * slidesTotal );
if( config.rtl ) {
slideIndex = slidesTotal - slideIndex;
}
slide( slideIndex );
}
/**
* Event handler for navigation control buttons.
*/
function onNavigateLeftClicked( event ) { event.preventDefault(); onUserInput(); navigateLeft(); }
function onNavigateRightClicked( event ) { event.preventDefault(); onUserInput(); navigateRight(); }
function onNavigateUpClicked( event ) { event.preventDefault(); onUserInput(); navigateUp(); }
function onNavigateDownClicked( event ) { event.preventDefault(); onUserInput(); navigateDown(); }
function onNavigatePrevClicked( event ) { event.preventDefault(); onUserInput(); navigatePrev(); }
function onNavigateNextClicked( event ) { event.preventDefault(); onUserInput(); navigateNext(); }
/**
* Handler for the window level 'hashchange' event.
*
* @param {object} [event]
*/
function onWindowHashChange( event ) {
readURL();
}
/**
* Handler for the window level 'resize' event.
*
* @param {object} [event]
*/
function onWindowResize( event ) {
layout();
}
/**
* Handle for the window level 'visibilitychange' event.
*
* @param {object} [event]
*/
function onPageVisibilityChange( event ) {
var isHidden = document.webkitHidden ||
document.msHidden ||
document.hidden;
// If, after clicking a link or similar and we're coming back,
// focus the document.body to ensure we can use keyboard shortcuts
if( isHidden === false && document.activeElement !== document.body ) {
// Not all elements support .blur() - SVGs among them.
if( typeof document.activeElement.blur === 'function' ) {
document.activeElement.blur();
}
document.body.focus();
}
}
/**
* Invoked when a slide is and we're in the overview.
*
* @param {object} event
*/
function onOverviewSlideClicked( event ) {
// TODO There's a bug here where the event listeners are not
// removed after deactivating the overview.
if( eventsAreBound && isOverview() ) {
event.preventDefault();
var element = event.target;
while( element && !element.nodeName.match( /section/gi ) ) {
element = element.parentNode;
}
if( element && !element.classList.contains( 'disabled' ) ) {
deactivateOverview();
if( element.nodeName.match( /section/gi ) ) {
var h = parseInt( element.getAttribute( 'data-index-h' ), 10 ),
v = parseInt( element.getAttribute( 'data-index-v' ), 10 );
slide( h, v );
}
}
}
}
/**
* Handles clicks on links that are set to preview in the
* iframe overlay.
*
* @param {object} event
*/
function onPreviewLinkClicked( event ) {
if( event.currentTarget && event.currentTarget.hasAttribute( 'href' ) ) {
var url = event.currentTarget.getAttribute( 'href' );
if( url ) {
showPreview( url );
event.preventDefault();
}
}
}
/**
* Handles click on the auto-sliding controls element.
*
* @param {object} [event]
*/
function onAutoSlidePlayerClick( event ) {
// Replay
if( Reveal.isLastSlide() && config.loop === false ) {
slide( 0, 0 );
resumeAutoSlide();
}
// Resume
else if( autoSlidePaused ) {
resumeAutoSlide();
}
// Pause
else {
pauseAutoSlide();
}
}
// --------------------------------------------------------------------//
// ------------------------ PLAYBACK COMPONENT ------------------------//
// --------------------------------------------------------------------//
/**
* Constructor for the playback component, which displays
* play/pause/progress controls.
*
* @param {HTMLElement} container The component will append
* itself to this
* @param {function} progressCheck A method which will be
* called frequently to get the current progress on a range
* of 0-1
*/
function Playback( container, progressCheck ) {
// Cosmetics
this.diameter = 100;
this.diameter2 = this.diameter/2;
this.thickness = 6;
// Flags if we are currently playing
this.playing = false;
// Current progress on a 0-1 range
this.progress = 0;
// Used to loop the animation smoothly
this.progressOffset = 1;
this.container = container;
this.progressCheck = progressCheck;
this.canvas = document.createElement( 'canvas' );
this.canvas.className = 'playback';
this.canvas.width = this.diameter;
this.canvas.height = this.diameter;
this.canvas.style.width = this.diameter2 + 'px';
this.canvas.style.height = this.diameter2 + 'px';
this.context = this.canvas.getContext( '2d' );
this.container.appendChild( this.canvas );
this.render();
}
/**
* @param value
*/
Playback.prototype.setPlaying = function( value ) {
var wasPlaying = this.playing;
this.playing = value;
// Start repainting if we weren't already
if( !wasPlaying && this.playing ) {
this.animate();
}
else {
this.render();
}
};
Playback.prototype.animate = function() {
var progressBefore = this.progress;
this.progress = this.progressCheck();
// When we loop, offset the progress so that it eases
// smoothly rather than immediately resetting
if( progressBefore > 0.8 && this.progress < 0.2 ) {
this.progressOffset = this.progress;
}
this.render();
if( this.playing ) {
features.requestAnimationFrameMethod.call( window, this.animate.bind( this ) );
}
};
/**
* Renders the current progress and playback state.
*/
Playback.prototype.render = function() {
var progress = this.playing ? this.progress : 0,
radius = ( this.diameter2 ) - this.thickness,
x = this.diameter2,
y = this.diameter2,
iconSize = 28;
// Ease towards 1
this.progressOffset += ( 1 - this.progressOffset ) * 0.1;
var endAngle = ( - Math.PI / 2 ) + ( progress * ( Math.PI * 2 ) );
var startAngle = ( - Math.PI / 2 ) + ( this.progressOffset * ( Math.PI * 2 ) );
this.context.save();
this.context.clearRect( 0, 0, this.diameter, this.diameter );
// Solid background color
this.context.beginPath();
this.context.arc( x, y, radius + 4, 0, Math.PI * 2, false );
this.context.fillStyle = 'rgba( 0, 0, 0, 0.4 )';
this.context.fill();
// Draw progress track
this.context.beginPath();
this.context.arc( x, y, radius, 0, Math.PI * 2, false );
this.context.lineWidth = this.thickness;
this.context.strokeStyle = '#666';
this.context.stroke();
if( this.playing ) {
// Draw progress on top of track
this.context.beginPath();
this.context.arc( x, y, radius, startAngle, endAngle, false );
this.context.lineWidth = this.thickness;
this.context.strokeStyle = '#fff';
this.context.stroke();
}
this.context.translate( x - ( iconSize / 2 ), y - ( iconSize / 2 ) );
// Draw play/pause icons
if( this.playing ) {
this.context.fillStyle = '#fff';
this.context.fillRect( 0, 0, iconSize / 2 - 4, iconSize );
this.context.fillRect( iconSize / 2 + 4, 0, iconSize / 2 - 4, iconSize );
}
else {
this.context.beginPath();
this.context.translate( 4, 0 );
this.context.moveTo( 0, 0 );
this.context.lineTo( iconSize - 4, iconSize / 2 );
this.context.lineTo( 0, iconSize );
this.context.fillStyle = '#fff';
this.context.fill();
}
this.context.restore();
};
Playback.prototype.on = function( type, listener ) {
this.canvas.addEventListener( type, listener, false );
};
Playback.prototype.off = function( type, listener ) {
this.canvas.removeEventListener( type, listener, false );
};
Playback.prototype.destroy = function() {
this.playing = false;
if( this.canvas.parentNode ) {
this.container.removeChild( this.canvas );
}
};
// --------------------------------------------------------------------//
// ------------------------------- API --------------------------------//
// --------------------------------------------------------------------//
Reveal = {
VERSION: VERSION,
initialize: initialize,
configure: configure,
sync: sync,
// Navigation methods
slide: slide,
left: navigateLeft,
right: navigateRight,
up: navigateUp,
down: navigateDown,
prev: navigatePrev,
next: navigateNext,
// Fragment methods
navigateFragment: navigateFragment,
prevFragment: previousFragment,
nextFragment: nextFragment,
// Deprecated aliases
navigateTo: slide,
navigateLeft: navigateLeft,
navigateRight: navigateRight,
navigateUp: navigateUp,
navigateDown: navigateDown,
navigatePrev: navigatePrev,
navigateNext: navigateNext,
// Forces an update in slide layout
layout: layout,
// Randomizes the order of slides
shuffle: shuffle,
// Returns an object with the available routes as booleans (left/right/top/bottom)
availableRoutes: availableRoutes,
// Returns an object with the available fragments as booleans (prev/next)
availableFragments: availableFragments,
// Toggles a help overlay with keyboard shortcuts
toggleHelp: toggleHelp,
// Toggles the overview mode on/off
toggleOverview: toggleOverview,
// Toggles the "black screen" mode on/off
togglePause: togglePause,
// Toggles the auto slide mode on/off
toggleAutoSlide: toggleAutoSlide,
// State checks
isOverview: isOverview,
isPaused: isPaused,
isAutoSliding: isAutoSliding,
// Adds or removes all internal event listeners (such as keyboard)
addEventListeners: addEventListeners,
removeEventListeners: removeEventListeners,
// Facility for persisting and restoring the presentation state
getState: getState,
setState: setState,
// Presentation progress
getSlidePastCount: getSlidePastCount,
// Presentation progress on range of 0-1
getProgress: getProgress,
// Returns the indices of the current, or specified, slide
getIndices: getIndices,
// Returns an Array of all slides
getSlides: getSlides,
// Returns the total number of slides
getTotalSlides: getTotalSlides,
// Returns the slide element at the specified index
getSlide: getSlide,
// Returns the slide background element at the specified index
getSlideBackground: getSlideBackground,
// Returns the speaker notes string for a slide, or null
getSlideNotes: getSlideNotes,
// Returns the previous slide element, may be null
getPreviousSlide: function() {
return previousSlide;
},
// Returns the current slide element
getCurrentSlide: function() {
return currentSlide;
},
// Returns the current scale of the presentation content
getScale: function() {
return scale;
},
// Returns the current configuration object
getConfig: function() {
return config;
},
// Helper method, retrieves query string as a key/value hash
getQueryHash: function() {
var query = {};
location.search.replace( /[A-Z0-9]+?=([\w\.%-]*)/gi, function(a) {
query[ a.split( '=' ).shift() ] = a.split( '=' ).pop();
} );
// Basic deserialization
for( var i in query ) {
var value = query[ i ];
query[ i ] = deserialize( unescape( value ) );
}
return query;
},
// Returns true if we're currently on the first slide
isFirstSlide: function() {
return ( indexh === 0 && indexv === 0 );
},
// Returns true if we're currently on the last slide
isLastSlide: function() {
if( currentSlide ) {
// Does this slide has next a sibling?
if( currentSlide.nextElementSibling ) return false;
// If it's vertical, does its parent have a next sibling?
if( isVerticalSlide( currentSlide ) && currentSlide.parentNode.nextElementSibling ) return false;
return true;
}
return false;
},
// Checks if reveal.js has been loaded and is ready for use
isReady: function() {
return loaded;
},
// Forward event binding to the reveal DOM element
addEventListener: function( type, listener, useCapture ) {
if( 'addEventListener' in window ) {
( dom.wrapper || document.querySelector( '.reveal' ) ).addEventListener( type, listener, useCapture );
}
},
removeEventListener: function( type, listener, useCapture ) {
if( 'addEventListener' in window ) {
( dom.wrapper || document.querySelector( '.reveal' ) ).removeEventListener( type, listener, useCapture );
}
},
// Programatically triggers a keyboard event
triggerKey: function( keyCode ) {
onDocumentKeyDown( { keyCode: keyCode } );
},
// Registers a new shortcut to include in the help overlay
registerKeyboardShortcut: function( key, value ) {
keyboardShortcuts[key] = value;
}
};
return Reveal;
}));
| PythonDayMX/taller_testing | docs/reveal/js/reveal.js | JavaScript | apache-2.0 | 145,168 |
import React from 'react';
import { Box, Text } from 'grommet';
import doc from 'grommet/components/Text/doc';
import Doc from '../components/Doc';
const desc = doc(Text).toJSON();
export default () => (
<Doc name='Text' desc={desc}>
<Box pad='large'>
<Text size='xsmall'>Text XSmall</Text>
<Text size='small'>Text Small</Text>
<Text size='medium'>Text Medium</Text>
<Text size='large'>Text Large</Text>
<Text size='xlarge'>Text XLarge</Text>
<Text size='xxlarge'>Text XXLarge</Text>
<Text color='status-critical'>status-critical</Text>
</Box>
</Doc>
);
| grommet/next-sample | src/js/screens/Text.js | JavaScript | apache-2.0 | 612 |
import {ddescribe, describe, it, expect} from 'changular2/test_lib';
import {CONST} from './fixtures/annotations';
class Foo {
a;
b;
constructor(a, b) {
this.a = a;
this.b = b;
}
sum() {
return this.a + this.b;
}
}
class SubFoo extends Foo {
c;
constructor(a, b) {
this.c = 3;
super(a, b);
}
}
@CONST
class ConstClass {}
class Const {
a;
@CONST
constructor(a:number) {
this.a = a;
}
}
class SubConst extends Const {
b;
@CONST
constructor(a:number, b:number) {
super(a);
this.b = b;
}
}
class HasGetters {
get getter():string {
return 'getter';
}
static get staticGetter():string {
return 'getter';
}
}
class WithFields {
name: string;
static id: number;
}
export function main() {
describe('classes', function() {
it('should work', function() {
var foo = new Foo(2, 3);
expect(foo.a).toBe(2);
expect(foo.b).toBe(3);
expect(foo.sum()).toBe(5);
});
it('@CONST should be transpiled to a const constructor', function() {
var subConst = new SubConst(1, 2);
expect(subConst.a).toBe(1);
expect(subConst.b).toBe(2);
});
it('@CONST on class without constructor should generate const constructor', function () {
var constClass = new ConstClass();
expect(constClass).not.toBe(null);
});
describe('inheritance', function() {
it('should support super call', function () {
var subFoo = new SubFoo(1, 2);
expect(subFoo.a).toBe(1);
expect(subFoo.b).toBe(2);
expect(subFoo.c).toBe(3);
});
});
describe("getters", function () {
it("should call instance getters", function () {
var obj = new HasGetters();
expect(obj.getter).toEqual('getter');
});
it("should call static getters", function () {
expect(HasGetters.staticGetter).toEqual('getter');
});
});
describe('fields', function() {
it('should work', function() {
var obj = new WithFields();
obj.name = 'Vojta';
WithFields.id = 12;
});
});
});
}
| jasonjchang/changular | tools/transpiler/spec/classes_spec.js | JavaScript | apache-2.0 | 2,122 |
"use strict";
$.require([
'lib!console/core.js',
'lib!console/color/core.js'
], function(
console,
color
) {
/**
* Build all loggers from config
*/
var list = $.config.get('console.logger'), logOut = {}, addLog = function(name) {
var c = new console(name), f = function() {
c.print(arguments);
return (f);
};
return (f);
};
for (var i in list) {
logOut[i] = addLog(i);
}
/**
* Build all color function
* @type {string[]}
*/
var colorRef = ['black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white', 'none'], colorOut = {}, addColor = function(col) {
return (function() {
var c = new color();
return (c._add(col, arguments));
});
};
for (var i in colorRef) {
colorOut[colorRef[i]] = addColor(colorRef[i]);
}
module.exports = {
log: logOut,
color: colorOut
};
}); | Product-Live/Singularity | engine/core/lib/console.js | JavaScript | apache-2.0 | 920 |
eventsApp.factory('eventData', function($resource) {
var resource = $resource('/data/event/:id', {id:'@id'})
return {
getEvent: function(eventId) {
return resource.get({id:eventId});
},
save: function(event) {
event.id = 999;
return resource.save(event);
},
getAllEvents: function() {
return resource.query();
}
};
}); | Straightly/DemoApp | app/js/services/EventData.js | JavaScript | apache-2.0 | 349 |
/*!
* SAP UI development toolkit for HTML5 (SAPUI5/OpenUI5)
* (c) Copyright 2009-2014 SAP AG or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
sap.ui.define(['jquery.sap.global', './Core'],
function(jQuery, Core) {
"use strict";
// keys for configuration sections
var CONFIG_VIEW_REPLACEMENTS = "sap.ui.viewReplacements",
CONFIG_VIEW_EXTENSIONS = "sap.ui.viewExtensions",
CONFIG_VIEW_MODIFICATIONS = "sap.ui.viewModifications",
CONFIG_CONTROLLER_EXTENSIONS = "sap.ui.controllerExtensions";
// map of component configurations
var mComponentConfigs = {};
/**
* finds the config in the given type and use the check function to validate
* if the correct entry has been found!
* @param {string} sType name of the config section
* @param {function} fnCheck check function
*/
function findConfig(sType, fnCheck) {
// TODO: checking order of components?
jQuery.each(mComponentConfigs, function(sNamespace, oConfig) {
if (oConfig && oConfig[sType]) {
if (fnCheck(oConfig[sType])) {
return false;
}
}
});
};
/**
* The static object <code>CustomizingConfiguration</code> contains configuration
* for view replacements, view extensions and custom properties. The configuration
* will be added from component metadata objects once the component gets activated.
* By deactivating the component the customizing configuration of the component
* gets removed again.
*
* @author SAP AG
* @version 1.22.10
* @constructor
* @private
* @since 1.15.1
* @name sap.ui.core.CustomizingConfiguration
*/
var CustomizingConfiguration = {
/**
* logging of customizing configuration
* @private
*/
log: function() {
if (window.console) {
window.console.log(mComponentConfigs);
}
},
/**
* Activates the customizing of a component by registering the component
* configuration in the central customizing configuration.
* @param {string} sComponentName the name of the component
* @private
*/
activateForComponent: function(sComponentName) {
jQuery.sap.log.info("CustomizingConfiguration: activateForComponent('" + sComponentName + "')");
var sFullComponentName = sComponentName + ".Component";
jQuery.sap.require(sFullComponentName);
var oCustomizingConfig = jQuery.sap.getObject(sFullComponentName).getMetadata().getCustomizing();
mComponentConfigs[sComponentName] = oCustomizingConfig;
},
/**
* Deactivates the customizing of a component by removing the component
* configuration in the central customizing configuration.
* @param {string} sComponentName the name of the component
* @private
*/
deactivateForComponent: function(sComponentName) {
jQuery.sap.log.info("CustomizingConfiguration: deactivateForComponent('" + sComponentName + "')");
delete mComponentConfigs[sComponentName];
},
/**
* returns the configuration of the replacement View or undefined
* @private
*/
getViewReplacement: function(sViewName) {
var oResultConfig = undefined;
// TODO: checking order of components?
findConfig(CONFIG_VIEW_REPLACEMENTS, function(oConfig) {
oResultConfig = oConfig[sViewName];
return !!oResultConfig;
});
return oResultConfig;
},
/**
* returns the configuration of the given extension point or undefined
* @private
*/
getViewExtension: function(sViewName, sExtensionPointName) { // FIXME: currently ONE extension wins, but they should be somehow merged - but how to define the order?
var oResultConfig = undefined;
// TODO: checking order of components?
findConfig(CONFIG_VIEW_EXTENSIONS, function(oConfig) {
oResultConfig = oConfig[sViewName] && oConfig[sViewName][sExtensionPointName];
return !!oResultConfig;
});
return oResultConfig;
},
/**
* returns the configuration of the controller extensions for the given
* controller name
* @private
*/
getControllerExtension: function(sControllerName) {
var oResultConfig = undefined;
findConfig(CONFIG_CONTROLLER_EXTENSIONS, function(oConfig) {
oResultConfig = oConfig[sControllerName];
return !!oResultConfig;
});
return oResultConfig;
},
/**
* currently returns an object (or undefined) because we assume there is
* only one property modified and only once, but this
* @private
*/
getCustomProperties: function(sViewName, sControlId) { // TODO: Fragments and Views are mixed here
var mSettings = {};
// TODO: checking order of components?
findConfig(CONFIG_VIEW_MODIFICATIONS, function(oConfig) {
var oSettings = oConfig[sViewName] && oConfig[sViewName][sControlId];
var oUsedSettings = {};
if (oSettings) {
jQuery.each(oSettings, function(sName, vValue) {
if (sName === "visible") {
oUsedSettings[sName] = vValue;
jQuery.sap.log.info("Customizing: custom value for property '" + sName + "' of control '" + sControlId + "' in View '" + sViewName + "' applied: " + vValue);
} else {
jQuery.sap.log.warning("Customizing: custom value for property '" + sName + "' of control '" + sControlId + "' in View '" + sViewName + "' ignored: only the 'visible' property can be customized.");
}
});
jQuery.extend(mSettings, oUsedSettings); // FIXME: this currently overrides customizations from different components in random order
}
});
return mSettings;
}
};
// when the customizing is disabled all the functions will be noop
if (sap.ui.getCore().getConfiguration().getDisableCustomizing()) {
jQuery.sap.log.info("CustomizingConfiguration: disabling Customizing now");
jQuery.each(CustomizingConfiguration, function(sName, vAny) {
if (typeof vAny === "function") {
CustomizingConfiguration[sName] = function() {};
}
});
}
return CustomizingConfiguration;
}, /* bExport= */ true);
| esjewett/tdcode-examples | lib/openUI5/resources/sap/ui/core/CustomizingConfiguration-dbg.js | JavaScript | apache-2.0 | 6,061 |
var chai = require('chai'),
expect = chai.expect;
import {default as React} from 'react';
import {default as i18n} from '../src/i18n';
let Application = React.createElement('div');
let props = {
messages : {
"Shared":{
"Save": "Save it!"
}
}
};
describe('internationalize', () => {
let IntlApplication;
beforeEach(() => {
IntlApplication = i18n(Application);
});
it('provides Intl class with contextTypes', () => {
expect(IntlApplication.childContextTypes).to.be.defined;
expect(IntlApplication.childContextTypes.getIntlMessage).to.be.defined;
});
it('creates Intl component', () => {
let appInstance = new IntlApplication(props);
expect(appInstance).to.be.defined;
expect(appInstance).to.be.an('object');
});
describe('Intl', () => {
let appInstance, childContext;
beforeEach(() => {
appInstance = new IntlApplication(props);
childContext = appInstance.getChildContext();
});
it('has context', () => {
expect(childContext).to.be.defined;
});
it('has getIntlMessage function', () => {
expect(childContext.getIntlMessage).to.be.defined;
});
it('getIntlMessage returns message for specified path', () => {
expect(childContext.getIntlMessage('Shared.Save')).to.equal('Save it!');
});
});
});
| Brightspace/react-frau-intl | test/i18n.js | JavaScript | apache-2.0 | 1,341 |
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var bench = require( '@stdlib/bench' );
var randu = require( '@stdlib/random/base/randu' );
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var EPS = require( '@stdlib/constants/float64/eps' );
var pkg = require( './../package.json' ).name;
var F = require( './../lib' );
// MAIN //
bench( pkg+'::instantiation', function benchmark( b ) {
var dist;
var d1;
var d2;
var i;
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
d1 = ( randu() * 10.0 ) + EPS;
d2 = ( randu() * 10.0 ) + EPS;
dist = new F( d1, d2 );
if ( !( dist instanceof F ) ) {
b.fail( 'should return a distribution instance' );
}
}
b.toc();
if ( !( dist instanceof F ) ) {
b.fail( 'should return a distribution instance' );
}
b.pass( 'benchmark finished' );
b.end();
});
bench( pkg+'::get:d1', function benchmark( b ) {
var dist;
var d1;
var d2;
var y;
var i;
d1 = 10.56;
d2 = 5.54;
dist = new F( d1, d2 );
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
y = dist.d1;
if ( y !== d1 ) {
b.fail( 'should return set value' );
}
}
b.toc();
if ( isnan( y ) ) {
b.fail( 'should not return NaN' );
}
b.pass( 'benchmark finished' );
b.end();
});
bench( pkg+'::set:d1', function benchmark( b ) {
var dist;
var d1;
var d2;
var y;
var i;
d1 = 10.56;
d2 = 5.54;
dist = new F( d1, d2 );
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
y = ( 10.0*randu() ) + EPS;
dist.d1 = y;
if ( dist.d1 !== y ) {
b.fail( 'should return set value' );
}
}
b.toc();
if ( isnan( y ) ) {
b.fail( 'should not return NaN' );
}
b.pass( 'benchmark finished' );
b.end();
});
bench( pkg+'::get:d2', function benchmark( b ) {
var dist;
var d1;
var d2;
var y;
var i;
d1 = 10.56;
d2 = 5.54;
dist = new F( d1, d2 );
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
y = dist.d2;
if ( y !== d2 ) {
b.fail( 'should return set value' );
}
}
b.toc();
if ( isnan( y ) ) {
b.fail( 'should not return NaN' );
}
b.pass( 'benchmark finished' );
b.end();
});
bench( pkg+'::set:d2', function benchmark( b ) {
var dist;
var d1;
var d2;
var y;
var i;
d1 = 10.56;
d2 = 5.54;
dist = new F( d1, d2 );
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
y = ( 10.0*randu() ) + EPS;
dist.d2 = y;
if ( dist.d2 !== y ) {
b.fail( 'should return set value' );
}
}
b.toc();
if ( isnan( y ) ) {
b.fail( 'should not return NaN' );
}
b.pass( 'benchmark finished' );
b.end();
});
bench( pkg+':entropy', function benchmark( b ) {
var dist;
var d1;
var d2;
var y;
var i;
d1 = 10.56;
d2 = 5.54;
dist = new F( d1, d2 );
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
dist.d1 = ( 10.0*randu() ) + EPS;
y = dist.entropy;
if ( isnan( y ) ) {
b.fail( 'should not return NaN' );
}
}
b.toc();
if ( isnan( y ) ) {
b.fail( 'should not return NaN' );
}
b.pass( 'benchmark finished' );
b.end();
});
bench( pkg+':kurtosis', function benchmark( b ) {
var dist;
var d1;
var d2;
var y;
var i;
d1 = 10.56;
d2 = 8.54;
dist = new F( d1, d2 );
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
dist.d1 = ( 10.0*randu() ) + 8.0 + EPS;
y = dist.kurtosis;
if ( isnan( y ) ) {
b.fail( 'should not return NaN' );
}
}
b.toc();
if ( isnan( y ) ) {
b.fail( 'should not return NaN' );
}
b.pass( 'benchmark finished' );
b.end();
});
bench( pkg+':mean', function benchmark( b ) {
var dist;
var d1;
var d2;
var y;
var i;
d1 = 10.56;
d2 = 5.54;
dist = new F( d1, d2 );
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
dist.d1 = ( 10.0*randu() ) + EPS;
y = dist.mean;
if ( isnan( y ) ) {
b.fail( 'should not return NaN' );
}
}
b.toc();
if ( isnan( y ) ) {
b.fail( 'should not return NaN' );
}
b.pass( 'benchmark finished' );
b.end();
});
bench( pkg+':mode', function benchmark( b ) {
var dist;
var d1;
var d2;
var y;
var i;
d1 = 10.56;
d2 = 5.54;
dist = new F( d1, d2 );
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
dist.d1 = ( 10.0*randu() ) + 2.0 + EPS;
y = dist.mode;
if ( isnan( y ) ) {
b.fail( 'should not return NaN' );
}
}
b.toc();
if ( isnan( y ) ) {
b.fail( 'should not return NaN' );
}
b.pass( 'benchmark finished' );
b.end();
});
bench( pkg+':skewness', function benchmark( b ) {
var dist;
var d1;
var d2;
var y;
var i;
d1 = 10.56;
d2 = 6.54;
dist = new F( d1, d2 );
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
dist.d1 = ( 10.0*randu() ) + 6.0 + EPS;
y = dist.skewness;
if ( isnan( y ) ) {
b.fail( 'should not return NaN' );
}
}
b.toc();
if ( isnan( y ) ) {
b.fail( 'should not return NaN' );
}
b.pass( 'benchmark finished' );
b.end();
});
bench( pkg+':stdev', function benchmark( b ) {
var dist;
var d1;
var d2;
var y;
var i;
d1 = 10.56;
d2 = 5.54;
dist = new F( d1, d2 );
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
dist.d1 = ( 10.0*randu() ) + 1.0 + EPS;
y = dist.stdev;
if ( isnan( y ) ) {
b.fail( 'should not return NaN' );
}
}
b.toc();
if ( isnan( y ) ) {
b.fail( 'should not return NaN' );
}
b.pass( 'benchmark finished' );
b.end();
});
bench( pkg+':variance', function benchmark( b ) {
var dist;
var d1;
var d2;
var y;
var i;
d1 = 10.56;
d2 = 5.54;
dist = new F( d1, d2 );
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
dist.d1 = ( 10.0*randu() ) + 1.0 + EPS;
y = dist.variance;
if ( isnan( y ) ) {
b.fail( 'should not return NaN' );
}
}
b.toc();
if ( isnan( y ) ) {
b.fail( 'should not return NaN' );
}
b.pass( 'benchmark finished' );
b.end();
});
bench( pkg+':cdf', function benchmark( b ) {
var dist;
var d1;
var d2;
var x;
var y;
var i;
d1 = 10.56;
d2 = 5.54;
dist = new F( d1, d2 );
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
x = randu();
y = dist.cdf( x );
if ( isnan( y ) ) {
b.fail( 'should not return NaN' );
}
}
b.toc();
if ( isnan( y ) ) {
b.fail( 'should not return NaN' );
}
b.pass( 'benchmark finished' );
b.end();
});
bench( pkg+':pdf', function benchmark( b ) {
var dist;
var d1;
var d2;
var x;
var y;
var i;
d1 = 10.56;
d2 = 5.54;
dist = new F( d1, d2 );
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
x = randu();
y = dist.pdf( x );
if ( isnan( y ) ) {
b.fail( 'should not return NaN' );
}
}
b.toc();
if ( isnan( y ) ) {
b.fail( 'should not return NaN' );
}
b.pass( 'benchmark finished' );
b.end();
});
bench( pkg+':quantile', function benchmark( b ) {
var dist;
var d1;
var d2;
var x;
var y;
var i;
d1 = 10.56;
d2 = 5.54;
dist = new F( d1, d2 );
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
x = randu();
y = dist.quantile( x );
if ( isnan( y ) ) {
b.fail( 'should not return NaN' );
}
}
b.toc();
if ( isnan( y ) ) {
b.fail( 'should not return NaN' );
}
b.pass( 'benchmark finished' );
b.end();
});
| stdlib-js/stdlib | lib/node_modules/@stdlib/stats/base/dists/f/ctor/benchmark/benchmark.js | JavaScript | apache-2.0 | 7,441 |
/**
* checkArgs returns true when there is a matching signature.
* @param {Type} type object with type information.
* @param {Array<Argument>} args are the arguments passed into a function.
* @param {number} paramIndex index of the argument to be analyzed.
* @return {boolean} true if there is a signature that matches the types of the
* operation arguments.
*/
function checkArg(type, args, paramIndex) {
var param = args[paramIndex];
var paramType = typeof param;
if (paramType === 'object') {
if (type.array) {
return param.every(function(item) {
return typeof item === type.typeOf;
});
}
return param instanceof type.instance;
}
if (paramType === type.typeOf) {
if (type.varArgs) {
var varArgs = args.slice(paramIndex, args.length);
return varArgs.every(function(varArg) {
return typeof varArg === type.typeOf;
});
}
if (type.enum) {
return type.enum[param] !== undefined;
}
return true;
}
return false;
}
/**
* checkArgs
* @param {Array<Argument>} args are the arguments passed into a function.
* @param {Array<Types>} signatures all valid signatures.
* @return {boolean} true if there is at least one matching signature.
*/
function checkArgs(args, signatures) {
return signatures.some(function(signature) {
var isVariadic = signature.some(function(param) {
return param.varArgs;
});
if (!isVariadic && signature.length !== args.length) {
return false;
}
return signature.every(function(type, paramIndex) {
return checkArg(type, args, paramIndex);
});
});
}
module.exports = checkArgs;
| airamrguez/cordova-plugin-realm | www/checkArgs.js | JavaScript | apache-2.0 | 1,655 |
/**
* Copyright 2015 The AMP HTML Authors. 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.
*/
import {BaseElement} from './base-element';
import {BaseTemplate, registerExtendedTemplate} from './template';
import {assert} from './asserts';
import {getMode} from './mode';
import {installStyles} from './styles';
import {isExperimentOn, toggleExperiment} from './experiments';
import {performanceFor} from './performance';
import {registerElement} from './custom-element';
import {registerExtendedElement} from './extended-element';
import {resourcesFor} from './resources';
import {viewerFor} from './viewer';
import {viewportFor} from './viewport';
/** @type {!Array} */
const elementsForTesting = [];
/**
* Applies the runtime to a given global scope.
* Multi frame support is currently incomplete.
* @param {!Window} global Global scope to adopt.
*/
export function adopt(global) {
// Tests can adopt the same window twice. sigh.
if (global.AMP_TAG) {
return;
}
global.AMP_TAG = true;
// If there is already a global AMP object we assume it is an array
// of functions
const preregisteredElements = global.AMP || [];
global.AMP = {};
/**
* Registers an extended element and installs its styles.
* @param {string} name
* @param {!Function} implementationClass
* @param {string=} opt_css Optional CSS to install with the component. Use
* the special variable $CSS$ in your code. It will be replaced with the
* CSS file associated with the element.
*/
global.AMP.registerElement = function(name, implementationClass, opt_css) {
const register = function() {
registerExtendedElement(global, name, implementationClass);
elementsForTesting.push({
name: name,
implementationClass: implementationClass
});
};
if (opt_css) {
installStyles(global.document, opt_css, register);
} else {
register();
}
};
/** @const */
global.AMP.BaseElement = BaseElement;
/** @const */
global.AMP.BaseTemplate = BaseTemplate;
/**
* Registers an extended template.
* @param {string} name
* @param {!Function} implementationClass
*/
global.AMP.registerTemplate = function(name, implementationClass) {
registerExtendedTemplate(global, name, implementationClass);
};
/** @const */
global.AMP.assert = assert;
const viewer = viewerFor(global);
/** @const */
global.AMP.viewer = viewer;
if (getMode().development) {
/** @const */
global.AMP.toggleRuntime = viewer.toggleRuntime.bind(viewer);
/** @const */
global.AMP.resources = resourcesFor(global);
/** @const */
global.AMP.isExperimentOn = isExperimentOn.bind(null, global);
/** @const */
global.AMP.toggleExperiment = toggleExperiment.bind(null, global);
}
const viewport = viewportFor(global);
/** @const */
global.AMP.viewport = {};
global.AMP.viewport.getScrollLeft = viewport.getScrollLeft.bind(viewport);
global.AMP.viewport.getScrollWidth = viewport.getScrollWidth.bind(viewport);
global.AMP.viewport.getWidth = viewport.getWidth.bind(viewport);
/**
* Registers a new custom element.
* @param {GlobalAmp} fn
*/
global.AMP.push = function(fn) {
preregisteredElements.push(fn);
fn(global.AMP);
};
/**
* Sets the function to forward tick events to.
* @param {funtion(string,?string=,number=)} fn
* @param {function()=} opt_flush
* @export
*/
global.AMP.setTickFunction = (fn, opt_flush) => {
const perf = performanceFor(global);
perf.setTickFunction(fn, opt_flush);
};
// Execute asynchronously scheduled elements.
for (let i = 0; i < preregisteredElements.length; i++) {
const fn = preregisteredElements[i];
fn(global.AMP);
}
}
/**
* Registers all extended elements as normal elements in the given
* window.
* Make sure to call `adopt(window)` in your unit test as well and
* then call this on the generated iframe.
* @param {!Window} win
*/
export function registerForUnitTest(win) {
for (let i = 0; i < elementsForTesting.length; i++) {
const element = elementsForTesting[i];
registerElement(win, element.name, element.implementationClass);
}
}
| chrisbrent/amphtml | src/runtime.js | JavaScript | apache-2.0 | 4,726 |
'use strict';
/**
* @license
* Copyright SOAJS All Rights Reserved.
*
* Use of this source code is governed by an Apache license that can be
* found in the LICENSE file at the root of this repository
*/
const lib = {
"mail": null,
"pin": require("../../lib/pin.js"),
"generateUsername": require("../../lib/generateUsername.js")
};
let bl = null;
let local = (soajs, inputmaskData, options, cb) => {
let modelObj = bl.user.mt.getModel(soajs);
options = {};
options.mongoCore = modelObj.mongoCore;
inputmaskData = inputmaskData || {};
if (!inputmaskData.username) {
inputmaskData.username = lib.generateUsername();
}
bl.user.countUser(soajs, inputmaskData, options, (error, found) => {
if (error) {
//close model
bl.user.mt.closeModel(modelObj);
return cb(bl.user.handleError(soajs, 602, error), null);
}
if (found) {
//close model
bl.user.mt.closeModel(modelObj);
return cb(bl.user.handleError(soajs, 402, null));
}
inputmaskData.config = {};
let doAdd = (pin, pinCode) => {
bl.user.add(soajs, inputmaskData, options, (error, userRecord) => {
if (error) {
//close model
bl.user.mt.closeModel(modelObj);
return cb(error, null);
}
if (pin) {
userRecord.pin = pinCode;
lib.mail.send(soajs, 'invitePin', userRecord, null, function (error) {
if (error) {
soajs.log.info('invitePin: No Mail was sent: ' + error.message);
}
});
}
if (userRecord.status === "pending") {
bl.user.mt.closeModel(modelObj);
return cb(null, {
id: userRecord._id.toString()
});
} else if (userRecord.status !== "pendingNew") {
//close model
bl.user.mt.closeModel(modelObj);
lib.mail.send(soajs, "addUser", userRecord, null, function (error) {
if (error) {
soajs.log.info('addUserNotPending: No Mail was sent: ' + error.message);
}
return cb(null, {
id: userRecord._id.toString()
});
});
} else {
let data = {};
data.userId = userRecord._id.toString();
data.username = userRecord.username;
data.service = "addUser";
bl.token.add(soajs, data, options, (error, tokenRecord) => {
bl.user.mt.closeModel(modelObj);
if (error) {
return cb(error, null);
}
lib.mail.send(soajs, "addUser", userRecord, tokenRecord, function (error) {
if (error) {
soajs.log.info('addUser: No Mail was sent: ' + error.message);
}
return cb(null, {
id: userRecord._id.toString()
});
});
});
}
});
};
let doPin = (mainTenant) => {
let generatedPin = null;
if (inputmaskData.pin && inputmaskData.pin.code) {
let pinConfig = lib.pin.config(soajs, bl.user.localConfig);
try {
generatedPin = lib.pin.generate(pinConfig);
if (mainTenant) {
inputmaskData.tenant.pin.code = generatedPin;
} else {
inputmaskData.config.allowedTenants[0].tenant.pin.code = generatedPin;
inputmaskData.config.allowedTenants[0].tenant.pin.allowed = !!inputmaskData.pin.allowed;
}
inputmaskData.tenant.pin.allowed = !!inputmaskData.pin.allowed;
doAdd(true, generatedPin);
} catch (e) {
//close model
bl.user.mt.closeModel(modelObj);
return cb(bl.user.handleError(soajs, 525, e));
}
} else {
doAdd(false, null);
}
};
if (inputmaskData.membership) {
let membershipConfig = null;
if (soajs.servicesConfig && soajs.servicesConfig.urac && soajs.servicesConfig.urac.membership) {
if (soajs.servicesConfig.urac.membership[inputmaskData.membership]) {
membershipConfig = soajs.servicesConfig.urac.membership[inputmaskData.membership];
}
}
if (!membershipConfig && soajs.registry && soajs.registry.custom && soajs.registry.custom.urac && soajs.registry.custom.urac.value && soajs.registry.custom.urac.value.membership) {
if (soajs.registry.custom.urac.value.membership[inputmaskData.membership]) {
membershipConfig = soajs.registry.custom.urac.value.membership[inputmaskData.membership];
}
}
if (membershipConfig) {
if (membershipConfig.groups) {
if (Array.isArray(membershipConfig.groups) && membershipConfig.groups.length > 0) {
inputmaskData.groups = membershipConfig.groups;
} else {
soajs.log.warn("Skipping [" + inputmaskData.membership + "] membership setting, groups must be an array of at least one group");
}
}
} else {
soajs.log.debug("Skipping [" + inputmaskData.membership + "] membership, unable to find any setting for it");
}
}
if (soajs.tenant.type === "client" && soajs.tenant.main) {
inputmaskData.tenant = {
id: soajs.tenant.main.id,
code: soajs.tenant.main.code,
pin: {}
};
if (!inputmaskData.config.allowedTenants) {
inputmaskData.config.allowedTenants = [];
}
let allowedTenantObj = {
"tenant": {
"id": soajs.tenant.id,
"code": soajs.tenant.code,
"pin": {}
}
};
if (inputmaskData.groups) {
allowedTenantObj.groups = inputmaskData.groups;
inputmaskData.groups = [];
}
inputmaskData.config.allowedTenants.push(allowedTenantObj);
doPin(false);
} else {
if (!inputmaskData.tenant) {
inputmaskData.tenant = {
"id": soajs.tenant.id,
"code": soajs.tenant.code,
"pin": {}
};
} else {
inputmaskData.tenant.pin = {};
}
doPin(true);
}
});
};
module.exports = function (_bl) {
bl = _bl;
lib.mail = require("../../lib/mail.js")(bl);
return local;
};
| soajs/soajs.urac | bl/lib/addUser.js | JavaScript | apache-2.0 | 7,436 |
/**
* Copyright 2014 Scn Community Contributors
*
* Original Source Code Location:
* https://github.com/org-scn-design-studio-community/sdkpackage/
*
* 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.
*/
(function() {
org_scn_community_require.knownComponents.databound.HarveyBallMicroChart.spec =
{};
org_scn_community_require.knownComponents.databound.HarveyBallMicroChart.specInclude =
{
"colorPalette": {
"opts": {
"apsControl": "array",
"arrayMode": "StringArray",
"cat": "Display",
"desc": "Colour Palette",
"noAps": false,
"noZtl": false,
"tooltip": "The color palette for the chart. If this property is set, semantic colors defined in HarveyBallMicroChart are ignored. Colors from the palette are assigned to each slice consequentially. When all the palette colors are used, assignment of the colors begins from the first palette color.",
"ztlFunction": "",
"ztlType": "StringArray"
},
"origType": "string[]",
"template": "StringArray",
"type": "String",
"value": "[]",
"visible": true
},
"contentWidth": {
"opts": {
"apsControl": "spinner",
"cat": "Display",
"desc": "Content Width",
"noAps": false,
"noZtl": false,
"tooltip": "The width of the chart. If it is not set, the size of the control is defined by the size property.",
"ztlFunction": "",
"ztlType": "int"
},
"template": "int",
"type": "int",
"value": 0,
"visible": true
},
"dataCellListItems": {
"options": {
"includeData": "true",
"includeFormattedData": "true"
},
"opts": {
"cat": "Data",
"desc": "Items Data List [Multiple]",
"noAps": true,
"noZtl": true,
"tooltip": "Items Data List [Multiple]",
"type": "data",
"value": "null",
"ztlFunction": ""
},
"template": "ds-DataCellList",
"type": "ResultCellList",
"value": "null",
"visible": true
},
"dataCellListTotal": {
"options": {
"includeData": "true",
"includeFormattedData": "true"
},
"opts": {
"cat": "Data",
"desc": "Total Data List",
"noAps": true,
"noZtl": true,
"tooltip": "Total Data List",
"type": "data",
"value": "null",
"ztlFunction": ""
},
"template": "ds-DataCellList",
"type": "ResultCellList",
"value": "null",
"visible": true
},
"formattedLabel": {
"opts": {
"apsControl": "checkbox",
"cat": "Display-Labels",
"desc": "Formatted Label",
"noAps": false,
"noZtl": false,
"tooltip": "If set to true, the totalLabel parameter is considered as the combination of the total value and its scaling factor. The default value is false. It means that the total value and the scaling factor are defined separately by the total and the totalScale properties accordingly.",
"ztlFunction": "",
"ztlType": "boolean"
},
"template": "boolean",
"type": "boolean",
"value": false,
"visible": true
},
"items": {
"opts": {
"apsControl": "array",
"arrayDefinition": {"items": {
"color": {
"apsControl": "combobox",
"desc": "Colour",
"options": [
{
"key": "Neutral",
"text": "Neutral InfoTile value color"
},
{
"key": "Good",
"text": "Good InfoTile value color"
},
{
"key": "Critical",
"text": "Critical InfoTile value color"
},
{
"key": "Error",
"text": "Error InfoTile value color"
}
],
"type": "String"
},
"formattedLabel": {
"desc": "Formatted Label",
"type": "boolean"
},
"fraction": {
"desc": "Fraction",
"type": "float"
},
"fractionLabel": {
"desc": "Fraction Label",
"type": "String"
},
"fractionScale": {
"desc": "Fraction Scale",
"type": "String"
},
"key": {
"desc": "Unique Property Key",
"type": "String"
},
"sequence": "key,color,formattedLabel,fraction,fractionLabel,fractionScale",
"type": "Array"
}},
"arrayMode": "OneLevelArray",
"cat": "Content-Items",
"desc": "Items",
"noAps": false,
"noZtl": false,
"tooltip": "The pie chart slices.",
"ztlFunction": "",
"ztlType": "SingleArray"
},
"origType": "HarveyBallMicroChartItem",
"template": "ObjectArray",
"type": "String",
"value": "[{\"parentKey\":\"ROOT\",\"key\":\"ELEMENT\",\"leaf\":false,\"formattedLabel\":false,\"color\":\"Good\",\"fraction\":20,\"fractionLabel\":\"sold \",\"fractionScale\":\"20T\"}]",
"visible": true
},
"showFractions": {
"opts": {
"apsControl": "checkbox",
"cat": "Display",
"desc": "Show Fractions",
"noAps": false,
"noZtl": false,
"tooltip": "If set to true, the fraction values are displayed near the pie chart. Default is true.",
"ztlFunction": "",
"ztlType": "boolean"
},
"template": "boolean",
"type": "boolean",
"value": true,
"visible": true
},
"showTotal": {
"opts": {
"apsControl": "checkbox",
"cat": "Display",
"desc": "Show Total",
"noAps": false,
"noZtl": false,
"tooltip": "If set to true, the total value is displayed near the pie chart. Default is true.",
"ztlFunction": "",
"ztlType": "boolean"
},
"template": "boolean",
"type": "boolean",
"value": true,
"visible": true
},
"size": {
"opts": {
"apsControl": "combobox",
"cat": "Display",
"choiceType": "InfoTileSize",
"desc": "Size",
"noAps": false,
"noZtl": false,
"options": [
{
"key": "XS",
"text": "Extra small size"
},
{
"key": "S",
"text": "Small size"
},
{
"key": "M",
"text": "Medium size"
},
{
"key": "L",
"text": "Large size"
},
{
"key": "Auto",
"text": "The size of the tile depends on the device it is running on. It is large on desktop, medium on tablet and small on phone"
}
],
"tooltip": "Updates the size of the chart. If not set then the default size is applied based on the device tile.",
"ztlFunction": "",
"ztlType": "Choice"
},
"template": "Choice",
"type": "String",
"value": "Auto",
"visible": true
},
"total": {
"opts": {
"apsControl": "text",
"cat": "Display",
"desc": "Total",
"noAps": false,
"noZtl": false,
"tooltip": "The total value. This is taken as 360 degrees value on the chart.",
"ztlFunction": "",
"ztlType": "float"
},
"template": "float",
"type": "float",
"value": 100,
"visible": true
},
"totalLabel": {
"opts": {
"apsControl": "text",
"cat": "Display-Labels",
"desc": "Total Label",
"noAps": false,
"noZtl": false,
"tooltip": "The total label. If specified, it is displayed instead of the total value.",
"ztlFunction": "",
"ztlType": "String"
},
"template": "String",
"type": "String",
"value": "",
"visible": true
},
"totalScale": {
"opts": {
"apsControl": "text",
"cat": "Display",
"desc": "Total Scale",
"noAps": false,
"noZtl": false,
"tooltip": "The scaling factor that is displayed after the total value.",
"ztlFunction": "",
"ztlType": "String"
},
"template": "String",
"type": "String",
"value": "M",
"visible": true
},
"useColorPalette": {
"opts": {
"apsControl": "checkbox",
"cat": "Display",
"desc": "Use Manual 'Colour Palette'",
"noAps": false,
"noZtl": false,
"tooltip": "If checked, the property 'Colour Palette' will be used.",
"ztlFunction": "",
"ztlType": "boolean"
},
"template": "ds-boolean",
"type": "boolean",
"value": true,
"visible": true
},
"useContentWidth": {
"opts": {
"apsControl": "checkbox",
"cat": "Display",
"desc": "Use Manual 'Content Width'",
"noAps": false,
"noZtl": false,
"tooltip": "If checked, the property 'Content Width' will be used.",
"ztlFunction": "",
"ztlType": "boolean"
},
"template": "ds-boolean",
"type": "boolean",
"value": true,
"visible": true
},
"useItems": {
"opts": {
"apsControl": "checkbox",
"cat": "Content-Items",
"desc": "Use Manual 'Items'",
"noAps": false,
"noZtl": false,
"tooltip": "If checked, the property 'Items' will be used.",
"ztlFunction": "",
"ztlType": "boolean"
},
"template": "ds-boolean",
"type": "boolean",
"value": true,
"visible": true
},
"useTotal": {
"opts": {
"apsControl": "checkbox",
"cat": "Display",
"desc": "Use Manual 'Total'",
"noAps": false,
"noZtl": false,
"tooltip": "If checked, the property 'Total' will be used.",
"ztlFunction": "",
"ztlType": "boolean"
},
"template": "ds-boolean",
"type": "boolean",
"value": true,
"visible": true
}
};
org_scn_community_require.knownComponents.databound.HarveyBallMicroChart.specAbout =
{
"description": "Harvey Ball Micro Chart - Component for Visualization of Data on small areas",
"icon": "HarveyBallMicroChart.png",
"title": "Harvey Ball Micro Chart 2.0",
"topics": [
{
"content": "This component can visualize the data on small area as harvey ball chart.",
"title": "Harvey Ball Micro Chart"
},
{
"content": "This component is a visualization component. It requires specific space in the application canvas.",
"title": "Visualization"
}
]
};
org_scn_community_require.knownComponents.databound.HarveyBallMicroChart.specComp =
{
"dataType": "DataCellList",
"databound": true,
"extends1ControlDs": "HarveyBallMicroChart.ds",
"extends2Control": "HarveyBallMicroChart",
"extension": "ui5.HarveyBallMicroChart",
"generatedJsFile": "true",
"group": "ScnCommunityUnified",
"handlerType": "sapui5",
"height": "100",
"id": "HarveyBallMicroChart",
"package": "databound",
"parentControl": "sap.ui.commons.layout.AbsoluteLayout",
"repeaterProperty": "items",
"require": [
{
"id": "common_basics",
"space": "known"
},
{
"id": "common_databound",
"space": "known"
},
{
"id": "common_unified",
"space": "known"
},
{
"id": "jshashtable",
"space": "known"
},
{
"id": "numberformatter",
"space": "known"
},
{
"id": "sap_m_loader",
"space": "known"
},
{
"id": "sap_suite_loader",
"space": "known"
}
],
"title": "Harvey Ball Micro Chart2.0",
"tooltip": "Harvey Ball Micro Chart- Component for visualization of data on small areas.",
"width": "200"
};
})();// End of closure
| bugodelnya/scn-sdk-package | src/org.scn.community.databound/res/HarveyBallMicroChart/HarveyBallMicroChartSpec.js | JavaScript | apache-2.0 | 11,827 |
$('#create-idea-tab').dblclick(function() {
var uid = $(this).closest('#expand-tab').attr('uid');
location.href = "Idea/Idea/ideaList/uid/" + uid + "/type/create";
});
| grey256/easyX | public/app/usercenter/js/member.js | JavaScript | apache-2.0 | 180 |
/**
* Copyright JS Foundation and other contributors, http://js.foundation
*
* 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.
**/
/**
* @mixin @node-red/editor-api_auth
*/
var passport = require("passport");
var oauth2orize = require("oauth2orize");
var strategies = require("./strategies");
var Tokens = require("./tokens");
var Users = require("./users");
var permissions = require("./permissions");
var theme = require("../editor/theme");
var settings = null;
var log = require("@node-red/util").log; // TODO: separate module
passport.use(strategies.bearerStrategy.BearerStrategy);
passport.use(strategies.clientPasswordStrategy.ClientPasswordStrategy);
passport.use(strategies.anonymousStrategy);
var server = oauth2orize.createServer();
server.exchange(oauth2orize.exchange.password(strategies.passwordTokenExchange));
function init(_settings,storage) {
settings = _settings;
if (settings.adminAuth) {
var mergedAdminAuth = Object.assign({}, settings.adminAuth, settings.adminAuth.module);
Users.init(mergedAdminAuth);
Tokens.init(mergedAdminAuth,storage);
}
}
/**
* Returns an Express middleware function that ensures the user making a request
* has the necessary permission.
*
* @param {String} permission - the permission required for the request, such as `flows.write`
* @return {Function} - an Express middleware
* @memberof @node-red/editor-api_auth
*/
function needsPermission(permission) {
return function(req,res,next) {
if (settings && settings.adminAuth) {
return passport.authenticate(['bearer','anon'],{ session: false })(req,res,function() {
if (!req.user) {
return next();
}
if (permissions.hasPermission(req.authInfo.scope,permission)) {
return next();
}
log.audit({event: "permission.fail", permissions: permission},req);
return res.status(401).end();
});
} else {
next();
}
}
}
function ensureClientSecret(req,res,next) {
if (!req.body.client_secret) {
req.body.client_secret = 'not_available';
}
next();
}
function authenticateClient(req,res,next) {
return passport.authenticate(['oauth2-client-password'], {session: false})(req,res,next);
}
function getToken(req,res,next) {
return server.token()(req,res,next);
}
function login(req,res) {
var response = {};
if (settings.adminAuth) {
var mergedAdminAuth = Object.assign({}, settings.adminAuth, settings.adminAuth.module);
if (mergedAdminAuth.type === "credentials") {
response = {
"type":"credentials",
"prompts":[{id:"username",type:"text",label:"user.username"},{id:"password",type:"password",label:"user.password"}]
}
} else if (mergedAdminAuth.type === "strategy") {
var urlPrefix = (settings.httpAdminRoot==='/')?"":settings.httpAdminRoot;
response = {
"type":"strategy",
"prompts":[{type:"button",label:mergedAdminAuth.strategy.label, url: urlPrefix + "auth/strategy"}]
}
if (mergedAdminAuth.strategy.icon) {
response.prompts[0].icon = mergedAdminAuth.strategy.icon;
}
if (mergedAdminAuth.strategy.image) {
response.prompts[0].image = theme.serveFile('/login/',mergedAdminAuth.strategy.image);
}
}
if (theme.context().login && theme.context().login.image) {
response.image = theme.context().login.image;
}
}
res.json(response);
}
function revoke(req,res) {
var token = req.body.token;
// TODO: audit log
Tokens.revoke(token).then(function() {
log.audit({event: "auth.login.revoke"},req);
if (settings.editorTheme && settings.editorTheme.logout && settings.editorTheme.logout.redirect) {
res.json({redirect:settings.editorTheme.logout.redirect});
} else {
res.status(200).end();
}
});
}
function completeVerify(profile,done) {
Users.authenticate(profile).then(function(user) {
if (user) {
Tokens.create(user.username,"node-red-editor",user.permissions).then(function(tokens) {
log.audit({event: "auth.login",username:user.username,scope:user.permissions});
user.tokens = tokens;
done(null,user);
});
} else {
log.audit({event: "auth.login.fail.oauth",username:typeof profile === "string"?profile:profile.username});
done(null,false);
}
});
}
function genericStrategy(adminApp,strategy) {
var crypto = require("crypto")
var session = require('express-session')
var MemoryStore = require('memorystore')(session)
adminApp.use(session({
// As the session is only used across the life-span of an auth
// hand-shake, we can use a instance specific random string
secret: crypto.randomBytes(20).toString('hex'),
resave: false,
saveUninitialized: false,
store: new MemoryStore({
checkPeriod: 86400000 // prune expired entries every 24h
})
}));
//TODO: all passport references ought to be in ./auth
adminApp.use(passport.initialize());
adminApp.use(passport.session());
var options = strategy.options;
passport.use(new strategy.strategy(options,
function() {
var originalDone = arguments[arguments.length-1];
if (options.verify) {
var args = Array.from(arguments);
args[args.length-1] = function(err,profile) {
if (err) {
return originalDone(err);
} else {
return completeVerify(profile,originalDone);
}
};
options.verify.apply(null,args);
} else {
var profile = arguments[arguments.length - 2];
return completeVerify(profile,originalDone);
}
}
));
adminApp.get('/auth/strategy',
passport.authenticate(strategy.name, {session:false, failureRedirect: settings.httpAdminRoot }),
completeGenerateStrategyAuth
);
var callbackMethodFunc = adminApp.get;
if (/^post$/i.test(options.callbackMethod)) {
callbackMethodFunc = adminApp.post;
}
callbackMethodFunc.call(adminApp,'/auth/strategy/callback',
passport.authenticate(strategy.name, {session:false, failureRedirect: settings.httpAdminRoot }),
completeGenerateStrategyAuth
);
}
function completeGenerateStrategyAuth(req,res) {
var tokens = req.user.tokens;
delete req.user.tokens;
// Successful authentication, redirect home.
res.redirect(settings.httpAdminRoot + '?access_token='+tokens.accessToken);
}
module.exports = {
init: init,
needsPermission: needsPermission,
ensureClientSecret: ensureClientSecret,
authenticateClient: authenticateClient,
getToken: getToken,
errorHandler: function(err,req,res,next) {
//TODO: audit log statment
//console.log(err.stack);
//log.log({level:"audit",type:"auth",msg:err.toString()});
return server.errorHandler()(err,req,res,next);
},
login: login,
revoke: revoke,
genericStrategy: genericStrategy
}
| HiroyasuNishiyama/node-red | packages/node_modules/@node-red/editor-api/lib/auth/index.js | JavaScript | apache-2.0 | 7,962 |
export const mp4File = new File(
[
new Blob(
[
'\x00\x00\x00 ftypisom\x00\x00\x02\x00isomiso2avc1mp41\x00\x00\x00\bfree\x00\x00\x00\bmdat\x00\x00\x00Ömoov\x00\x00\x00lmvhd\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x03è\x00\x00\x00\x00\x00\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00@\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00budta\x00\x00\x00Zmeta\x00\x00\x00\x00\x00\x00\x00!hdlr\x00\x00\x00\x00\x00\x00\x00\x00mdirappl\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00-ilst\x00\x00\x00%©too\x00\x00\x00\x1Ddata\x00\x00\x00\x01\x00\x00\x00\x00Lavf57.41.100',
],
{ type: 'video/mp4' }
),
],
'video.mp4'
);
| mnutt/davros | tests/fixtures/files.js | JavaScript | apache-2.0 | 899 |
(function () {
"use strict";
angular
.module("productManagement")
.controller("rptQuotationCtrl",
["$scope", "global", rptQuotationCtrl]);
function rptQuotationCtrl($scope, global) {
//Enable view essentials on load.
var setPreferences = {
menuBar: 'true',
menuActive: 'reports',
};
global.setViewPreferences(setPreferences);
}
}());
| sai-alladi/Chemlabs | Turnk/Src/Development/Code/QMS/QMS.Client/Views/Reports/reportQuotationCtrl.js | JavaScript | apache-2.0 | 463 |
/*
Copyright 2008-2009 University of Cambridge
Copyright 2008-2009 University of Toronto
Copyright 2007-2009 University of California, Berkeley
Licensed under the Educational Community License (ECL), Version 2.0 or the New
BSD license. You may not use this file except in compliance with one these
Licenses.
You may obtain a copy of the ECL 2.0 License and BSD License at
https://source.fluidproject.org/svn/LICENSE.txt
*/
// A super-simple jQuery TinyMCE plugin that actually works.
// Written by Colin Clark
/*global jQuery, tinyMCE*/
(function ($) {
if (typeof(tinyMCE) !== "undefined") {
// Invoke this immediately to prime TinyMCE.
tinyMCE.init({
mode: "none",
theme: "simple"
});
}
$.fn.tinymce = function () {
this.each(function () {
// Need code to generate an id for the tinymce control if one doesn't exist.
tinyMCE.execCommand("mceAddControl", false, this.id);
});
return this;
};
})(jQuery);
| GIP-RECIA/esco-grouper-ui | metier/esco-web/src/web/webapp/media/js/fluid/components/inlineEdit/js/jquery.tinymce.js | JavaScript | apache-2.0 | 1,046 |
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isArray = require( '@stdlib/assert/is-array' );
var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ).isPrimitive;
var PINF = require( '@stdlib/constants/float64/pinf' );
var deepCopy = require( './deep_copy.js' );
// MAIN //
/**
* Copies or deep clones a value to an arbitrary depth.
*
* @param {*} value - value to copy
* @param {NonNegativeInteger} [level=+infinity] - copy depth
* @throws {TypeError} `level` must be a nonnegative integer
* @returns {*} value copy
*
* @example
* var out = copy( 'beep' );
* // returns 'beep'
*
* @example
* var value = [
* {
* 'a': 1,
* 'b': true,
* 'c': [ 1, 2, 3 ]
* }
* ];
* var out = copy( value );
* // returns [ { 'a': 1, 'b': true, 'c': [ 1, 2, 3 ] } ]
*
* var bool = ( value[0].c === out[0].c );
* // returns false
*/
function copy( value, level ) {
var out;
if ( arguments.length > 1 ) {
if ( !isNonNegativeInteger( level ) ) {
throw new TypeError( 'invalid argument. `level` must be a nonnegative integer. Value: `' + level + '`.' );
}
if ( level === 0 ) {
return value;
}
} else {
level = PINF;
}
out = ( isArray( value ) ) ? new Array( value.length ) : {};
return deepCopy( value, out, [value], [out], level );
}
// EXPORTS //
module.exports = copy;
| stdlib-js/stdlib | lib/node_modules/@stdlib/utils/copy/lib/copy.js | JavaScript | apache-2.0 | 1,936 |
'use strict';
/** resource cache service, loads resources once and then provides cached version
* also allows refreshing specific resources */
angular.module('ngBlog.services').factory('resourceCache', ['$http', function ($http) {
var exports = {};
var cache = {};
var loadResource = function(url) {
$http({method: 'GET', url: url, cache: false}).then(function (res) {
cache[url].data = res.data;
if (res.data.hasOwnProperty("preload")) {
_.each(res.data.preload, function(item) { exports.getResource(item, _.str.endsWith("json")); });
}
});
};
exports.getResource = function(url, expectObject) {
if (!cache.hasOwnProperty(url)) {
if (expectObject) { cache[url] = { url: url, data: { snippets: {}, images: {}} }; }
else { cache[url] = { url: url, data: "" }; }
loadResource(url);
}
return cache[url];
};
exports.refresh = function(url) { loadResource(url); };
return exports;
}]);
| matthiasn/ng-blog | src/js/services/resource-cache.js | JavaScript | apache-2.0 | 1,061 |
import Raw from './raw'
import React from 'react'
import ReactDOMServer from 'react-dom/server'
import cheerio from 'cheerio'
import typeOf from 'type-of'
import { Record } from 'immutable'
/**
* String.
*
* @type {String}
*/
const String = new Record({
kind: 'string',
text: ''
})
/**
* A rule to (de)serialize text nodes. This is automatically added to the HTML
* serializer so that users don't have to worry about text-level serialization.
*
* @type {Object}
*/
const TEXT_RULE = {
deserialize(el) {
if (el.tagName == 'br') {
return {
kind: 'text',
text: '\n'
}
}
if (el.type == 'text') {
if (el.data && el.data.match(/<!--.*?-->/)) return
return {
kind: 'text',
text: el.data
}
}
},
serialize(obj, children) {
if (obj.kind == 'string') {
return children
.split('\n')
.reduce((array, text, i) => {
if (i != 0) array.push(<br />)
array.push(text)
return array
}, [])
}
}
}
/**
* HTML serializer.
*
* @type {Html}
*/
class Html {
/**
* Create a new serializer with `rules`.
*
* @param {Object} options
* @property {Array} rules
* @property {String} defaultBlockType
* @property {String|Object} defaultBlockType
*/
constructor(options = {}) {
this.rules = [
...(options.rules || []),
TEXT_RULE
]
this.defaultBlockType = options.defaultBlockType || 'paragraph'
}
/**
* Deserialize pasted HTML.
*
* @param {String} html
* @param {Object} options
* @property {Boolean} toRaw
* @return {State}
*/
deserialize = (html, options = {}) => {
const $ = cheerio.load(html).root()
const children = $.children().toArray()
let nodes = this.deserializeElements(children)
// HACK: ensure for now that all top-level inline are wrapped into a block.
nodes = nodes.reduce((memo, node, i, original) => {
if (node.kind == 'block') {
memo.push(node)
return memo
}
if (i > 0 && original[i - 1].kind != 'block') {
const block = memo[memo.length - 1]
block.nodes.push(node)
return memo
}
const { defaultBlockType } = this
const defaults = typeof defaultBlockType == 'string'
? { type: defaultBlockType }
: defaultBlockType
const block = {
kind: 'block',
nodes: [node],
...defaults
}
memo.push(block)
return memo
}, [])
const raw = {
kind: 'state',
document: {
kind: 'document',
nodes,
}
}
if (options.toRaw) {
return raw
}
const state = Raw.deserialize(raw, { terse: true })
return state
}
/**
* Deserialize an array of Cheerio `elements`.
*
* @param {Array} elements
* @return {Array}
*/
deserializeElements = (elements = []) => {
let nodes = []
elements.forEach((element) => {
const node = this.deserializeElement(element)
switch (typeOf(node)) {
case 'array':
nodes = nodes.concat(node)
break
case 'object':
nodes.push(node)
break
}
})
return nodes
}
/**
* Deserialize a Cheerio `element`.
*
* @param {Object} element
* @return {Any}
*/
deserializeElement = (element) => {
let node
const next = (elements) => {
switch (typeOf(elements)) {
case 'array':
return this.deserializeElements(elements)
case 'object':
return this.deserializeElement(elements)
case 'null':
case 'undefined':
return
default:
throw new Error(`The \`next\` argument was called with invalid children: "${elements}".`)
}
}
for (const rule of this.rules) {
if (!rule.deserialize) continue
const ret = rule.deserialize(element, next)
const type = typeOf(ret)
if (type != 'array' && type != 'object' && type != 'null' && type != 'undefined') {
throw new Error(`A rule returned an invalid deserialized representation: "${node}".`)
}
if (ret === undefined) continue
if (ret === null) return null
node = ret.kind == 'mark' ? this.deserializeMark(ret) : ret
break
}
return node || next(element.children)
}
/**
* Deserialize a `mark` object.
*
* @param {Object} mark
* @return {Array}
*/
deserializeMark = (mark) => {
const { type, data } = mark
const applyMark = (node) => {
if (node.kind == 'mark') {
return this.deserializeMark(node)
}
else if (node.kind == 'text') {
if (!node.ranges) node.ranges = [{ text: node.text }]
node.ranges = node.ranges.map((range) => {
range.marks = range.marks || []
range.marks.push({ type, data })
return range
})
}
else {
node.nodes = node.nodes.map(applyMark)
}
return node
}
return mark.nodes.reduce((nodes, node) => {
const ret = applyMark(node)
if (Array.isArray(ret)) return nodes.concat(ret)
nodes.push(ret)
return nodes
}, [])
}
/**
* Serialize a `state` object into an HTML string.
*
* @param {State} state
* @param {Object} options
* @property {Boolean} render
* @return {String|Array}
*/
serialize = (state, options = {}) => {
const { document } = state
const elements = document.nodes.map(this.serializeNode)
if (options.render === false) return elements
const html = ReactDOMServer.renderToStaticMarkup(<body>{elements}</body>)
const inner = html.slice(6, -7)
return inner
}
/**
* Serialize a `node`.
*
* @param {Node} node
* @return {String}
*/
serializeNode = (node) => {
if (node.kind == 'text') {
const ranges = node.getRanges()
return ranges.map(this.serializeRange)
}
const children = node.nodes.map(this.serializeNode)
for (const rule of this.rules) {
if (!rule.serialize) continue
const ret = rule.serialize(node, children)
if (ret) return addKey(ret)
}
throw new Error(`No serializer defined for node of type "${node.type}".`)
}
/**
* Serialize a `range`.
*
* @param {Range} range
* @return {String}
*/
serializeRange = (range) => {
const string = new String({ text: range.text })
const text = this.serializeString(string)
return range.marks.reduce((children, mark) => {
for (const rule of this.rules) {
if (!rule.serialize) continue
const ret = rule.serialize(mark, children)
if (ret) return addKey(ret)
}
throw new Error(`No serializer defined for mark of type "${mark.type}".`)
}, text)
}
/**
* Serialize a `string`.
*
* @param {String} string
* @return {String}
*/
serializeString = (string) => {
for (const rule of this.rules) {
if (!rule.serialize) continue
const ret = rule.serialize(string, string.text)
if (ret) return ret
}
}
}
/**
* Add a unique key to a React `element`.
*
* @param {Element} element
* @return {Element}
*/
let key = 0
function addKey(element) {
return React.cloneElement(element, { key: key++ })
}
/**
* Export.
*
* @type {Html}
*/
export default Html
| standardhealth/flux | src/lib/slate/serializers/html.js | JavaScript | apache-2.0 | 7,378 |
'use strict';
(function () {
angular.module('main').filter('nl2br', [nl2brFilter]);
function nl2brFilter () {
return function (data) {
if (!data) { return data; }
return data.replace(/\n\r?/g, '<br />');
};
}
})();
| YouCCTech/skyapp | app/main/infra/nl2br.filter.js | JavaScript | apache-2.0 | 241 |
(function(global) {
'use strict';
global.BoardRenderer = (function() {
var service = {
render: render
};
return service;
/////////////////////////
function render(board) {
var canvas = document.getElementById('board');
var table = document.createElement('table');
var tr, td;
canvas.innerHTML = "";
table.cellPadding = 0;
table.cellSpacing = 0;
for (var i = 0; i < board.matrix.length; i++) {
tr = document.createElement('tr');
for (var j = 0; j < board.matrix[0].length; j++) {
td = document.createElement('td');
td.style.width = 20;
td.style.height = 20;
if (board.matrix[i][j].isAlive) {
td.innerHTML = 1;
td.style.backgroundColor = 'black';
}
else {
td.innerHTML = 1;
td.style.backgroundColor = '#ccc';
td.style.color = '#ccc';
}
tr.appendChild(td);
}
table.appendChild(tr);
}
canvas.appendChild(table);
}
})();
})(window);
| damianfarina/GoL | app/scripts/board/board-renderer.js | JavaScript | apache-2.0 | 1,095 |
/**
* @fileOverview This test specs runs tests on the package.json file of repository. It has a set of strict tests on the
* content of the file as well. Any change to package.json must be accompanied by valid test case in this spec-sheet.
*/
var expect = require('expect.js');
/* global describe, it */
describe('repository', function () {
var fs = require('fs');
describe('package.json', function () {
var content,
json;
it('must exist', function () {
expect(fs.existsSync('./package.json')).to.be.ok();
});
it('must have readable content', function () {
expect(content = fs.readFileSync('./package.json').toString()).to.be.ok();
});
it('content must be valid JSON', function () {
expect(json = JSON.parse(content)).to.be.ok();
});
describe('package.json JSON data', function () {
it('must have valid name, description and author', function () {
expect(json.name).to.equal('env-lift');
expect(json.description)
.to.equal('Simple namespaced environment variable configuration management solution');
expect(json.author).to.equal('Postman Labs <[email protected]>');
expect(json.license).to.equal('Apache 2.0');
});
it('must have a valid version string in form of <major>.<minor>.<revision>', function () {
/* jshint ignore:start */
expect(json.version).to.match(/^((\d+)\.(\d+)\.(\d+))(?:-([\dA-Za-z\-]+(?:\.[\dA-Za-z\-]+)*))?(?:\+([\dA-Za-z\-]+(?:\.[\dA-Za-z\-]+)*))?$/);
/* jshint ignore:end */
});
});
describe('script definitions', function () {
var props = {};
it('files must exist', function () {
var prop,
propBase;
expect(json.scripts).to.be.ok();
for (prop in json.scripts) {
props[prop] = {
base: (propBase = prop.substr(0, prop.indexOf('-') > -1 ?
prop.indexOf('-') : undefined)),
path: 'scripts/' + propBase + '.sh'
};
expect(fs.existsSync(props[prop].path)).to.be.ok();
}
});
it('must be defined as per standards `[script]: scripts/[name].sh`', function () {
for (var prop in json.scripts) {
expect(json.scripts[prop]).to.match(new RegExp(props[prop].path, 'g'));
}
});
it('must have the hashbang defined', function () {
var fileContent,
prop;
for (prop in json.scripts) {
fileContent = fs.readFileSync(props[prop].path).toString();
expect(/^#!\/(bin\/bash|usr\/bin\/env\s(node|bash))[\r\n][\W\w]*$/g.test(fileContent)).to.be.ok();
}
});
});
describe('devDependencies', function () {
it('must exist', function () {
expect(json.devDependencies).to.be.a('object');
});
it('must have specified version for dependencies ', function () {
for (var item in json.devDependencies) {
expect(json.devDependencies[item]).to.be.ok();
}
});
it('must point to specific package version; (*) not expected', function () {
for (var item in json.devDependencies) {
expect(json.devDependencies[item]).not.to.equal('*');
}
});
});
describe('main entry script', function () {
it('must point to a valid file', function () {
expect(json.main).to.equal('index.js');
expect(fs.existsSync(json.main)).to.be.ok();
});
});
});
describe('README.md', function () {
it('must exist', function () {
expect(fs.existsSync('./README.md')).to.be.ok();
});
it('must have readable content', function () {
expect(fs.readFileSync('./README.md').toString()).to.be.ok();
});
});
describe('LICENSE.md', function () {
it('must exist', function () {
expect(fs.existsSync('./LICENSE.md')).to.be.ok();
});
it('must have readable content', function () {
expect(fs.readFileSync('./LICENSE.md').toString()).to.be.ok();
});
});
describe('.gitignore file', function () {
it('must exist', function () {
expect(fs.existsSync('./.gitignore')).to.be.ok();
});
it('must have readable content', function () {
expect(fs.readFileSync('./.gitignore').toString()).to.be.ok();
});
});
describe('.npmignore file', function () {
it('must exist', function () {
expect(fs.existsSync('./.npmignore')).to.be.ok();
});
it('must be a superset of .gitignore (.npmi = .npmi + .gi)', function () {
// normalise the ignore file text contents
var gi = fs.readFileSync('./.gitignore').toString().replace(/#.*\n/g, '\n').replace(/\n+/g, '\n'),
npmi = fs.readFileSync('./.npmignore').toString().replace(/#.*\n/g, '\n').replace(/\n+/g, '\n');
expect(npmi.substr(-gi.length)).to.eql(gi);
});
});
});
| postmanlabs/env-lift | tests/unit/repository-spec.js | JavaScript | apache-2.0 | 5,529 |
/*!
* jQuery JavaScript Library v2.0.3
* http://jquery.com/
*
* Includes Sizzle.js
* http://sizzlejs.com/
*
* Copyright 2005, 2013 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2013-07-03T13:30Z
*/
(function( window, undefined ) {
// Can't do this because several apps including ASP.NET trace
// the stack via arguments.caller.callee and Firefox dies if
// you try to trace through "use strict" call chains. (#13335)
// Support: Firefox 18+
//"use strict";
var
// A central reference to the root jQuery(document)
rootjQuery,
// The deferred used on DOM ready
readyList,
// Support: IE9
// For `typeof xmlNode.method` instead of `xmlNode.method !== undefined`
core_strundefined = typeof undefined,
// Use the correct document accordingly with window argument (sandbox)
location = window.location,
document = window.document,
docElem = document.documentElement,
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$,
// [[Class]] -> type pairs
class2type = {},
// List of deleted data cache ids, so we can reuse them
core_deletedIds = [],
core_version = "2.0.3",
// Save a reference to some core methods
core_concat = core_deletedIds.concat,
core_push = core_deletedIds.push,
core_slice = core_deletedIds.slice,
core_indexOf = core_deletedIds.indexOf,
core_toString = class2type.toString,
core_hasOwn = class2type.hasOwnProperty,
core_trim = core_version.trim,
// Define a local copy of jQuery
jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context, rootjQuery );
},
// Used for matching numbers
core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,
// Used for splitting on whitespace
core_rnotwhite = /\S+/g,
// A simple way to check for HTML strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
// Strict HTML recognition (#11290: must start with <)
rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,
// Match a standalone tag
rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,
// Matches dashed string for camelizing
rmsPrefix = /^-ms-/,
rdashAlpha = /-([\da-z])/gi,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function( all, letter ) {
return letter.toUpperCase();
},
// The ready event handler and self cleanup method
completed = function() {
document.removeEventListener( "DOMContentLoaded", completed, false );
window.removeEventListener( "load", completed, false );
jQuery.ready();
};
jQuery.fn = jQuery.prototype = {
// The current version of jQuery being used
jquery: core_version,
constructor: jQuery,
init: function( selector, context, rootjQuery ) {
var match, elem;
// HANDLE: $(""), $(null), $(undefined), $(false)
if ( !selector ) {
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = rquickExpr.exec( selector );
}
// Match html or make sure no context is specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] ) {
context = context instanceof jQuery ? context[0] : context;
// scripts is true for back-compat
jQuery.merge( this, jQuery.parseHTML(
match[1],
context && context.nodeType ? context.ownerDocument || context : document,
true
) );
// HANDLE: $(html, props)
if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {
for ( match in context ) {
// Properties of context are called as methods if possible
if ( jQuery.isFunction( this[ match ] ) ) {
this[ match ]( context[ match ] );
// ...and otherwise set as attributes
} else {
this.attr( match, context[ match ] );
}
}
}
return this;
// HANDLE: $(#id)
} else {
elem = document.getElementById( match[2] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return ( context || rootjQuery ).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor( context ).find( selector );
}
// HANDLE: $(DOMElement)
} else if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return rootjQuery.ready( selector );
}
if ( selector.selector !== undefined ) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
},
// Start with an empty selector
selector: "",
// The default length of a jQuery object is 0
length: 0,
toArray: function() {
return core_slice.call( this );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num == null ?
// Return a 'clean' array
this.toArray() :
// Return just the object
( num < 0 ? this[ this.length + num ] : this[ num ] );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems ) {
// Build a new jQuery matched element set
var ret = jQuery.merge( this.constructor(), elems );
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
ready: function( fn ) {
// Add the callback
jQuery.ready.promise().done( fn );
return this;
},
slice: function() {
return this.pushStack( core_slice.apply( this, arguments ) );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
eq: function( i ) {
var len = this.length,
j = +i + ( i < 0 ? len : 0 );
return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] );
},
map: function( callback ) {
return this.pushStack( jQuery.map(this, function( elem, i ) {
return callback.call( elem, i, elem );
}));
},
end: function() {
return this.prevObject || this.constructor(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: core_push,
sort: [].sort,
splice: [].splice
};
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
jQuery.extend = jQuery.fn.extend = function() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( length === i ) {
target = this;
--i;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend({
// Unique for each copy of jQuery on the page
expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ),
noConflict: function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
},
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// Handle when the DOM is ready
ready: function( wait ) {
// Abort if there are pending holds or we're already ready
if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
return;
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.trigger ) {
jQuery( document ).trigger("ready").off("ready");
}
},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
isArray: Array.isArray,
isWindow: function( obj ) {
return obj != null && obj === obj.window;
},
isNumeric: function( obj ) {
return !isNaN( parseFloat(obj) ) && isFinite( obj );
},
type: function( obj ) {
if ( obj == null ) {
return String( obj );
}
// Support: Safari <= 5.1 (functionish RegExp)
return typeof obj === "object" || typeof obj === "function" ?
class2type[ core_toString.call(obj) ] || "object" :
typeof obj;
},
isPlainObject: function( obj ) {
// Not plain objects:
// - Any object or value whose internal [[Class]] property is not "[object Object]"
// - DOM nodes
// - window
if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
// Support: Firefox <20
// The try/catch suppresses exceptions thrown when attempting to access
// the "constructor" property of certain host objects, ie. |window.location|
// https://bugzilla.mozilla.org/show_bug.cgi?id=814622
try {
if ( obj.constructor &&
!core_hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) {
return false;
}
} catch ( e ) {
return false;
}
// If the function hasn't returned already, we're confident that
// |obj| is a plain object, created by {} or constructed with new Object
return true;
},
isEmptyObject: function( obj ) {
var name;
for ( name in obj ) {
return false;
}
return true;
},
error: function( msg ) {
throw new Error( msg );
},
// data: string of html
// context (optional): If specified, the fragment will be created in this context, defaults to document
// keepScripts (optional): If true, will include scripts passed in the html string
parseHTML: function( data, context, keepScripts ) {
if ( !data || typeof data !== "string" ) {
return null;
}
if ( typeof context === "boolean" ) {
keepScripts = context;
context = false;
}
context = context || document;
var parsed = rsingleTag.exec( data ),
scripts = !keepScripts && [];
// Single tag
if ( parsed ) {
return [ context.createElement( parsed[1] ) ];
}
parsed = jQuery.buildFragment( [ data ], context, scripts );
if ( scripts ) {
jQuery( scripts ).remove();
}
return jQuery.merge( [], parsed.childNodes );
},
parseJSON: JSON.parse,
// Cross-browser xml parsing
parseXML: function( data ) {
var xml, tmp;
if ( !data || typeof data !== "string" ) {
return null;
}
// Support: IE9
try {
tmp = new DOMParser();
xml = tmp.parseFromString( data , "text/xml" );
} catch ( e ) {
xml = undefined;
}
if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
},
noop: function() {},
// Evaluates a script in a global context
globalEval: function( code ) {
var script,
indirect = eval;
code = jQuery.trim( code );
if ( code ) {
// If the code includes a valid, prologue position
// strict mode pragma, execute code by injecting a
// script tag into the document.
if ( code.indexOf("use strict") === 1 ) {
script = document.createElement("script");
script.text = code;
document.head.appendChild( script ).parentNode.removeChild( script );
} else {
// Otherwise, avoid the DOM node creation, insertion
// and removal by using an indirect global eval
indirect( code );
}
}
},
// Convert dashed to camelCase; used by the css and data modules
// Microsoft forgot to hump their vendor prefix (#9572)
camelCase: function( string ) {
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
},
// args is for internal usage only
each: function( obj, callback, args ) {
var value,
i = 0,
length = obj.length,
isArray = isArraylike( obj );
if ( args ) {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
}
}
return obj;
},
trim: function( text ) {
return text == null ? "" : core_trim.call( text );
},
// results is for internal usage only
makeArray: function( arr, results ) {
var ret = results || [];
if ( arr != null ) {
if ( isArraylike( Object(arr) ) ) {
jQuery.merge( ret,
typeof arr === "string" ?
[ arr ] : arr
);
} else {
core_push.call( ret, arr );
}
}
return ret;
},
inArray: function( elem, arr, i ) {
return arr == null ? -1 : core_indexOf.call( arr, elem, i );
},
merge: function( first, second ) {
var l = second.length,
i = first.length,
j = 0;
if ( typeof l === "number" ) {
for ( ; j < l; j++ ) {
first[ i++ ] = second[ j ];
}
} else {
while ( second[j] !== undefined ) {
first[ i++ ] = second[ j++ ];
}
}
first.length = i;
return first;
},
grep: function( elems, callback, inv ) {
var retVal,
ret = [],
i = 0,
length = elems.length;
inv = !!inv;
// Go through the array, only saving the items
// that pass the validator function
for ( ; i < length; i++ ) {
retVal = !!callback( elems[ i ], i );
if ( inv !== retVal ) {
ret.push( elems[ i ] );
}
}
return ret;
},
// arg is for internal usage only
map: function( elems, callback, arg ) {
var value,
i = 0,
length = elems.length,
isArray = isArraylike( elems ),
ret = [];
// Go through the array, translating each of the items to their
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
// Go through every key on the object,
} else {
for ( i in elems ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
}
// Flatten any nested arrays
return core_concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function( fn, context ) {
var tmp, args, proxy;
if ( typeof context === "string" ) {
tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
args = core_slice.call( arguments, 2 );
proxy = function() {
return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || jQuery.guid++;
return proxy;
},
// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
access: function( elems, fn, key, value, chainable, emptyGet, raw ) {
var i = 0,
length = elems.length,
bulk = key == null;
// Sets many values
if ( jQuery.type( key ) === "object" ) {
chainable = true;
for ( i in key ) {
jQuery.access( elems, fn, i, key[i], true, emptyGet, raw );
}
// Sets one value
} else if ( value !== undefined ) {
chainable = true;
if ( !jQuery.isFunction( value ) ) {
raw = true;
}
if ( bulk ) {
// Bulk operations run against the entire set
if ( raw ) {
fn.call( elems, value );
fn = null;
// ...except when executing function values
} else {
bulk = fn;
fn = function( elem, key, value ) {
return bulk.call( jQuery( elem ), value );
};
}
}
if ( fn ) {
for ( ; i < length; i++ ) {
fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) );
}
}
}
return chainable ?
elems :
// Gets
bulk ?
fn.call( elems ) :
length ? fn( elems[0], key ) : emptyGet;
},
now: Date.now,
// A method for quickly swapping in/out CSS properties to get correct calculations.
// Note: this method belongs to the css module but it's needed here for the support module.
// If support gets modularized, this method should be moved back to the css module.
swap: function( elem, options, callback, args ) {
var ret, name,
old = {};
// Remember the old values, and insert the new ones
for ( name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
ret = callback.apply( elem, args || [] );
// Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
}
return ret;
}
});
jQuery.ready.promise = function( obj ) {
if ( !readyList ) {
readyList = jQuery.Deferred();
// Catch cases where $(document).ready() is called after the browser event has already occurred.
// we once tried to use readyState "interactive" here, but it caused issues like the one
// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
setTimeout( jQuery.ready );
} else {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", completed, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", completed, false );
}
}
return readyList.promise( obj );
};
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
function isArraylike( obj ) {
var length = obj.length,
type = jQuery.type( obj );
if ( jQuery.isWindow( obj ) ) {
return false;
}
if ( obj.nodeType === 1 && length ) {
return true;
}
return type === "array" || type !== "function" &&
( length === 0 ||
typeof length === "number" && length > 0 && ( length - 1 ) in obj );
}
// All jQuery objects should point back to these
rootjQuery = jQuery(document);
/*!
* Sizzle CSS Selector Engine v1.9.4-pre
* http://sizzlejs.com/
*
* Copyright 2013 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2013-06-03
*/
(function( window, undefined ) {
var i,
support,
cachedruns,
Expr,
getText,
isXML,
compile,
outermostContext,
sortInput,
// Local document vars
setDocument,
document,
docElem,
documentIsHTML,
rbuggyQSA,
rbuggyMatches,
matches,
contains,
// Instance-specific data
expando = "sizzle" + -(new Date()),
preferredDoc = window.document,
dirruns = 0,
done = 0,
classCache = createCache(),
tokenCache = createCache(),
compilerCache = createCache(),
hasDuplicate = false,
sortOrder = function( a, b ) {
if ( a === b ) {
hasDuplicate = true;
return 0;
}
return 0;
},
// General-purpose constants
strundefined = typeof undefined,
MAX_NEGATIVE = 1 << 31,
// Instance methods
hasOwn = ({}).hasOwnProperty,
arr = [],
pop = arr.pop,
push_native = arr.push,
push = arr.push,
slice = arr.slice,
// Use a stripped-down indexOf if we can't use a native one
indexOf = arr.indexOf || function( elem ) {
var i = 0,
len = this.length;
for ( ; i < len; i++ ) {
if ( this[i] === elem ) {
return i;
}
}
return -1;
},
booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",
// Regular expressions
// Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace
whitespace = "[\\x20\\t\\r\\n\\f]",
// http://www.w3.org/TR/css3-syntax/#characters
characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",
// Loosely modeled on CSS identifier characters
// An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors
// Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
identifier = characterEncoding.replace( "w", "w#" ),
// Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors
attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace +
"*(?:([*^$|!~]?=)" + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]",
// Prefer arguments quoted,
// then not containing pseudos/brackets,
// then attribute selectors/non-parenthetical expressions,
// then anything else
// These preferences are here to reduce the number of selectors
// needing tokenize in the PSEUDO preFilter
pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)",
// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),
rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ),
rsibling = new RegExp( whitespace + "*[+~]" ),
rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*)" + whitespace + "*\\]", "g" ),
rpseudo = new RegExp( pseudos ),
ridentifier = new RegExp( "^" + identifier + "$" ),
matchExpr = {
"ID": new RegExp( "^#(" + characterEncoding + ")" ),
"CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ),
"TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ),
"ATTR": new RegExp( "^" + attributes ),
"PSEUDO": new RegExp( "^" + pseudos ),
"CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace +
"*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
"*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
"bool": new RegExp( "^(?:" + booleans + ")$", "i" ),
// For use in libraries implementing .is()
// We use this for POS matching in `select`
"needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" +
whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" )
},
rnative = /^[^{]+\{\s*\[native \w/,
// Easily-parseable/retrievable ID or TAG or CLASS selectors
rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
rinputs = /^(?:input|select|textarea|button)$/i,
rheader = /^h\d$/i,
rescape = /'|\\/g,
// CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ),
funescape = function( _, escaped, escapedWhitespace ) {
var high = "0x" + escaped - 0x10000;
// NaN means non-codepoint
// Support: Firefox
// Workaround erroneous numeric interpretation of +"0x"
return high !== high || escapedWhitespace ?
escaped :
// BMP codepoint
high < 0 ?
String.fromCharCode( high + 0x10000 ) :
// Supplemental Plane codepoint (surrogate pair)
String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
};
// Optimize for push.apply( _, NodeList )
try {
push.apply(
(arr = slice.call( preferredDoc.childNodes )),
preferredDoc.childNodes
);
// Support: Android<4.0
// Detect silently failing push.apply
arr[ preferredDoc.childNodes.length ].nodeType;
} catch ( e ) {
push = { apply: arr.length ?
// Leverage slice if possible
function( target, els ) {
push_native.apply( target, slice.call(els) );
} :
// Support: IE<9
// Otherwise append directly
function( target, els ) {
var j = target.length,
i = 0;
// Can't trust NodeList.length
while ( (target[j++] = els[i++]) ) {}
target.length = j - 1;
}
};
}
function Sizzle( selector, context, results, seed ) {
var match, elem, m, nodeType,
// QSA vars
i, groups, old, nid, newContext, newSelector;
if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {
setDocument( context );
}
context = context || document;
results = results || [];
if ( !selector || typeof selector !== "string" ) {
return results;
}
if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) {
return [];
}
if ( documentIsHTML && !seed ) {
// Shortcuts
if ( (match = rquickExpr.exec( selector )) ) {
// Speed-up: Sizzle("#ID")
if ( (m = match[1]) ) {
if ( nodeType === 9 ) {
elem = context.getElementById( m );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE, Opera, and Webkit return items
// by name instead of ID
if ( elem.id === m ) {
results.push( elem );
return results;
}
} else {
return results;
}
} else {
// Context is not a document
if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) &&
contains( context, elem ) && elem.id === m ) {
results.push( elem );
return results;
}
}
// Speed-up: Sizzle("TAG")
} else if ( match[2] ) {
push.apply( results, context.getElementsByTagName( selector ) );
return results;
// Speed-up: Sizzle(".CLASS")
} else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) {
push.apply( results, context.getElementsByClassName( m ) );
return results;
}
}
// QSA path
if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) {
nid = old = expando;
newContext = context;
newSelector = nodeType === 9 && selector;
// qSA works strangely on Element-rooted queries
// We can work around this by specifying an extra ID on the root
// and working up from there (Thanks to Andrew Dupont for the technique)
// IE 8 doesn't work on object elements
if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
groups = tokenize( selector );
if ( (old = context.getAttribute("id")) ) {
nid = old.replace( rescape, "\\$&" );
} else {
context.setAttribute( "id", nid );
}
nid = "[id='" + nid + "'] ";
i = groups.length;
while ( i-- ) {
groups[i] = nid + toSelector( groups[i] );
}
newContext = rsibling.test( selector ) && context.parentNode || context;
newSelector = groups.join(",");
}
if ( newSelector ) {
try {
push.apply( results,
newContext.querySelectorAll( newSelector )
);
return results;
} catch(qsaError) {
} finally {
if ( !old ) {
context.removeAttribute("id");
}
}
}
}
}
// All others
return select( selector.replace( rtrim, "$1" ), context, results, seed );
}
/**
* Create key-value caches of limited size
* @returns {Function(string, Object)} Returns the Object data after storing it on itself with
* property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
* deleting the oldest entry
*/
function createCache() {
var keys = [];
function cache( key, value ) {
// Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
if ( keys.push( key += " " ) > Expr.cacheLength ) {
// Only keep the most recent entries
delete cache[ keys.shift() ];
}
return (cache[ key ] = value);
}
return cache;
}
/**
* Mark a function for special use by Sizzle
* @param {Function} fn The function to mark
*/
function markFunction( fn ) {
fn[ expando ] = true;
return fn;
}
/**
* Support testing using an element
* @param {Function} fn Passed the created div and expects a boolean result
*/
function assert( fn ) {
var div = document.createElement("div");
try {
return !!fn( div );
} catch (e) {
return false;
} finally {
// Remove from its parent by default
if ( div.parentNode ) {
div.parentNode.removeChild( div );
}
// release memory in IE
div = null;
}
}
/**
* Adds the same handler for all of the specified attrs
* @param {String} attrs Pipe-separated list of attributes
* @param {Function} handler The method that will be applied
*/
function addHandle( attrs, handler ) {
var arr = attrs.split("|"),
i = attrs.length;
while ( i-- ) {
Expr.attrHandle[ arr[i] ] = handler;
}
}
/**
* Checks document order of two siblings
* @param {Element} a
* @param {Element} b
* @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b
*/
function siblingCheck( a, b ) {
var cur = b && a,
diff = cur && a.nodeType === 1 && b.nodeType === 1 &&
( ~b.sourceIndex || MAX_NEGATIVE ) -
( ~a.sourceIndex || MAX_NEGATIVE );
// Use IE sourceIndex if available on both nodes
if ( diff ) {
return diff;
}
// Check if b follows a
if ( cur ) {
while ( (cur = cur.nextSibling) ) {
if ( cur === b ) {
return -1;
}
}
}
return a ? 1 : -1;
}
/**
* Returns a function to use in pseudos for input types
* @param {String} type
*/
function createInputPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === type;
};
}
/**
* Returns a function to use in pseudos for buttons
* @param {String} type
*/
function createButtonPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && elem.type === type;
};
}
/**
* Returns a function to use in pseudos for positionals
* @param {Function} fn
*/
function createPositionalPseudo( fn ) {
return markFunction(function( argument ) {
argument = +argument;
return markFunction(function( seed, matches ) {
var j,
matchIndexes = fn( [], seed.length, argument ),
i = matchIndexes.length;
// Match elements found at the specified indexes
while ( i-- ) {
if ( seed[ (j = matchIndexes[i]) ] ) {
seed[j] = !(matches[j] = seed[j]);
}
}
});
});
}
/**
* Detect xml
* @param {Element|Object} elem An element or a document
*/
isXML = Sizzle.isXML = function( elem ) {
// documentElement is verified for cases where it doesn't yet exist
// (such as loading iframes in IE - #4833)
var documentElement = elem && (elem.ownerDocument || elem).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
// Expose support vars for convenience
support = Sizzle.support = {};
/**
* Sets document-related variables once based on the current document
* @param {Element|Object} [doc] An element or document object to use to set the document
* @returns {Object} Returns the current document
*/
setDocument = Sizzle.setDocument = function( node ) {
var doc = node ? node.ownerDocument || node : preferredDoc,
parent = doc.defaultView;
// If no document and documentElement is available, return
if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) {
return document;
}
// Set our document
document = doc;
docElem = doc.documentElement;
// Support at.tugraz.kti.pdftable.tests
documentIsHTML = !isXML( doc );
// Support: IE>8
// If iframe document is assigned to "document" variable and if iframe has been reloaded,
// IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936
// IE6-8 do not support the defaultView property so parent will be undefined
if ( parent && parent.attachEvent && parent !== parent.top ) {
parent.attachEvent( "onbeforeunload", function() {
setDocument();
});
}
/* Attributes
---------------------------------------------------------------------- */
// Support: IE<8
// Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans)
support.attributes = assert(function( div ) {
div.className = "i";
return !div.getAttribute("className");
});
/* getElement(s)By*
---------------------------------------------------------------------- */
// Check if getElementsByTagName("*") returns only elements
support.getElementsByTagName = assert(function( div ) {
div.appendChild( doc.createComment("") );
return !div.getElementsByTagName("*").length;
});
// Check if getElementsByClassName can be trusted
support.getElementsByClassName = assert(function( div ) {
div.innerHTML = "<div class='a'></div><div class='a i'></div>";
// Support: Safari<4
// Catch class over-caching
div.firstChild.className = "i";
// Support: Opera<10
// Catch gEBCN failure to find non-leading classes
return div.getElementsByClassName("i").length === 2;
});
// Support: IE<10
// Check if getElementById returns elements by name
// The broken getElementById methods don't pick up programatically-set names,
// so use a roundabout getElementsByName test
support.getById = assert(function( div ) {
docElem.appendChild( div ).id = expando;
return !doc.getElementsByName || !doc.getElementsByName( expando ).length;
});
// ID find and filter
if ( support.getById ) {
Expr.find["ID"] = function( id, context ) {
if ( typeof context.getElementById !== strundefined && documentIsHTML ) {
var m = context.getElementById( id );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m && m.parentNode ? [m] : [];
}
};
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
return elem.getAttribute("id") === attrId;
};
};
} else {
// Support: IE6/7
// getElementById is not reliable as a find shortcut
delete Expr.find["ID"];
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id");
return node && node.value === attrId;
};
};
}
// Tag
Expr.find["TAG"] = support.getElementsByTagName ?
function( tag, context ) {
if ( typeof context.getElementsByTagName !== strundefined ) {
return context.getElementsByTagName( tag );
}
} :
function( tag, context ) {
var elem,
tmp = [],
i = 0,
results = context.getElementsByTagName( tag );
// Filter out possible comments
if ( tag === "*" ) {
while ( (elem = results[i++]) ) {
if ( elem.nodeType === 1 ) {
tmp.push( elem );
}
}
return tmp;
}
return results;
};
// Class
Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) {
if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) {
return context.getElementsByClassName( className );
}
};
/* QSA/matchesSelector
---------------------------------------------------------------------- */
// QSA and matchesSelector support
// matchesSelector(:active) reports false when true (IE9/Opera 11.5)
rbuggyMatches = [];
// qSa(:focus) reports false when true (Chrome 21)
// We allow this because of a bug in IE8/9 that throws an error
// whenever `document.activeElement` is accessed on an iframe
// So, we allow :focus to pass through QSA all the time to avoid the IE error
// See http://bugs.jquery.com/ticket/13378
rbuggyQSA = [];
if ( (support.qsa = rnative.test( doc.querySelectorAll )) ) {
// Build QSA regex
// Regex strategy adopted from Diego Perini
assert(function( div ) {
// Select is set to empty string on purpose
// This is to test IE's treatment of not explicitly
// setting a boolean content attribute,
// since its presence should be enough
// http://bugs.jquery.com/ticket/12359
div.innerHTML = "<select><option selected=''></option></select>";
// Support: IE8
// Boolean attributes and "value" are not treated correctly
if ( !div.querySelectorAll("[selected]").length ) {
rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" );
}
// Webkit/Opera - :checked should return selected option elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
// IE8 throws error here and will not see later at.tugraz.kti.pdftable.tests
if ( !div.querySelectorAll(":checked").length ) {
rbuggyQSA.push(":checked");
}
});
assert(function( div ) {
// Support: Opera 10-12/IE8
// ^= $= *= and empty values
// Should not select anything
// Support: Windows 8 Native Apps
// The type attribute is restricted during .innerHTML assignment
var input = doc.createElement("input");
input.setAttribute( "type", "hidden" );
div.appendChild( input ).setAttribute( "t", "" );
if ( div.querySelectorAll("[t^='']").length ) {
rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" );
}
// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
// IE8 throws error here and will not see later at.tugraz.kti.pdftable.tests
if ( !div.querySelectorAll(":enabled").length ) {
rbuggyQSA.push( ":enabled", ":disabled" );
}
// Opera 10-11 does not throw on post-comma invalid pseudos
div.querySelectorAll("*,:x");
rbuggyQSA.push(",.*:");
});
}
if ( (support.matchesSelector = rnative.test( (matches = docElem.webkitMatchesSelector ||
docElem.mozMatchesSelector ||
docElem.oMatchesSelector ||
docElem.msMatchesSelector) )) ) {
assert(function( div ) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9)
support.disconnectedMatch = matches.call( div, "div" );
// This should fail with an exception
// Gecko does not error, returns false instead
matches.call( div, "[s!='']:x" );
rbuggyMatches.push( "!=", pseudos );
});
}
rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") );
rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") );
/* Contains
---------------------------------------------------------------------- */
// Element contains another
// Purposefully does not implement inclusive descendent
// As in, an element does not contain itself
contains = rnative.test( docElem.contains ) || docElem.compareDocumentPosition ?
function( a, b ) {
var adown = a.nodeType === 9 ? a.documentElement : a,
bup = b && b.parentNode;
return a === bup || !!( bup && bup.nodeType === 1 && (
adown.contains ?
adown.contains( bup ) :
a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
));
} :
function( a, b ) {
if ( b ) {
while ( (b = b.parentNode) ) {
if ( b === a ) {
return true;
}
}
}
return false;
};
/* Sorting
---------------------------------------------------------------------- */
// Document order sorting
sortOrder = docElem.compareDocumentPosition ?
function( a, b ) {
// Flag for duplicate removal
if ( a === b ) {
hasDuplicate = true;
return 0;
}
var compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b );
if ( compare ) {
// Disconnected nodes
if ( compare & 1 ||
(!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) {
// Choose the first element that is related to our preferred document
if ( a === doc || contains(preferredDoc, a) ) {
return -1;
}
if ( b === doc || contains(preferredDoc, b) ) {
return 1;
}
// Maintain original order
return sortInput ?
( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) :
0;
}
return compare & 4 ? -1 : 1;
}
// Not directly comparable, sort on existence of method
return a.compareDocumentPosition ? -1 : 1;
} :
function( a, b ) {
var cur,
i = 0,
aup = a.parentNode,
bup = b.parentNode,
ap = [ a ],
bp = [ b ];
// Exit early if the nodes are identical
if ( a === b ) {
hasDuplicate = true;
return 0;
// Parentless nodes are either documents or disconnected
} else if ( !aup || !bup ) {
return a === doc ? -1 :
b === doc ? 1 :
aup ? -1 :
bup ? 1 :
sortInput ?
( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) :
0;
// If the nodes are siblings, we can do a quick check
} else if ( aup === bup ) {
return siblingCheck( a, b );
}
// Otherwise we need full lists of their ancestors for comparison
cur = a;
while ( (cur = cur.parentNode) ) {
ap.unshift( cur );
}
cur = b;
while ( (cur = cur.parentNode) ) {
bp.unshift( cur );
}
// Walk down the tree looking for a discrepancy
while ( ap[i] === bp[i] ) {
i++;
}
return i ?
// Do a sibling check if the nodes have a common ancestor
siblingCheck( ap[i], bp[i] ) :
// Otherwise nodes in our document sort first
ap[i] === preferredDoc ? -1 :
bp[i] === preferredDoc ? 1 :
0;
};
return doc;
};
Sizzle.matches = function( expr, elements ) {
return Sizzle( expr, null, null, elements );
};
Sizzle.matchesSelector = function( elem, expr ) {
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
// Make sure that attribute selectors are quoted
expr = expr.replace( rattributeQuotes, "='$1']" );
if ( support.matchesSelector && documentIsHTML &&
( !rbuggyMatches || !rbuggyMatches.test( expr ) ) &&
( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) {
try {
var ret = matches.call( elem, expr );
// IE 9's matchesSelector returns false on disconnected nodes
if ( ret || support.disconnectedMatch ||
// As well, disconnected nodes are said to be in a document
// fragment in IE 9
elem.document && elem.document.nodeType !== 11 ) {
return ret;
}
} catch(e) {}
}
return Sizzle( expr, document, null, [elem] ).length > 0;
};
Sizzle.contains = function( context, elem ) {
// Set document vars if needed
if ( ( context.ownerDocument || context ) !== document ) {
setDocument( context );
}
return contains( context, elem );
};
Sizzle.attr = function( elem, name ) {
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
var fn = Expr.attrHandle[ name.toLowerCase() ],
// Don't get fooled by Object.prototype properties (jQuery #13807)
val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ?
fn( elem, name, !documentIsHTML ) :
undefined;
return val === undefined ?
support.attributes || !documentIsHTML ?
elem.getAttribute( name ) :
(val = elem.getAttributeNode(name)) && val.specified ?
val.value :
null :
val;
};
Sizzle.error = function( msg ) {
throw new Error( "Syntax error, unrecognized expression: " + msg );
};
/**
* Document sorting and removing duplicates
* @param {ArrayLike} results
*/
Sizzle.uniqueSort = function( results ) {
var elem,
duplicates = [],
j = 0,
i = 0;
// Unless we *know* we can detect duplicates, assume their presence
hasDuplicate = !support.detectDuplicates;
sortInput = !support.sortStable && results.slice( 0 );
results.sort( sortOrder );
if ( hasDuplicate ) {
while ( (elem = results[i++]) ) {
if ( elem === results[ i ] ) {
j = duplicates.push( i );
}
}
while ( j-- ) {
results.splice( duplicates[ j ], 1 );
}
}
return results;
};
/**
* Utility function for retrieving the text value of an array of DOM nodes
* @param {Array|Element} elem
*/
getText = Sizzle.getText = function( elem ) {
var node,
ret = "",
i = 0,
nodeType = elem.nodeType;
if ( !nodeType ) {
// If no nodeType, this is expected to be an array
for ( ; (node = elem[i]); i++ ) {
// Do not traverse comment nodes
ret += getText( node );
}
} else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
// Use textContent for elements
// innerText usage removed for consistency of new lines (see #11153)
if ( typeof elem.textContent === "string" ) {
return elem.textContent;
} else {
// Traverse its children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
ret += getText( elem );
}
}
} else if ( nodeType === 3 || nodeType === 4 ) {
return elem.nodeValue;
}
// Do not include comment or processing instruction nodes
return ret;
};
Expr = Sizzle.selectors = {
// Can be adjusted by the user
cacheLength: 50,
createPseudo: markFunction,
match: matchExpr,
attrHandle: {},
find: {},
relative: {
">": { dir: "parentNode", first: true },
" ": { dir: "parentNode" },
"+": { dir: "previousSibling", first: true },
"~": { dir: "previousSibling" }
},
preFilter: {
"ATTR": function( match ) {
match[1] = match[1].replace( runescape, funescape );
// Move the given value to match[3] whether quoted or unquoted
match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape );
if ( match[2] === "~=" ) {
match[3] = " " + match[3] + " ";
}
return match.slice( 0, 4 );
},
"CHILD": function( match ) {
/* matches from matchExpr["CHILD"]
1 type (only|nth|...)
2 what (child|of-type)
3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
4 xn-component of xn+y argument ([+-]?\d*n|)
5 sign of xn-component
6 x of xn-component
7 sign of y-component
8 y of y-component
*/
match[1] = match[1].toLowerCase();
if ( match[1].slice( 0, 3 ) === "nth" ) {
// nth-* requires argument
if ( !match[3] ) {
Sizzle.error( match[0] );
}
// numeric x and y parameters for Expr.filter.CHILD
// remember that false/true cast respectively to 0/1
match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) );
match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" );
// other types prohibit arguments
} else if ( match[3] ) {
Sizzle.error( match[0] );
}
return match;
},
"PSEUDO": function( match ) {
var excess,
unquoted = !match[5] && match[2];
if ( matchExpr["CHILD"].test( match[0] ) ) {
return null;
}
// Accept quoted arguments as-is
if ( match[3] && match[4] !== undefined ) {
match[2] = match[4];
// Strip excess characters from unquoted arguments
} else if ( unquoted && rpseudo.test( unquoted ) &&
// Get excess from tokenize (recursively)
(excess = tokenize( unquoted, true )) &&
// advance to the next closing parenthesis
(excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {
// excess is a negative index
match[0] = match[0].slice( 0, excess );
match[2] = unquoted.slice( 0, excess );
}
// Return only captures needed by the pseudo filter method (type and argument)
return match.slice( 0, 3 );
}
},
filter: {
"TAG": function( nodeNameSelector ) {
var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase();
return nodeNameSelector === "*" ?
function() { return true; } :
function( elem ) {
return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
};
},
"CLASS": function( className ) {
var pattern = classCache[ className + " " ];
return pattern ||
(pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&
classCache( className, function( elem ) {
return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute("class") || "" );
});
},
"ATTR": function( name, operator, check ) {
return function( elem ) {
var result = Sizzle.attr( elem, name );
if ( result == null ) {
return operator === "!=";
}
if ( !operator ) {
return true;
}
result += "";
return operator === "=" ? result === check :
operator === "!=" ? result !== check :
operator === "^=" ? check && result.indexOf( check ) === 0 :
operator === "*=" ? check && result.indexOf( check ) > -1 :
operator === "$=" ? check && result.slice( -check.length ) === check :
operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 :
operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" :
false;
};
},
"CHILD": function( type, what, argument, first, last ) {
var simple = type.slice( 0, 3 ) !== "nth",
forward = type.slice( -4 ) !== "last",
ofType = what === "of-type";
return first === 1 && last === 0 ?
// Shortcut for :nth-*(n)
function( elem ) {
return !!elem.parentNode;
} :
function( elem, context, xml ) {
var cache, outerCache, node, diff, nodeIndex, start,
dir = simple !== forward ? "nextSibling" : "previousSibling",
parent = elem.parentNode,
name = ofType && elem.nodeName.toLowerCase(),
useCache = !xml && !ofType;
if ( parent ) {
// :(first|last|only)-(child|of-type)
if ( simple ) {
while ( dir ) {
node = elem;
while ( (node = node[ dir ]) ) {
if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) {
return false;
}
}
// Reverse direction for :only-* (if we haven't yet done so)
start = dir = type === "only" && !start && "nextSibling";
}
return true;
}
start = [ forward ? parent.firstChild : parent.lastChild ];
// non-xml :nth-child(...) stores cache data on `parent`
if ( forward && useCache ) {
// Seek `elem` from a previously-cached index
outerCache = parent[ expando ] || (parent[ expando ] = {});
cache = outerCache[ type ] || [];
nodeIndex = cache[0] === dirruns && cache[1];
diff = cache[0] === dirruns && cache[2];
node = nodeIndex && parent.childNodes[ nodeIndex ];
while ( (node = ++nodeIndex && node && node[ dir ] ||
// Fallback to seeking `elem` from the start
(diff = nodeIndex = 0) || start.pop()) ) {
// When found, cache indexes on `parent` and break
if ( node.nodeType === 1 && ++diff && node === elem ) {
outerCache[ type ] = [ dirruns, nodeIndex, diff ];
break;
}
}
// Use previously-cached element index if available
} else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) {
diff = cache[1];
// xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...)
} else {
// Use the same loop as above to seek `elem` from the start
while ( (node = ++nodeIndex && node && node[ dir ] ||
(diff = nodeIndex = 0) || start.pop()) ) {
if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) {
// Cache the index of each encountered element
if ( useCache ) {
(node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ];
}
if ( node === elem ) {
break;
}
}
}
}
// Incorporate the offset, then check against cycle size
diff -= last;
return diff === first || ( diff % first === 0 && diff / first >= 0 );
}
};
},
"PSEUDO": function( pseudo, argument ) {
// pseudo-class names are case-insensitive
// http://www.w3.org/TR/selectors/#pseudo-classes
// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
// Remember that setFilters inherits from pseudos
var args,
fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
Sizzle.error( "unsupported pseudo: " + pseudo );
// The user may use createPseudo to indicate that
// arguments are needed to create the filter function
// just as Sizzle does
if ( fn[ expando ] ) {
return fn( argument );
}
// But maintain support for old signatures
if ( fn.length > 1 ) {
args = [ pseudo, pseudo, "", argument ];
return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
markFunction(function( seed, matches ) {
var idx,
matched = fn( seed, argument ),
i = matched.length;
while ( i-- ) {
idx = indexOf.call( seed, matched[i] );
seed[ idx ] = !( matches[ idx ] = matched[i] );
}
}) :
function( elem ) {
return fn( elem, 0, args );
};
}
return fn;
}
},
pseudos: {
// Potentially complex pseudos
"not": markFunction(function( selector ) {
// Trim the selector passed to compile
// to avoid treating leading and trailing
// spaces as combinators
var input = [],
results = [],
matcher = compile( selector.replace( rtrim, "$1" ) );
return matcher[ expando ] ?
markFunction(function( seed, matches, context, xml ) {
var elem,
unmatched = matcher( seed, null, xml, [] ),
i = seed.length;
// Match elements unmatched by `matcher`
while ( i-- ) {
if ( (elem = unmatched[i]) ) {
seed[i] = !(matches[i] = elem);
}
}
}) :
function( elem, context, xml ) {
input[0] = elem;
matcher( input, null, xml, results );
return !results.pop();
};
}),
"has": markFunction(function( selector ) {
return function( elem ) {
return Sizzle( selector, elem ).length > 0;
};
}),
"contains": markFunction(function( text ) {
return function( elem ) {
return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
};
}),
// "Whether an element is represented by a :lang() selector
// is based solely on the element's language value
// being equal to the identifier C,
// or beginning with the identifier C immediately followed by "-".
// The matching of C against the element's language value is performed case-insensitively.
// The identifier C does not have to be a valid language name."
// http://www.w3.org/TR/selectors/#lang-pseudo
"lang": markFunction( function( lang ) {
// lang value must be a valid identifier
if ( !ridentifier.test(lang || "") ) {
Sizzle.error( "unsupported lang: " + lang );
}
lang = lang.replace( runescape, funescape ).toLowerCase();
return function( elem ) {
var elemLang;
do {
if ( (elemLang = documentIsHTML ?
elem.lang :
elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) {
elemLang = elemLang.toLowerCase();
return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0;
}
} while ( (elem = elem.parentNode) && elem.nodeType === 1 );
return false;
};
}),
// Miscellaneous
"target": function( elem ) {
var hash = window.location && window.location.hash;
return hash && hash.slice( 1 ) === elem.id;
},
"root": function( elem ) {
return elem === docElem;
},
"focus": function( elem ) {
return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
},
// Boolean properties
"enabled": function( elem ) {
return elem.disabled === false;
},
"disabled": function( elem ) {
return elem.disabled === true;
},
"checked": function( elem ) {
// In CSS3, :checked should return both checked and selected elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
var nodeName = elem.nodeName.toLowerCase();
return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
},
"selected": function( elem ) {
// Accessing this property makes selected-by-default
// options in Safari work properly
if ( elem.parentNode ) {
elem.parentNode.selectedIndex;
}
return elem.selected === true;
},
// Contents
"empty": function( elem ) {
// http://www.w3.org/TR/selectors/#empty-pseudo
// :empty is only affected by element nodes and content nodes(including text(3), cdata(4)),
// not comment, processing instructions, or others
// Thanks to Diego Perini for the nodeName shortcut
// Greater than "@" means alpha characters (specifically not starting with "#" or "?")
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) {
return false;
}
}
return true;
},
"parent": function( elem ) {
return !Expr.pseudos["empty"]( elem );
},
// Element/input types
"header": function( elem ) {
return rheader.test( elem.nodeName );
},
"input": function( elem ) {
return rinputs.test( elem.nodeName );
},
"button": function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === "button" || name === "button";
},
"text": function( elem ) {
var attr;
// IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc)
// use getAttribute instead to test this case
return elem.nodeName.toLowerCase() === "input" &&
elem.type === "text" &&
( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type );
},
// Position-in-collection
"first": createPositionalPseudo(function() {
return [ 0 ];
}),
"last": createPositionalPseudo(function( matchIndexes, length ) {
return [ length - 1 ];
}),
"eq": createPositionalPseudo(function( matchIndexes, length, argument ) {
return [ argument < 0 ? argument + length : argument ];
}),
"even": createPositionalPseudo(function( matchIndexes, length ) {
var i = 0;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"odd": createPositionalPseudo(function( matchIndexes, length ) {
var i = 1;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"lt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; --i >= 0; ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"gt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; ++i < length; ) {
matchIndexes.push( i );
}
return matchIndexes;
})
}
};
Expr.pseudos["nth"] = Expr.pseudos["eq"];
// Add button/input type pseudos
for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) {
Expr.pseudos[ i ] = createInputPseudo( i );
}
for ( i in { submit: true, reset: true } ) {
Expr.pseudos[ i ] = createButtonPseudo( i );
}
// Easy API for creating new setFilters
function setFilters() {}
setFilters.prototype = Expr.filters = Expr.pseudos;
Expr.setFilters = new setFilters();
function tokenize( selector, parseOnly ) {
var matched, match, tokens, type,
soFar, groups, preFilters,
cached = tokenCache[ selector + " " ];
if ( cached ) {
return parseOnly ? 0 : cached.slice( 0 );
}
soFar = selector;
groups = [];
preFilters = Expr.preFilter;
while ( soFar ) {
// Comma and first run
if ( !matched || (match = rcomma.exec( soFar )) ) {
if ( match ) {
// Don't consume trailing commas as valid
soFar = soFar.slice( match[0].length ) || soFar;
}
groups.push( tokens = [] );
}
matched = false;
// Combinators
if ( (match = rcombinators.exec( soFar )) ) {
matched = match.shift();
tokens.push({
value: matched,
// Cast descendant combinators to space
type: match[0].replace( rtrim, " " )
});
soFar = soFar.slice( matched.length );
}
// Filters
for ( type in Expr.filter ) {
if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
(match = preFilters[ type ]( match ))) ) {
matched = match.shift();
tokens.push({
value: matched,
type: type,
matches: match
});
soFar = soFar.slice( matched.length );
}
}
if ( !matched ) {
break;
}
}
// Return the length of the invalid excess
// if we're just parsing
// Otherwise, throw an error or return tokens
return parseOnly ?
soFar.length :
soFar ?
Sizzle.error( selector ) :
// Cache the tokens
tokenCache( selector, groups ).slice( 0 );
}
function toSelector( tokens ) {
var i = 0,
len = tokens.length,
selector = "";
for ( ; i < len; i++ ) {
selector += tokens[i].value;
}
return selector;
}
function addCombinator( matcher, combinator, base ) {
var dir = combinator.dir,
checkNonElements = base && dir === "parentNode",
doneName = done++;
return combinator.first ?
// Check against closest ancestor/preceding element
function( elem, context, xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
return matcher( elem, context, xml );
}
}
} :
// Check against all ancestor/preceding elements
function( elem, context, xml ) {
var data, cache, outerCache,
dirkey = dirruns + " " + doneName;
// We can't set arbitrary data on XML nodes, so they don't benefit from dir caching
if ( xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
if ( matcher( elem, context, xml ) ) {
return true;
}
}
}
} else {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
outerCache = elem[ expando ] || (elem[ expando ] = {});
if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) {
if ( (data = cache[1]) === true || data === cachedruns ) {
return data === true;
}
} else {
cache = outerCache[ dir ] = [ dirkey ];
cache[1] = matcher( elem, context, xml ) || cachedruns;
if ( cache[1] === true ) {
return true;
}
}
}
}
}
};
}
function elementMatcher( matchers ) {
return matchers.length > 1 ?
function( elem, context, xml ) {
var i = matchers.length;
while ( i-- ) {
if ( !matchers[i]( elem, context, xml ) ) {
return false;
}
}
return true;
} :
matchers[0];
}
function condense( unmatched, map, filter, context, xml ) {
var elem,
newUnmatched = [],
i = 0,
len = unmatched.length,
mapped = map != null;
for ( ; i < len; i++ ) {
if ( (elem = unmatched[i]) ) {
if ( !filter || filter( elem, context, xml ) ) {
newUnmatched.push( elem );
if ( mapped ) {
map.push( i );
}
}
}
}
return newUnmatched;
}
function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
if ( postFilter && !postFilter[ expando ] ) {
postFilter = setMatcher( postFilter );
}
if ( postFinder && !postFinder[ expando ] ) {
postFinder = setMatcher( postFinder, postSelector );
}
return markFunction(function( seed, results, context, xml ) {
var temp, i, elem,
preMap = [],
postMap = [],
preexisting = results.length,
// Get initial elements from seed or context
elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),
// Prefilter to get matcher input, preserving a map for seed-results synchronization
matcherIn = preFilter && ( seed || !selector ) ?
condense( elems, preMap, preFilter, context, xml ) :
elems,
matcherOut = matcher ?
// If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
// ...intermediate processing is necessary
[] :
// ...otherwise use results directly
results :
matcherIn;
// Find primary matches
if ( matcher ) {
matcher( matcherIn, matcherOut, context, xml );
}
// Apply postFilter
if ( postFilter ) {
temp = condense( matcherOut, postMap );
postFilter( temp, [], context, xml );
// Un-match failing elements by moving them back to matcherIn
i = temp.length;
while ( i-- ) {
if ( (elem = temp[i]) ) {
matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
}
}
}
if ( seed ) {
if ( postFinder || preFilter ) {
if ( postFinder ) {
// Get the final matcherOut by condensing this intermediate into postFinder contexts
temp = [];
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) ) {
// Restore matcherIn since elem is not yet a final match
temp.push( (matcherIn[i] = elem) );
}
}
postFinder( null, (matcherOut = []), temp, xml );
}
// Move matched elements from seed to results to keep them synchronized
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) &&
(temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) {
seed[temp] = !(results[temp] = elem);
}
}
}
// Add elements to results, through postFinder if defined
} else {
matcherOut = condense(
matcherOut === results ?
matcherOut.splice( preexisting, matcherOut.length ) :
matcherOut
);
if ( postFinder ) {
postFinder( null, results, matcherOut, xml );
} else {
push.apply( results, matcherOut );
}
}
});
}
function matcherFromTokens( tokens ) {
var checkContext, matcher, j,
len = tokens.length,
leadingRelative = Expr.relative[ tokens[0].type ],
implicitRelative = leadingRelative || Expr.relative[" "],
i = leadingRelative ? 1 : 0,
// The foundational matcher ensures that elements are reachable from top-level context(s)
matchContext = addCombinator( function( elem ) {
return elem === checkContext;
}, implicitRelative, true ),
matchAnyContext = addCombinator( function( elem ) {
return indexOf.call( checkContext, elem ) > -1;
}, implicitRelative, true ),
matchers = [ function( elem, context, xml ) {
return ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
(checkContext = context).nodeType ?
matchContext( elem, context, xml ) :
matchAnyContext( elem, context, xml ) );
} ];
for ( ; i < len; i++ ) {
if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
matchers = [ addCombinator(elementMatcher( matchers ), matcher) ];
} else {
matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );
// Return special upon seeing a positional matcher
if ( matcher[ expando ] ) {
// Find the next relative operator (if any) for proper handling
j = ++i;
for ( ; j < len; j++ ) {
if ( Expr.relative[ tokens[j].type ] ) {
break;
}
}
return setMatcher(
i > 1 && elementMatcher( matchers ),
i > 1 && toSelector(
// If the preceding token was a descendant combinator, insert an implicit any-element `*`
tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" })
).replace( rtrim, "$1" ),
matcher,
i < j && matcherFromTokens( tokens.slice( i, j ) ),
j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
j < len && toSelector( tokens )
);
}
matchers.push( matcher );
}
}
return elementMatcher( matchers );
}
function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
// A counter to specify which element is currently being matched
var matcherCachedRuns = 0,
bySet = setMatchers.length > 0,
byElement = elementMatchers.length > 0,
superMatcher = function( seed, context, xml, results, expandContext ) {
var elem, j, matcher,
setMatched = [],
matchedCount = 0,
i = "0",
unmatched = seed && [],
outermost = expandContext != null,
contextBackup = outermostContext,
// We must always have either seed elements or context
elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ),
// Use integer dirruns iff this is the outermost matcher
dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1);
if ( outermost ) {
outermostContext = context !== document && context;
cachedruns = matcherCachedRuns;
}
// Add elements passing elementMatchers directly to results
// Keep `i` a string if there are no elements so `matchedCount` will be "00" below
for ( ; (elem = elems[i]) != null; i++ ) {
if ( byElement && elem ) {
j = 0;
while ( (matcher = elementMatchers[j++]) ) {
if ( matcher( elem, context, xml ) ) {
results.push( elem );
break;
}
}
if ( outermost ) {
dirruns = dirrunsUnique;
cachedruns = ++matcherCachedRuns;
}
}
// Track unmatched elements for set filters
if ( bySet ) {
// They will have gone through all possible matchers
if ( (elem = !matcher && elem) ) {
matchedCount--;
}
// Lengthen the array for every element, matched or not
if ( seed ) {
unmatched.push( elem );
}
}
}
// Apply set filters to unmatched elements
matchedCount += i;
if ( bySet && i !== matchedCount ) {
j = 0;
while ( (matcher = setMatchers[j++]) ) {
matcher( unmatched, setMatched, context, xml );
}
if ( seed ) {
// Reintegrate element matches to eliminate the need for sorting
if ( matchedCount > 0 ) {
while ( i-- ) {
if ( !(unmatched[i] || setMatched[i]) ) {
setMatched[i] = pop.call( results );
}
}
}
// Discard index placeholder values to get only actual matches
setMatched = condense( setMatched );
}
// Add matches to results
push.apply( results, setMatched );
// Seedless set matches succeeding multiple successful matchers stipulate sorting
if ( outermost && !seed && setMatched.length > 0 &&
( matchedCount + setMatchers.length ) > 1 ) {
Sizzle.uniqueSort( results );
}
}
// Override manipulation of globals by nested matchers
if ( outermost ) {
dirruns = dirrunsUnique;
outermostContext = contextBackup;
}
return unmatched;
};
return bySet ?
markFunction( superMatcher ) :
superMatcher;
}
compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) {
var i,
setMatchers = [],
elementMatchers = [],
cached = compilerCache[ selector + " " ];
if ( !cached ) {
// Generate a function of recursive functions that can be used to check each element
if ( !group ) {
group = tokenize( selector );
}
i = group.length;
while ( i-- ) {
cached = matcherFromTokens( group[i] );
if ( cached[ expando ] ) {
setMatchers.push( cached );
} else {
elementMatchers.push( cached );
}
}
// Cache the compiled function
cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
}
return cached;
};
function multipleContexts( selector, contexts, results ) {
var i = 0,
len = contexts.length;
for ( ; i < len; i++ ) {
Sizzle( selector, contexts[i], results );
}
return results;
}
function select( selector, context, results, seed ) {
var i, tokens, token, type, find,
match = tokenize( selector );
if ( !seed ) {
// Try to minimize operations if there is only one group
if ( match.length === 1 ) {
// Take a shortcut and set the context if the root selector is an ID
tokens = match[0] = match[0].slice( 0 );
if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
support.getById && context.nodeType === 9 && documentIsHTML &&
Expr.relative[ tokens[1].type ] ) {
context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0];
if ( !context ) {
return results;
}
selector = selector.slice( tokens.shift().value.length );
}
// Fetch a seed set for right-to-left matching
i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length;
while ( i-- ) {
token = tokens[i];
// Abort if we hit a combinator
if ( Expr.relative[ (type = token.type) ] ) {
break;
}
if ( (find = Expr.find[ type ]) ) {
// Search, expanding context for leading sibling combinators
if ( (seed = find(
token.matches[0].replace( runescape, funescape ),
rsibling.test( tokens[0].type ) && context.parentNode || context
)) ) {
// If seed is empty or no tokens remain, we can return early
tokens.splice( i, 1 );
selector = seed.length && toSelector( tokens );
if ( !selector ) {
push.apply( results, seed );
return results;
}
break;
}
}
}
}
}
// Compile and execute a filtering function
// Provide `match` to avoid retokenization if we modified the selector above
compile( selector, match )(
seed,
context,
!documentIsHTML,
results,
rsibling.test( selector )
);
return results;
}
// One-time assignments
// Sort stability
support.sortStable = expando.split("").sort( sortOrder ).join("") === expando;
// Support: Chrome<14
// Always assume duplicates if they aren't passed to the comparison function
support.detectDuplicates = hasDuplicate;
// Initialize against the default document
setDocument();
// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27)
// Detached nodes confoundingly follow *each other*
support.sortDetached = assert(function( div1 ) {
// Should return 1, but returns 4 (following)
return div1.compareDocumentPosition( document.createElement("div") ) & 1;
});
// Support: IE<8
// Prevent attribute/property "interpolation"
// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
if ( !assert(function( div ) {
div.innerHTML = "<a href='#'></a>";
return div.firstChild.getAttribute("href") === "#" ;
}) ) {
addHandle( "type|href|height|width", function( elem, name, isXML ) {
if ( !isXML ) {
return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 );
}
});
}
// Support: IE<9
// Use defaultValue in place of getAttribute("value")
if ( !support.attributes || !assert(function( div ) {
div.innerHTML = "<input/>";
div.firstChild.setAttribute( "value", "" );
return div.firstChild.getAttribute( "value" ) === "";
}) ) {
addHandle( "value", function( elem, name, isXML ) {
if ( !isXML && elem.nodeName.toLowerCase() === "input" ) {
return elem.defaultValue;
}
});
}
// Support: IE<9
// Use getAttributeNode to fetch booleans when getAttribute lies
if ( !assert(function( div ) {
return div.getAttribute("disabled") == null;
}) ) {
addHandle( booleans, function( elem, name, isXML ) {
var val;
if ( !isXML ) {
return (val = elem.getAttributeNode( name )) && val.specified ?
val.value :
elem[ name ] === true ? name.toLowerCase() : null;
}
});
}
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.pseudos;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
})( window );
// String to Object options format cache
var optionsCache = {};
// Convert String-formatted options into Object-formatted ones and store in cache
function createOptions( options ) {
var object = optionsCache[ options ] = {};
jQuery.each( options.match( core_rnotwhite ) || [], function( _, flag ) {
object[ flag ] = true;
});
return object;
}
/*
* Create a callback list using the following parameters:
*
* options: an optional list of space-separated options that will change how
* the callback list behaves or a more traditional option object
*
* By default a callback list will act like an event callback list and can be
* "fired" multiple times.
*
* Possible options:
*
* once: will ensure the callback list can only be fired once (like a Deferred)
*
* memory: will keep track of previous values and will call any callback added
* after the list has been fired right away with the latest "memorized"
* values (like a Deferred)
*
* unique: will ensure a callback can only be added once (no duplicate in the list)
*
* stopOnFalse: interrupt callings when a callback returns false
*
*/
jQuery.Callbacks = function( options ) {
// Convert options from String-formatted to Object-formatted if needed
// (we check in cache first)
options = typeof options === "string" ?
( optionsCache[ options ] || createOptions( options ) ) :
jQuery.extend( {}, options );
var // Last fire value (for non-forgettable lists)
memory,
// Flag to know if list was already fired
fired,
// Flag to know if list is currently firing
firing,
// First callback to fire (used internally by add and fireWith)
firingStart,
// End of the loop when firing
firingLength,
// Index of currently firing callback (modified by remove if needed)
firingIndex,
// Actual callback list
list = [],
// Stack of fire calls for repeatable lists
stack = !options.once && [],
// Fire callbacks
fire = function( data ) {
memory = options.memory && data;
fired = true;
firingIndex = firingStart || 0;
firingStart = 0;
firingLength = list.length;
firing = true;
for ( ; list && firingIndex < firingLength; firingIndex++ ) {
if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) {
memory = false; // To prevent further calls using add
break;
}
}
firing = false;
if ( list ) {
if ( stack ) {
if ( stack.length ) {
fire( stack.shift() );
}
} else if ( memory ) {
list = [];
} else {
self.disable();
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function() {
if ( list ) {
// First, we save the current length
var start = list.length;
(function add( args ) {
jQuery.each( args, function( _, arg ) {
var type = jQuery.type( arg );
if ( type === "function" ) {
if ( !options.unique || !self.has( arg ) ) {
list.push( arg );
}
} else if ( arg && arg.length && type !== "string" ) {
// Inspect recursively
add( arg );
}
});
})( arguments );
// Do we need to add the callbacks to the
// current firing batch?
if ( firing ) {
firingLength = list.length;
// With memory, if we're not firing then
// we should call right away
} else if ( memory ) {
firingStart = start;
fire( memory );
}
}
return this;
},
// Remove a callback from the list
remove: function() {
if ( list ) {
jQuery.each( arguments, function( _, arg ) {
var index;
while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
list.splice( index, 1 );
// Handle firing indexes
if ( firing ) {
if ( index <= firingLength ) {
firingLength--;
}
if ( index <= firingIndex ) {
firingIndex--;
}
}
}
});
}
return this;
},
// Check if a given callback is in the list.
// If no argument is given, return whether or not list has callbacks attached.
has: function( fn ) {
return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length );
},
// Remove all callbacks from the list
empty: function() {
list = [];
firingLength = 0;
return this;
},
// Have the list do nothing anymore
disable: function() {
list = stack = memory = undefined;
return this;
},
// Is it disabled?
disabled: function() {
return !list;
},
// Lock the list in its current state
lock: function() {
stack = undefined;
if ( !memory ) {
self.disable();
}
return this;
},
// Is it locked?
locked: function() {
return !stack;
},
// Call all callbacks with the given context and arguments
fireWith: function( context, args ) {
if ( list && ( !fired || stack ) ) {
args = args || [];
args = [ context, args.slice ? args.slice() : args ];
if ( firing ) {
stack.push( args );
} else {
fire( args );
}
}
return this;
},
// Call all the callbacks with the given arguments
fire: function() {
self.fireWith( this, arguments );
return this;
},
// To know if the callbacks have already been called at least once
fired: function() {
return !!fired;
}
};
return self;
};
jQuery.extend({
Deferred: function( func ) {
var tuples = [
// action, add listener, listener list, final state
[ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ],
[ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ],
[ "notify", "progress", jQuery.Callbacks("memory") ]
],
state = "pending",
promise = {
state: function() {
return state;
},
always: function() {
deferred.done( arguments ).fail( arguments );
return this;
},
then: function( /* fnDone, fnFail, fnProgress */ ) {
var fns = arguments;
return jQuery.Deferred(function( newDefer ) {
jQuery.each( tuples, function( i, tuple ) {
var action = tuple[ 0 ],
fn = jQuery.isFunction( fns[ i ] ) && fns[ i ];
// deferred[ done | fail | progress ] for forwarding actions to newDefer
deferred[ tuple[1] ](function() {
var returned = fn && fn.apply( this, arguments );
if ( returned && jQuery.isFunction( returned.promise ) ) {
returned.promise()
.done( newDefer.resolve )
.fail( newDefer.reject )
.progress( newDefer.notify );
} else {
newDefer[ action + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments );
}
});
});
fns = null;
}).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
return obj != null ? jQuery.extend( obj, promise ) : promise;
}
},
deferred = {};
// Keep pipe for back-compat
promise.pipe = promise.then;
// Add list-specific methods
jQuery.each( tuples, function( i, tuple ) {
var list = tuple[ 2 ],
stateString = tuple[ 3 ];
// promise[ done | fail | progress ] = list.add
promise[ tuple[1] ] = list.add;
// Handle state
if ( stateString ) {
list.add(function() {
// state = [ resolved | rejected ]
state = stateString;
// [ reject_list | resolve_list ].disable; progress_list.lock
}, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock );
}
// deferred[ resolve | reject | notify ]
deferred[ tuple[0] ] = function() {
deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments );
return this;
};
deferred[ tuple[0] + "With" ] = list.fireWith;
});
// Make the deferred a promise
promise.promise( deferred );
// Call given func if any
if ( func ) {
func.call( deferred, deferred );
}
// All done!
return deferred;
},
// Deferred helper
when: function( subordinate /* , ..., subordinateN */ ) {
var i = 0,
resolveValues = core_slice.call( arguments ),
length = resolveValues.length,
// the count of uncompleted subordinates
remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0,
// the master Deferred. If resolveValues consist of only a single Deferred, just use that.
deferred = remaining === 1 ? subordinate : jQuery.Deferred(),
// Update function for both resolve and progress values
updateFunc = function( i, contexts, values ) {
return function( value ) {
contexts[ i ] = this;
values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value;
if( values === progressValues ) {
deferred.notifyWith( contexts, values );
} else if ( !( --remaining ) ) {
deferred.resolveWith( contexts, values );
}
};
},
progressValues, progressContexts, resolveContexts;
// add listeners to Deferred subordinates; treat others as resolved
if ( length > 1 ) {
progressValues = new Array( length );
progressContexts = new Array( length );
resolveContexts = new Array( length );
for ( ; i < length; i++ ) {
if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) {
resolveValues[ i ].promise()
.done( updateFunc( i, resolveContexts, resolveValues ) )
.fail( deferred.reject )
.progress( updateFunc( i, progressContexts, progressValues ) );
} else {
--remaining;
}
}
}
// if we're not waiting on anything, resolve the master
if ( !remaining ) {
deferred.resolveWith( resolveContexts, resolveValues );
}
return deferred.promise();
}
});
jQuery.support = (function( support ) {
var input = document.createElement("input"),
fragment = document.createDocumentFragment(),
div = document.createElement("div"),
select = document.createElement("select"),
opt = select.appendChild( document.createElement("option") );
// Finish early in limited environments
if ( !input.type ) {
return support;
}
input.type = "checkbox";
// Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3
// Check the default checkbox/radio value ("" on old WebKit; "on" elsewhere)
support.checkOn = input.value !== "";
// Must access the parent to make an option select properly
// Support: IE9, IE10
support.optSelected = opt.selected;
// Will be defined later
support.reliableMarginRight = true;
support.boxSizingReliable = true;
support.pixelPosition = false;
// Make sure checked status is properly cloned
// Support: IE9, IE10
input.checked = true;
support.noCloneChecked = input.cloneNode( true ).checked;
// Make sure that the options inside disabled selects aren't marked as disabled
// (WebKit marks them as disabled)
select.disabled = true;
support.optDisabled = !opt.disabled;
// Check if an input maintains its value after becoming a radio
// Support: IE9, IE10
input = document.createElement("input");
input.value = "t";
input.type = "radio";
support.radioValue = input.value === "t";
// #11217 - WebKit loses check when the name is after the checked attribute
input.setAttribute( "checked", "t" );
input.setAttribute( "name", "t" );
fragment.appendChild( input );
// Support: Safari 5.1, Android 4.x, Android 2.3
// old WebKit doesn't clone checked state correctly in fragments
support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked;
// Support: Firefox, Chrome, Safari
// Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP)
support.focusinBubbles = "onfocusin" in window;
div.style.backgroundClip = "content-box";
div.cloneNode( true ).style.backgroundClip = "";
support.clearCloneStyle = div.style.backgroundClip === "content-box";
// Run at.tugraz.kti.pdftable.tests that need a body at doc ready
jQuery(function() {
var container, marginDiv,
// Support: Firefox, Android 2.3 (Prefixed box-sizing versions).
divReset = "padding:0;margin:0;border:0;display:block;-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box",
body = document.getElementsByTagName("body")[ 0 ];
if ( !body ) {
// Return for frameset docs that don't have a body
return;
}
container = document.createElement("div");
container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px";
// Check box-sizing and margin behavior.
body.appendChild( container ).appendChild( div );
div.innerHTML = "";
// Support: Firefox, Android 2.3 (Prefixed box-sizing versions).
div.style.cssText = "-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%";
// Workaround failing boxSizing test due to offsetWidth returning wrong value
// with some non-1 values of body zoom, ticket #13543
jQuery.swap( body, body.style.zoom != null ? { zoom: 1 } : {}, function() {
support.boxSizing = div.offsetWidth === 4;
});
// Use window.getComputedStyle because jsdom on node.js will break without it.
if ( window.getComputedStyle ) {
support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%";
support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px";
// Support: Android 2.3
// Check if div with explicit width and no margin-right incorrectly
// gets computed margin-right based on width of container. (#3333)
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
marginDiv = div.appendChild( document.createElement("div") );
marginDiv.style.cssText = div.style.cssText = divReset;
marginDiv.style.marginRight = marginDiv.style.width = "0";
div.style.width = "1px";
support.reliableMarginRight =
!parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight );
}
body.removeChild( container );
});
return support;
})( {} );
/*
Implementation Summary
1. Enforce API surface and semantic compatibility with 1.9.x branch
2. Improve the module's maintainability by reducing the storage
paths to a single mechanism.
3. Use the same single mechanism to support "private" and "user" data.
4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData)
5. Avoid exposing implementation details on user objects (eg. expando properties)
6. Provide a clear path for implementation upgrade to WeakMap in 2014
*/
var data_user, data_priv,
rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/,
rmultiDash = /([A-Z])/g;
function Data() {
// Support: Android < 4,
// Old WebKit does not have Object.preventExtensions/freeze method,
// return new empty object instead with no [[set]] accessor
Object.defineProperty( this.cache = {}, 0, {
get: function() {
return {};
}
});
this.expando = jQuery.expando + Math.random();
}
Data.uid = 1;
Data.accepts = function( owner ) {
// Accepts only:
// - Node
// - Node.ELEMENT_NODE
// - Node.DOCUMENT_NODE
// - Object
// - Any
return owner.nodeType ?
owner.nodeType === 1 || owner.nodeType === 9 : true;
};
Data.prototype = {
key: function( owner ) {
// We can accept data for non-element nodes in modern browsers,
// but we should not, see #8335.
// Always return the key for a frozen object.
if ( !Data.accepts( owner ) ) {
return 0;
}
var descriptor = {},
// Check if the owner object already has a cache key
unlock = owner[ this.expando ];
// If not, create one
if ( !unlock ) {
unlock = Data.uid++;
// Secure it in a non-enumerable, non-writable property
try {
descriptor[ this.expando ] = { value: unlock };
Object.defineProperties( owner, descriptor );
// Support: Android < 4
// Fallback to a less secure definition
} catch ( e ) {
descriptor[ this.expando ] = unlock;
jQuery.extend( owner, descriptor );
}
}
// Ensure the cache object
if ( !this.cache[ unlock ] ) {
this.cache[ unlock ] = {};
}
return unlock;
},
set: function( owner, data, value ) {
var prop,
// There may be an unlock assigned to this node,
// if there is no entry for this "owner", create one inline
// and set the unlock as though an owner entry had always existed
unlock = this.key( owner ),
cache = this.cache[ unlock ];
// Handle: [ owner, key, value ] args
if ( typeof data === "string" ) {
cache[ data ] = value;
// Handle: [ owner, { properties } ] args
} else {
// Fresh assignments by object are shallow copied
if ( jQuery.isEmptyObject( cache ) ) {
jQuery.extend( this.cache[ unlock ], data );
// Otherwise, copy the properties one-by-one to the cache object
} else {
for ( prop in data ) {
cache[ prop ] = data[ prop ];
}
}
}
return cache;
},
get: function( owner, key ) {
// Either a valid cache is found, or will be created.
// New caches will be created and the unlock returned,
// allowing direct access to the newly created
// empty data object. A valid owner object must be provided.
var cache = this.cache[ this.key( owner ) ];
return key === undefined ?
cache : cache[ key ];
},
access: function( owner, key, value ) {
var stored;
// In cases where either:
//
// 1. No key was specified
// 2. A string key was specified, but no value provided
//
// Take the "read" path and allow the get method to determine
// which value to return, respectively either:
//
// 1. The entire cache object
// 2. The data stored at the key
//
if ( key === undefined ||
((key && typeof key === "string") && value === undefined) ) {
stored = this.get( owner, key );
return stored !== undefined ?
stored : this.get( owner, jQuery.camelCase(key) );
}
// [*]When the key is not a string, or both a key and value
// are specified, set or extend (existing objects) with either:
//
// 1. An object of properties
// 2. A key and value
//
this.set( owner, key, value );
// Since the "set" path can have two possible entry points
// return the expected data based on which path was taken[*]
return value !== undefined ? value : key;
},
remove: function( owner, key ) {
var i, name, camel,
unlock = this.key( owner ),
cache = this.cache[ unlock ];
if ( key === undefined ) {
this.cache[ unlock ] = {};
} else {
// Support array or space separated string of keys
if ( jQuery.isArray( key ) ) {
// If "name" is an array of keys...
// When data is initially created, via ("key", "val") signature,
// keys will be converted to camelCase.
// Since there is no way to tell _how_ a key was added, remove
// both plain key and camelCase key. #12786
// This will only penalize the array argument path.
name = key.concat( key.map( jQuery.camelCase ) );
} else {
camel = jQuery.camelCase( key );
// Try the string as a key before any manipulation
if ( key in cache ) {
name = [ key, camel ];
} else {
// If a key with the spaces exists, use it.
// Otherwise, create an array by matching non-whitespace
name = camel;
name = name in cache ?
[ name ] : ( name.match( core_rnotwhite ) || [] );
}
}
i = name.length;
while ( i-- ) {
delete cache[ name[ i ] ];
}
}
},
hasData: function( owner ) {
return !jQuery.isEmptyObject(
this.cache[ owner[ this.expando ] ] || {}
);
},
discard: function( owner ) {
if ( owner[ this.expando ] ) {
delete this.cache[ owner[ this.expando ] ];
}
}
};
// These may be used throughout the jQuery core codebase
data_user = new Data();
data_priv = new Data();
jQuery.extend({
acceptData: Data.accepts,
hasData: function( elem ) {
return data_user.hasData( elem ) || data_priv.hasData( elem );
},
data: function( elem, name, data ) {
return data_user.access( elem, name, data );
},
removeData: function( elem, name ) {
data_user.remove( elem, name );
},
// TODO: Now that all calls to _data and _removeData have been replaced
// with direct calls to data_priv methods, these can be deprecated.
_data: function( elem, name, data ) {
return data_priv.access( elem, name, data );
},
_removeData: function( elem, name ) {
data_priv.remove( elem, name );
}
});
jQuery.fn.extend({
data: function( key, value ) {
var attrs, name,
elem = this[ 0 ],
i = 0,
data = null;
// Gets all values
if ( key === undefined ) {
if ( this.length ) {
data = data_user.get( elem );
if ( elem.nodeType === 1 && !data_priv.get( elem, "hasDataAttrs" ) ) {
attrs = elem.attributes;
for ( ; i < attrs.length; i++ ) {
name = attrs[ i ].name;
if ( name.indexOf( "data-" ) === 0 ) {
name = jQuery.camelCase( name.slice(5) );
dataAttr( elem, name, data[ name ] );
}
}
data_priv.set( elem, "hasDataAttrs", true );
}
}
return data;
}
// Sets multiple values
if ( typeof key === "object" ) {
return this.each(function() {
data_user.set( this, key );
});
}
return jQuery.access( this, function( value ) {
var data,
camelKey = jQuery.camelCase( key );
// The calling jQuery object (element matches) is not empty
// (and therefore has an element appears at this[ 0 ]) and the
// `value` parameter was not undefined. An empty jQuery object
// will result in `undefined` for elem = this[ 0 ] which will
// throw an exception if an attempt to read a data cache is made.
if ( elem && value === undefined ) {
// Attempt to get data from the cache
// with the key as-is
data = data_user.get( elem, key );
if ( data !== undefined ) {
return data;
}
// Attempt to get data from the cache
// with the key camelized
data = data_user.get( elem, camelKey );
if ( data !== undefined ) {
return data;
}
// Attempt to "discover" the data in
// HTML5 custom data-* attrs
data = dataAttr( elem, camelKey, undefined );
if ( data !== undefined ) {
return data;
}
// We tried really hard, but the data doesn't exist.
return;
}
// Set the data...
this.each(function() {
// First, attempt to store a copy or reference of any
// data that might've been store with a camelCased key.
var data = data_user.get( this, camelKey );
// For HTML5 data-* attribute interop, we have to
// store property names with dashes in a camelCase form.
// This might not apply to all properties...*
data_user.set( this, camelKey, value );
// *... In the case of properties that might _actually_
// have dashes, we need to also store a copy of that
// unchanged property.
if ( key.indexOf("-") !== -1 && data !== undefined ) {
data_user.set( this, key, value );
}
});
}, null, value, arguments.length > 1, null, true );
},
removeData: function( key ) {
return this.each(function() {
data_user.remove( this, key );
});
}
});
function dataAttr( elem, key, data ) {
var name;
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
// Only convert to a number if it doesn't change the string
+data + "" === data ? +data :
rbrace.test( data ) ? JSON.parse( data ) :
data;
} catch( e ) {}
// Make sure we set the data so it isn't changed later
data_user.set( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
jQuery.extend({
queue: function( elem, type, data ) {
var queue;
if ( elem ) {
type = ( type || "fx" ) + "queue";
queue = data_priv.get( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !queue || jQuery.isArray( data ) ) {
queue = data_priv.access( elem, type, jQuery.makeArray(data) );
} else {
queue.push( data );
}
}
return queue || [];
}
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
startLength = queue.length,
fn = queue.shift(),
hooks = jQuery._queueHooks( elem, type ),
next = function() {
jQuery.dequeue( elem, type );
};
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
fn = queue.shift();
startLength--;
}
if ( fn ) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if ( type === "fx" ) {
queue.unshift( "inprogress" );
}
// clear up the last queue stop function
delete hooks.stop;
fn.call( elem, next, hooks );
}
if ( !startLength && hooks ) {
hooks.empty.fire();
}
},
// not intended for public consumption - generates a queueHooks object, or returns the current one
_queueHooks: function( elem, type ) {
var key = type + "queueHooks";
return data_priv.get( elem, key ) || data_priv.access( elem, key, {
empty: jQuery.Callbacks("once memory").add(function() {
data_priv.remove( elem, [ type + "queue", key ] );
})
});
}
});
jQuery.fn.extend({
queue: function( type, data ) {
var setter = 2;
if ( typeof type !== "string" ) {
data = type;
type = "fx";
setter--;
}
if ( arguments.length < setter ) {
return jQuery.queue( this[0], type );
}
return data === undefined ?
this :
this.each(function() {
var queue = jQuery.queue( this, type, data );
// ensure a hooks for this queue
jQuery._queueHooks( this, type );
if ( type === "fx" && queue[0] !== "inprogress" ) {
jQuery.dequeue( this, type );
}
});
},
dequeue: function( type ) {
return this.each(function() {
jQuery.dequeue( this, type );
});
},
// Based off of the plugin by Clint Helfers, with permission.
// http://blindsignals.com/index.php/2009/07/jquery-delay/
delay: function( time, type ) {
time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
type = type || "fx";
return this.queue( type, function( next, hooks ) {
var timeout = setTimeout( next, time );
hooks.stop = function() {
clearTimeout( timeout );
};
});
},
clearQueue: function( type ) {
return this.queue( type || "fx", [] );
},
// Get a promise resolved when queues of a certain type
// are emptied (fx is the type by default)
promise: function( type, obj ) {
var tmp,
count = 1,
defer = jQuery.Deferred(),
elements = this,
i = this.length,
resolve = function() {
if ( !( --count ) ) {
defer.resolveWith( elements, [ elements ] );
}
};
if ( typeof type !== "string" ) {
obj = type;
type = undefined;
}
type = type || "fx";
while( i-- ) {
tmp = data_priv.get( elements[ i ], type + "queueHooks" );
if ( tmp && tmp.empty ) {
count++;
tmp.empty.add( resolve );
}
}
resolve();
return defer.promise( obj );
}
});
var nodeHook, boolHook,
rclass = /[\t\r\n\f]/g,
rreturn = /\r/g,
rfocusable = /^(?:input|select|textarea|button)$/i;
jQuery.fn.extend({
attr: function( name, value ) {
return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 );
},
removeAttr: function( name ) {
return this.each(function() {
jQuery.removeAttr( this, name );
});
},
prop: function( name, value ) {
return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 );
},
removeProp: function( name ) {
return this.each(function() {
delete this[ jQuery.propFix[ name ] || name ];
});
},
addClass: function( value ) {
var classes, elem, cur, clazz, j,
i = 0,
len = this.length,
proceed = typeof value === "string" && value;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).addClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
// The disjunction here is for better compressibility (see removeClass)
classes = ( value || "" ).match( core_rnotwhite ) || [];
for ( ; i < len; i++ ) {
elem = this[ i ];
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace( rclass, " " ) :
" "
);
if ( cur ) {
j = 0;
while ( (clazz = classes[j++]) ) {
if ( cur.indexOf( " " + clazz + " " ) < 0 ) {
cur += clazz + " ";
}
}
elem.className = jQuery.trim( cur );
}
}
}
return this;
},
removeClass: function( value ) {
var classes, elem, cur, clazz, j,
i = 0,
len = this.length,
proceed = arguments.length === 0 || typeof value === "string" && value;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).removeClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
classes = ( value || "" ).match( core_rnotwhite ) || [];
for ( ; i < len; i++ ) {
elem = this[ i ];
// This expression is here for better compressibility (see addClass)
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace( rclass, " " ) :
""
);
if ( cur ) {
j = 0;
while ( (clazz = classes[j++]) ) {
// Remove *all* instances
while ( cur.indexOf( " " + clazz + " " ) >= 0 ) {
cur = cur.replace( " " + clazz + " ", " " );
}
}
elem.className = value ? jQuery.trim( cur ) : "";
}
}
}
return this;
},
toggleClass: function( value, stateVal ) {
var type = typeof value;
if ( typeof stateVal === "boolean" && type === "string" ) {
return stateVal ? this.addClass( value ) : this.removeClass( value );
}
if ( jQuery.isFunction( value ) ) {
return this.each(function( i ) {
jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal );
});
}
return this.each(function() {
if ( type === "string" ) {
// toggle individual class names
var className,
i = 0,
self = jQuery( this ),
classNames = value.match( core_rnotwhite ) || [];
while ( (className = classNames[ i++ ]) ) {
// check each className given, space separated list
if ( self.hasClass( className ) ) {
self.removeClass( className );
} else {
self.addClass( className );
}
}
// Toggle whole class name
} else if ( type === core_strundefined || type === "boolean" ) {
if ( this.className ) {
// store className if set
data_priv.set( this, "__className__", this.className );
}
// If the element has a class name or if we're passed "false",
// then remove the whole classname (if there was one, the above saved it).
// Otherwise bring back whatever was previously saved (if anything),
// falling back to the empty string if nothing was stored.
this.className = this.className || value === false ? "" : data_priv.get( this, "__className__" ) || "";
}
});
},
hasClass: function( selector ) {
var className = " " + selector + " ",
i = 0,
l = this.length;
for ( ; i < l; i++ ) {
if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) {
return true;
}
}
return false;
},
val: function( value ) {
var hooks, ret, isFunction,
elem = this[0];
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];
if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
return ret;
}
ret = elem.value;
return typeof ret === "string" ?
// handle most common string cases
ret.replace(rreturn, "") :
// handle cases where value is null/undef or number
ret == null ? "" : ret;
}
return;
}
isFunction = jQuery.isFunction( value );
return this.each(function( i ) {
var val;
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call( this, i, jQuery( this ).val() );
} else {
val = value;
}
// Treat null/undefined as ""; convert numbers to string
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( jQuery.isArray( val ) ) {
val = jQuery.map(val, function ( value ) {
return value == null ? "" : value + "";
});
}
hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
// If set returns undefined, fall back to normal setting
if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
this.value = val;
}
});
}
});
jQuery.extend({
valHooks: {
option: {
get: function( elem ) {
// attributes.value is undefined in Blackberry 4.7 but
// uses .value. See #6932
var val = elem.attributes.value;
return !val || val.specified ? elem.value : elem.text;
}
},
select: {
get: function( elem ) {
var value, option,
options = elem.options,
index = elem.selectedIndex,
one = elem.type === "select-one" || index < 0,
values = one ? null : [],
max = one ? index + 1 : options.length,
i = index < 0 ?
max :
one ? index : 0;
// Loop through all the selected options
for ( ; i < max; i++ ) {
option = options[ i ];
// IE6-9 doesn't update selected after form reset (#2551)
if ( ( option.selected || i === index ) &&
// Don't return options that are disabled or in a disabled optgroup
( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) &&
( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) {
// Get the specific value for the option
value = jQuery( option ).val();
// We don't need an array for one selects
if ( one ) {
return value;
}
// Multi-Selects return an array
values.push( value );
}
}
return values;
},
set: function( elem, value ) {
var optionSet, option,
options = elem.options,
values = jQuery.makeArray( value ),
i = options.length;
while ( i-- ) {
option = options[ i ];
if ( (option.selected = jQuery.inArray( jQuery(option).val(), values ) >= 0) ) {
optionSet = true;
}
}
// force browsers to behave consistently when non-matching value is set
if ( !optionSet ) {
elem.selectedIndex = -1;
}
return values;
}
}
},
attr: function( elem, name, value ) {
var hooks, ret,
nType = elem.nodeType;
// don't get/set attributes on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
// Fallback to prop when attributes are not supported
if ( typeof elem.getAttribute === core_strundefined ) {
return jQuery.prop( elem, name, value );
}
// All attributes are lowercase
// Grab necessary hook if one is defined
if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
name = name.toLowerCase();
hooks = jQuery.attrHooks[ name ] ||
( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook );
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name );
} else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
elem.setAttribute( name, value + "" );
return value;
}
} else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
ret = jQuery.find.attr( elem, name );
// Non-existent attributes return null, we normalize to undefined
return ret == null ?
undefined :
ret;
}
},
removeAttr: function( elem, value ) {
var name, propName,
i = 0,
attrNames = value && value.match( core_rnotwhite );
if ( attrNames && elem.nodeType === 1 ) {
while ( (name = attrNames[i++]) ) {
propName = jQuery.propFix[ name ] || name;
// Boolean attributes get special treatment (#10870)
if ( jQuery.expr.match.bool.test( name ) ) {
// Set corresponding property to false
elem[ propName ] = false;
}
elem.removeAttribute( name );
}
}
},
attrHooks: {
type: {
set: function( elem, value ) {
if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) {
// Setting the type on a radio button after the value resets the value in IE6-9
// Reset value to default in case type is set after value during creation
var val = elem.value;
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
}
},
propFix: {
"for": "htmlFor",
"class": "className"
},
prop: function( elem, name, value ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set properties on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
if ( notxml ) {
// Fix name and attach hooks
name = jQuery.propFix[ name ] || name;
hooks = jQuery.propHooks[ name ];
}
if ( value !== undefined ) {
return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ?
ret :
( elem[ name ] = value );
} else {
return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ?
ret :
elem[ name ];
}
},
propHooks: {
tabIndex: {
get: function( elem ) {
return elem.hasAttribute( "tabindex" ) || rfocusable.test( elem.nodeName ) || elem.href ?
elem.tabIndex :
-1;
}
}
}
});
// Hooks for boolean attributes
boolHook = {
set: function( elem, value, name ) {
if ( value === false ) {
// Remove boolean attributes when set to false
jQuery.removeAttr( elem, name );
} else {
elem.setAttribute( name, name );
}
return name;
}
};
jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) {
var getter = jQuery.expr.attrHandle[ name ] || jQuery.find.attr;
jQuery.expr.attrHandle[ name ] = function( elem, name, isXML ) {
var fn = jQuery.expr.attrHandle[ name ],
ret = isXML ?
undefined :
/* jshint eqeqeq: false */
// Temporarily disable this handler to check existence
(jQuery.expr.attrHandle[ name ] = undefined) !=
getter( elem, name, isXML ) ?
name.toLowerCase() :
null;
// Restore handler
jQuery.expr.attrHandle[ name ] = fn;
return ret;
};
});
// Support: IE9+
// Selectedness for an option in an optgroup can be inaccurate
if ( !jQuery.support.optSelected ) {
jQuery.propHooks.selected = {
get: function( elem ) {
var parent = elem.parentNode;
if ( parent && parent.parentNode ) {
parent.parentNode.selectedIndex;
}
return null;
}
};
}
jQuery.each([
"tabIndex",
"readOnly",
"maxLength",
"cellSpacing",
"cellPadding",
"rowSpan",
"colSpan",
"useMap",
"frameBorder",
"contentEditable"
], function() {
jQuery.propFix[ this.toLowerCase() ] = this;
});
// Radios and checkboxes getter/setter
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = {
set: function( elem, value ) {
if ( jQuery.isArray( value ) ) {
return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 );
}
}
};
if ( !jQuery.support.checkOn ) {
jQuery.valHooks[ this ].get = function( elem ) {
// Support: Webkit
// "" is returned instead of "on" if a value isn't specified
return elem.getAttribute("value") === null ? "on" : elem.value;
};
}
});
var rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|contextmenu)|click/,
rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
rtypenamespace = /^([^.]*)(?:\.(.+)|)$/;
function returnTrue() {
return true;
}
function returnFalse() {
return false;
}
function safeActiveElement() {
try {
return document.activeElement;
} catch ( err ) { }
}
/*
* Helper functions for managing events -- not part of the public interface.
* Props to Dean Edwards' addEvent library for many of the ideas.
*/
jQuery.event = {
global: {},
add: function( elem, types, handler, data, selector ) {
var handleObjIn, eventHandle, tmp,
events, t, handleObj,
special, handlers, type, namespaces, origType,
elemData = data_priv.get( elem );
// Don't attach events to noData or text/comment nodes (but allow plain objects)
if ( !elemData ) {
return;
}
// Caller can pass in an object of custom data in lieu of the handler
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
selector = handleObjIn.selector;
}
// Make sure that the handler has a unique ID, used to find/remove it later
if ( !handler.guid ) {
handler.guid = jQuery.guid++;
}
// Init the element's event structure and main handler, if this is the first
if ( !(events = elemData.events) ) {
events = elemData.events = {};
}
if ( !(eventHandle = elemData.handle) ) {
eventHandle = elemData.handle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== core_strundefined && (!e || jQuery.event.triggered !== e.type) ?
jQuery.event.dispatch.apply( eventHandle.elem, arguments ) :
undefined;
};
// Add elem as a property of the handle fn to prevent a memory leak with IE non-native events
eventHandle.elem = elem;
}
// Handle multiple events separated by a space
types = ( types || "" ).match( core_rnotwhite ) || [""];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[t] ) || [];
type = origType = tmp[1];
namespaces = ( tmp[2] || "" ).split( "." ).sort();
// There *must* be a type, no attaching namespace-only handlers
if ( !type ) {
continue;
}
// If event changes its type, use the special event handlers for the changed type
special = jQuery.event.special[ type ] || {};
// If selector defined, determine special event api type, otherwise given type
type = ( selector ? special.delegateType : special.bindType ) || type;
// Update special based on newly reset type
special = jQuery.event.special[ type ] || {};
// handleObj is passed to all event handlers
handleObj = jQuery.extend({
type: type,
origType: origType,
data: data,
handler: handler,
guid: handler.guid,
selector: selector,
needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
namespace: namespaces.join(".")
}, handleObjIn );
// Init the event handler queue if we're the first
if ( !(handlers = events[ type ]) ) {
handlers = events[ type ] = [];
handlers.delegateCount = 0;
// Only use addEventListener if the special events handler returns false
if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle, false );
}
}
}
if ( special.add ) {
special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
}
}
// Add to the element's handler list, delegates in front
if ( selector ) {
handlers.splice( handlers.delegateCount++, 0, handleObj );
} else {
handlers.push( handleObj );
}
// Keep track of which events have ever been used, for event optimization
jQuery.event.global[ type ] = true;
}
// Nullify elem to prevent memory leaks in IE
elem = null;
},
// Detach an event or set of events from an element
remove: function( elem, types, handler, selector, mappedTypes ) {
var j, origCount, tmp,
events, t, handleObj,
special, handlers, type, namespaces, origType,
elemData = data_priv.hasData( elem ) && data_priv.get( elem );
if ( !elemData || !(events = elemData.events) ) {
return;
}
// Once for each type.namespace in types; type may be omitted
types = ( types || "" ).match( core_rnotwhite ) || [""];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[t] ) || [];
type = origType = tmp[1];
namespaces = ( tmp[2] || "" ).split( "." ).sort();
// Unbind all events (on this namespace, if provided) for the element
if ( !type ) {
for ( type in events ) {
jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
}
continue;
}
special = jQuery.event.special[ type ] || {};
type = ( selector ? special.delegateType : special.bindType ) || type;
handlers = events[ type ] || [];
tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" );
// Remove matching events
origCount = j = handlers.length;
while ( j-- ) {
handleObj = handlers[ j ];
if ( ( mappedTypes || origType === handleObj.origType ) &&
( !handler || handler.guid === handleObj.guid ) &&
( !tmp || tmp.test( handleObj.namespace ) ) &&
( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) {
handlers.splice( j, 1 );
if ( handleObj.selector ) {
handlers.delegateCount--;
}
if ( special.remove ) {
special.remove.call( elem, handleObj );
}
}
}
// Remove generic event handler if we removed something and no more handlers exist
// (avoids potential for endless recursion during removal of special event handlers)
if ( origCount && !handlers.length ) {
if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) {
jQuery.removeEvent( elem, type, elemData.handle );
}
delete events[ type ];
}
}
// Remove the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
delete elemData.handle;
data_priv.remove( elem, "events" );
}
},
trigger: function( event, data, elem, onlyHandlers ) {
var i, cur, tmp, bubbleType, ontype, handle, special,
eventPath = [ elem || document ],
type = core_hasOwn.call( event, "type" ) ? event.type : event,
namespaces = core_hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : [];
cur = tmp = elem = elem || document;
// Don't do events on text and comment nodes
if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
return;
}
// focus/blur morphs to focusin/out; ensure we're not firing them right now
if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
return;
}
if ( type.indexOf(".") >= 0 ) {
// Namespaced trigger; create a regexp to match event type in handle()
namespaces = type.split(".");
type = namespaces.shift();
namespaces.sort();
}
ontype = type.indexOf(":") < 0 && "on" + type;
// Caller can pass in a jQuery.Event object, Object, or just an event type string
event = event[ jQuery.expando ] ?
event :
new jQuery.Event( type, typeof event === "object" && event );
// Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true)
event.isTrigger = onlyHandlers ? 2 : 3;
event.namespace = namespaces.join(".");
event.namespace_re = event.namespace ?
new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) :
null;
// Clean up the event in case it is being reused
event.result = undefined;
if ( !event.target ) {
event.target = elem;
}
// Clone any incoming data and prepend the event, creating the handler arg list
data = data == null ?
[ event ] :
jQuery.makeArray( data, [ event ] );
// Allow special events to draw outside the lines
special = jQuery.event.special[ type ] || {};
if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) {
return;
}
// Determine event propagation path in advance, per W3C events spec (#9951)
// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
bubbleType = special.delegateType || type;
if ( !rfocusMorph.test( bubbleType + type ) ) {
cur = cur.parentNode;
}
for ( ; cur; cur = cur.parentNode ) {
eventPath.push( cur );
tmp = cur;
}
// Only add window if we got to document (e.g., not plain obj or detached DOM)
if ( tmp === (elem.ownerDocument || document) ) {
eventPath.push( tmp.defaultView || tmp.parentWindow || window );
}
}
// Fire handlers on the event path
i = 0;
while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) {
event.type = i > 1 ?
bubbleType :
special.bindType || type;
// jQuery handler
handle = ( data_priv.get( cur, "events" ) || {} )[ event.type ] && data_priv.get( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
}
// Native handler
handle = ontype && cur[ ontype ];
if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) {
event.preventDefault();
}
}
event.type = type;
// If nobody prevented the default action, do it now
if ( !onlyHandlers && !event.isDefaultPrevented() ) {
if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) &&
jQuery.acceptData( elem ) ) {
// Call a native DOM method on the target with the same name name as the event.
// Don't do default actions on window, that's where global variables be (#6170)
if ( ontype && jQuery.isFunction( elem[ type ] ) && !jQuery.isWindow( elem ) ) {
// Don't re-trigger an onFOO event when we call its FOO() method
tmp = elem[ ontype ];
if ( tmp ) {
elem[ ontype ] = null;
}
// Prevent re-triggering of the same event, since we already bubbled it above
jQuery.event.triggered = type;
elem[ type ]();
jQuery.event.triggered = undefined;
if ( tmp ) {
elem[ ontype ] = tmp;
}
}
}
}
return event.result;
},
dispatch: function( event ) {
// Make a writable jQuery.Event from the native event object
event = jQuery.event.fix( event );
var i, j, ret, matched, handleObj,
handlerQueue = [],
args = core_slice.call( arguments ),
handlers = ( data_priv.get( this, "events" ) || {} )[ event.type ] || [],
special = jQuery.event.special[ event.type ] || {};
// Use the fix-ed jQuery.Event rather than the (read-only) native event
args[0] = event;
event.delegateTarget = this;
// Call the preDispatch hook for the mapped type, and let it bail if desired
if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
return;
}
// Determine handlers
handlerQueue = jQuery.event.handlers.call( this, event, handlers );
// Run delegates first; they may want to stop propagation beneath us
i = 0;
while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) {
event.currentTarget = matched.elem;
j = 0;
while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) {
// Triggered event must either 1) have no namespace, or
// 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) {
event.handleObj = handleObj;
event.data = handleObj.data;
ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
.apply( matched.elem, args );
if ( ret !== undefined ) {
if ( (event.result = ret) === false ) {
event.preventDefault();
event.stopPropagation();
}
}
}
}
}
// Call the postDispatch hook for the mapped type
if ( special.postDispatch ) {
special.postDispatch.call( this, event );
}
return event.result;
},
handlers: function( event, handlers ) {
var i, matches, sel, handleObj,
handlerQueue = [],
delegateCount = handlers.delegateCount,
cur = event.target;
// Find delegate handlers
// Black-hole SVG <use> instance trees (#13180)
// Avoid non-left-click bubbling in Firefox (#3861)
if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) {
for ( ; cur !== this; cur = cur.parentNode || this ) {
// Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
if ( cur.disabled !== true || event.type !== "click" ) {
matches = [];
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
// Don't conflict with Object.prototype properties (#13203)
sel = handleObj.selector + " ";
if ( matches[ sel ] === undefined ) {
matches[ sel ] = handleObj.needsContext ?
jQuery( sel, this ).index( cur ) >= 0 :
jQuery.find( sel, this, null, [ cur ] ).length;
}
if ( matches[ sel ] ) {
matches.push( handleObj );
}
}
if ( matches.length ) {
handlerQueue.push({ elem: cur, handlers: matches });
}
}
}
}
// Add the remaining (directly-bound) handlers
if ( delegateCount < handlers.length ) {
handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) });
}
return handlerQueue;
},
// Includes some event props shared by KeyEvent and MouseEvent
props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
fixHooks: {},
keyHooks: {
props: "char charCode key keyCode".split(" "),
filter: function( event, original ) {
// Add which for key events
if ( event.which == null ) {
event.which = original.charCode != null ? original.charCode : original.keyCode;
}
return event;
}
},
mouseHooks: {
props: "button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
filter: function( event, original ) {
var eventDoc, doc, body,
button = original.button;
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && original.clientX != null ) {
eventDoc = event.target.ownerDocument || document;
doc = eventDoc.documentElement;
body = eventDoc.body;
event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 );
event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 );
}
// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && button !== undefined ) {
event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
}
return event;
}
},
fix: function( event ) {
if ( event[ jQuery.expando ] ) {
return event;
}
// Create a writable copy of the event object and normalize some properties
var i, prop, copy,
type = event.type,
originalEvent = event,
fixHook = this.fixHooks[ type ];
if ( !fixHook ) {
this.fixHooks[ type ] = fixHook =
rmouseEvent.test( type ) ? this.mouseHooks :
rkeyEvent.test( type ) ? this.keyHooks :
{};
}
copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;
event = new jQuery.Event( originalEvent );
i = copy.length;
while ( i-- ) {
prop = copy[ i ];
event[ prop ] = originalEvent[ prop ];
}
// Support: Cordova 2.5 (WebKit) (#13255)
// All events should have a target; Cordova deviceready doesn't
if ( !event.target ) {
event.target = document;
}
// Support: Safari 6.0+, Chrome < 28
// Target should not be a text node (#504, #13143)
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
return fixHook.filter? fixHook.filter( event, originalEvent ) : event;
},
special: {
load: {
// Prevent triggered image.load events from bubbling to window.load
noBubble: true
},
focus: {
// Fire native event if possible so blur/focus sequence is correct
trigger: function() {
if ( this !== safeActiveElement() && this.focus ) {
this.focus();
return false;
}
},
delegateType: "focusin"
},
blur: {
trigger: function() {
if ( this === safeActiveElement() && this.blur ) {
this.blur();
return false;
}
},
delegateType: "focusout"
},
click: {
// For checkbox, fire native event so checked state will be right
trigger: function() {
if ( this.type === "checkbox" && this.click && jQuery.nodeName( this, "input" ) ) {
this.click();
return false;
}
},
// For cross-browser consistency, don't fire native .click() on links
_default: function( event ) {
return jQuery.nodeName( event.target, "a" );
}
},
beforeunload: {
postDispatch: function( event ) {
// Support: Firefox 20+
// Firefox doesn't alert if the returnValue field is not set.
if ( event.result !== undefined ) {
event.originalEvent.returnValue = event.result;
}
}
}
},
simulate: function( type, elem, event, bubble ) {
// Piggyback on a donor event to simulate a different one.
// Fake originalEvent to avoid donor's stopPropagation, but if the
// simulated event prevents default then we do the same on the donor.
var e = jQuery.extend(
new jQuery.Event(),
event,
{
type: type,
isSimulated: true,
originalEvent: {}
}
);
if ( bubble ) {
jQuery.event.trigger( e, null, elem );
} else {
jQuery.event.dispatch.call( elem, e );
}
if ( e.isDefaultPrevented() ) {
event.preventDefault();
}
}
};
jQuery.removeEvent = function( elem, type, handle ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
}
};
jQuery.Event = function( src, props ) {
// Allow instantiation without the 'new' keyword
if ( !(this instanceof jQuery.Event) ) {
return new jQuery.Event( src, props );
}
// Event object
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = ( src.defaultPrevented ||
src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse;
// Event type
} else {
this.type = src;
}
// Put explicitly provided properties onto the event object
if ( props ) {
jQuery.extend( this, props );
}
// Create a timestamp if incoming event doesn't have one
this.timeStamp = src && src.timeStamp || jQuery.now();
// Mark it as fixed
this[ jQuery.expando ] = true;
};
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse,
preventDefault: function() {
var e = this.originalEvent;
this.isDefaultPrevented = returnTrue;
if ( e && e.preventDefault ) {
e.preventDefault();
}
},
stopPropagation: function() {
var e = this.originalEvent;
this.isPropagationStopped = returnTrue;
if ( e && e.stopPropagation ) {
e.stopPropagation();
}
},
stopImmediatePropagation: function() {
this.isImmediatePropagationStopped = returnTrue;
this.stopPropagation();
}
};
// Create mouseenter/leave events using mouseover/out and event-time checks
// Support: Chrome 15+
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
delegateType: fix,
bindType: fix,
handle: function( event ) {
var ret,
target = this,
related = event.relatedTarget,
handleObj = event.handleObj;
// For mousenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if ( !related || (related !== target && !jQuery.contains( target, related )) ) {
event.type = handleObj.origType;
ret = handleObj.handler.apply( this, arguments );
event.type = fix;
}
return ret;
}
};
});
// Create "bubbling" focus and blur events
// Support: Firefox, Chrome, Safari
if ( !jQuery.support.focusinBubbles ) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
// Attach a single capturing handler while someone wants focusin/focusout
var attaches = 0,
handler = function( event ) {
jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
};
jQuery.event.special[ fix ] = {
setup: function() {
if ( attaches++ === 0 ) {
document.addEventListener( orig, handler, true );
}
},
teardown: function() {
if ( --attaches === 0 ) {
document.removeEventListener( orig, handler, true );
}
}
};
});
}
jQuery.fn.extend({
on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
var origFn, type;
// Types can be a map of types/handlers
if ( typeof types === "object" ) {
// ( types-Object, selector, data )
if ( typeof selector !== "string" ) {
// ( types-Object, data )
data = data || selector;
selector = undefined;
}
for ( type in types ) {
this.on( type, selector, data, types[ type ], one );
}
return this;
}
if ( data == null && fn == null ) {
// ( types, fn )
fn = selector;
data = selector = undefined;
} else if ( fn == null ) {
if ( typeof selector === "string" ) {
// ( types, selector, fn )
fn = data;
data = undefined;
} else {
// ( types, data, fn )
fn = data;
data = selector;
selector = undefined;
}
}
if ( fn === false ) {
fn = returnFalse;
} else if ( !fn ) {
return this;
}
if ( one === 1 ) {
origFn = fn;
fn = function( event ) {
// Can use an empty set, since event contains the info
jQuery().off( event );
return origFn.apply( this, arguments );
};
// Use same guid so caller can remove using origFn
fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
}
return this.each( function() {
jQuery.event.add( this, types, fn, data, selector );
});
},
one: function( types, selector, data, fn ) {
return this.on( types, selector, data, fn, 1 );
},
off: function( types, selector, fn ) {
var handleObj, type;
if ( types && types.preventDefault && types.handleObj ) {
// ( event ) dispatched jQuery.Event
handleObj = types.handleObj;
jQuery( types.delegateTarget ).off(
handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType,
handleObj.selector,
handleObj.handler
);
return this;
}
if ( typeof types === "object" ) {
// ( types-object [, selector] )
for ( type in types ) {
this.off( type, selector, types[ type ] );
}
return this;
}
if ( selector === false || typeof selector === "function" ) {
// ( types [, fn] )
fn = selector;
selector = undefined;
}
if ( fn === false ) {
fn = returnFalse;
}
return this.each(function() {
jQuery.event.remove( this, types, fn, selector );
});
},
trigger: function( type, data ) {
return this.each(function() {
jQuery.event.trigger( type, data, this );
});
},
triggerHandler: function( type, data ) {
var elem = this[0];
if ( elem ) {
return jQuery.event.trigger( type, data, elem, true );
}
}
});
var isSimple = /^.[^:#\[\.,]*$/,
rparentsprev = /^(?:parents|prev(?:Until|All))/,
rneedsContext = jQuery.expr.match.needsContext,
// methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
jQuery.fn.extend({
find: function( selector ) {
var i,
ret = [],
self = this,
len = self.length;
if ( typeof selector !== "string" ) {
return this.pushStack( jQuery( selector ).filter(function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( self[ i ], this ) ) {
return true;
}
}
}) );
}
for ( i = 0; i < len; i++ ) {
jQuery.find( selector, self[ i ], ret );
}
// Needed because $( selector, context ) becomes $( context ).find( selector )
ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret );
ret.selector = this.selector ? this.selector + " " + selector : selector;
return ret;
},
has: function( target ) {
var targets = jQuery( target, this ),
l = targets.length;
return this.filter(function() {
var i = 0;
for ( ; i < l; i++ ) {
if ( jQuery.contains( this, targets[i] ) ) {
return true;
}
}
});
},
not: function( selector ) {
return this.pushStack( winnow(this, selector || [], true) );
},
filter: function( selector ) {
return this.pushStack( winnow(this, selector || [], false) );
},
is: function( selector ) {
return !!winnow(
this,
// If this is a positional/relative selector, check membership in the returned set
// so $("p:first").is("p:last") won't return true for a doc with two "p".
typeof selector === "string" && rneedsContext.test( selector ) ?
jQuery( selector ) :
selector || [],
false
).length;
},
closest: function( selectors, context ) {
var cur,
i = 0,
l = this.length,
matched = [],
pos = ( rneedsContext.test( selectors ) || typeof selectors !== "string" ) ?
jQuery( selectors, context || this.context ) :
0;
for ( ; i < l; i++ ) {
for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) {
// Always skip document fragments
if ( cur.nodeType < 11 && (pos ?
pos.index(cur) > -1 :
// Don't pass non-elements to Sizzle
cur.nodeType === 1 &&
jQuery.find.matchesSelector(cur, selectors)) ) {
cur = matched.push( cur );
break;
}
}
}
return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched );
},
// Determine the position of an element within
// the matched set of elements
index: function( elem ) {
// No argument, return index in parent
if ( !elem ) {
return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1;
}
// index in selector
if ( typeof elem === "string" ) {
return core_indexOf.call( jQuery( elem ), this[ 0 ] );
}
// Locate the position of the desired element
return core_indexOf.call( this,
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[ 0 ] : elem
);
},
add: function( selector, context ) {
var set = typeof selector === "string" ?
jQuery( selector, context ) :
jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ),
all = jQuery.merge( this.get(), set );
return this.pushStack( jQuery.unique(all) );
},
addBack: function( selector ) {
return this.add( selector == null ?
this.prevObject : this.prevObject.filter(selector)
);
}
});
function sibling( cur, dir ) {
while ( (cur = cur[dir]) && cur.nodeType !== 1 ) {}
return cur;
}
jQuery.each({
parent: function( elem ) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function( elem ) {
return jQuery.dir( elem, "parentNode" );
},
parentsUntil: function( elem, i, until ) {
return jQuery.dir( elem, "parentNode", until );
},
next: function( elem ) {
return sibling( elem, "nextSibling" );
},
prev: function( elem ) {
return sibling( elem, "previousSibling" );
},
nextAll: function( elem ) {
return jQuery.dir( elem, "nextSibling" );
},
prevAll: function( elem ) {
return jQuery.dir( elem, "previousSibling" );
},
nextUntil: function( elem, i, until ) {
return jQuery.dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
return jQuery.dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem );
},
children: function( elem ) {
return jQuery.sibling( elem.firstChild );
},
contents: function( elem ) {
return elem.contentDocument || jQuery.merge( [], elem.childNodes );
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
var matched = jQuery.map( this, fn, until );
if ( name.slice( -5 ) !== "Until" ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
matched = jQuery.filter( selector, matched );
}
if ( this.length > 1 ) {
// Remove duplicates
if ( !guaranteedUnique[ name ] ) {
jQuery.unique( matched );
}
// Reverse order for parents* and prev-derivatives
if ( rparentsprev.test( name ) ) {
matched.reverse();
}
}
return this.pushStack( matched );
};
});
jQuery.extend({
filter: function( expr, elems, not ) {
var elem = elems[ 0 ];
if ( not ) {
expr = ":not(" + expr + ")";
}
return elems.length === 1 && elem.nodeType === 1 ?
jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] :
jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) {
return elem.nodeType === 1;
}));
},
dir: function( elem, dir, until ) {
var matched = [],
truncate = until !== undefined;
while ( (elem = elem[ dir ]) && elem.nodeType !== 9 ) {
if ( elem.nodeType === 1 ) {
if ( truncate && jQuery( elem ).is( until ) ) {
break;
}
matched.push( elem );
}
}
return matched;
},
sibling: function( n, elem ) {
var matched = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
matched.push( n );
}
}
return matched;
}
});
// Implement the identical functionality for filter and not
function winnow( elements, qualifier, not ) {
if ( jQuery.isFunction( qualifier ) ) {
return jQuery.grep( elements, function( elem, i ) {
/* jshint -W018 */
return !!qualifier.call( elem, i, elem ) !== not;
});
}
if ( qualifier.nodeType ) {
return jQuery.grep( elements, function( elem ) {
return ( elem === qualifier ) !== not;
});
}
if ( typeof qualifier === "string" ) {
if ( isSimple.test( qualifier ) ) {
return jQuery.filter( qualifier, elements, not );
}
qualifier = jQuery.filter( qualifier, elements );
}
return jQuery.grep( elements, function( elem ) {
return ( core_indexOf.call( qualifier, elem ) >= 0 ) !== not;
});
}
var rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
rtagName = /<([\w:]+)/,
rhtml = /<|&#?\w+;/,
rnoInnerhtml = /<(?:script|style|link)/i,
manipulation_rcheckableType = /^(?:checkbox|radio)$/i,
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptType = /^$|\/(?:java|ecma)script/i,
rscriptTypeMasked = /^true\/(.*)/,
rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,
// We have to close these tags to support XHTML (#13200)
wrapMap = {
// Support: IE 9
option: [ 1, "<select multiple='multiple'>", "</select>" ],
thead: [ 1, "<table>", "</table>" ],
col: [ 2, "<table><colgroup>", "</colgroup></table>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
_default: [ 0, "", "" ]
};
// Support: IE 9
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
jQuery.fn.extend({
text: function( value ) {
return jQuery.access( this, function( value ) {
return value === undefined ?
jQuery.text( this ) :
this.empty().append( ( this[ 0 ] && this[ 0 ].ownerDocument || document ).createTextNode( value ) );
}, null, value, arguments.length );
},
append: function() {
return this.domManip( arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.appendChild( elem );
}
});
},
prepend: function() {
return this.domManip( arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.insertBefore( elem, target.firstChild );
}
});
},
before: function() {
return this.domManip( arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this );
}
});
},
after: function() {
return this.domManip( arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this.nextSibling );
}
});
},
// keepData is for internal use only--do not document
remove: function( selector, keepData ) {
var elem,
elems = selector ? jQuery.filter( selector, this ) : this,
i = 0;
for ( ; (elem = elems[i]) != null; i++ ) {
if ( !keepData && elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem ) );
}
if ( elem.parentNode ) {
if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) {
setGlobalEval( getAll( elem, "script" ) );
}
elem.parentNode.removeChild( elem );
}
}
return this;
},
empty: function() {
var elem,
i = 0;
for ( ; (elem = this[i]) != null; i++ ) {
if ( elem.nodeType === 1 ) {
// Prevent memory leaks
jQuery.cleanData( getAll( elem, false ) );
// Remove any remaining nodes
elem.textContent = "";
}
}
return this;
},
clone: function( dataAndEvents, deepDataAndEvents ) {
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map( function () {
return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
});
},
html: function( value ) {
return jQuery.access( this, function( value ) {
var elem = this[ 0 ] || {},
i = 0,
l = this.length;
if ( value === undefined && elem.nodeType === 1 ) {
return elem.innerHTML;
}
// See if we can take a shortcut and just use innerHTML
if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
!wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) {
value = value.replace( rxhtmlTag, "<$1></$2>" );
try {
for ( ; i < l; i++ ) {
elem = this[ i ] || {};
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem, false ) );
elem.innerHTML = value;
}
}
elem = 0;
// If using innerHTML throws an exception, use the fallback method
} catch( e ) {}
}
if ( elem ) {
this.empty().append( value );
}
}, null, value, arguments.length );
},
replaceWith: function() {
var
// Snapshot the DOM in case .domManip sweeps something relevant into its fragment
args = jQuery.map( this, function( elem ) {
return [ elem.nextSibling, elem.parentNode ];
}),
i = 0;
// Make the changes, replacing each context element with the new content
this.domManip( arguments, function( elem ) {
var next = args[ i++ ],
parent = args[ i++ ];
if ( parent ) {
// Don't use the snapshot next if it has moved (#13810)
if ( next && next.parentNode !== parent ) {
next = this.nextSibling;
}
jQuery( this ).remove();
parent.insertBefore( elem, next );
}
// Allow new content to include elements from the context set
}, true );
// Force removal if there was no new content (e.g., from empty arguments)
return i ? this : this.remove();
},
detach: function( selector ) {
return this.remove( selector, true );
},
domManip: function( args, callback, allowIntersection ) {
// Flatten any nested arrays
args = core_concat.apply( [], args );
var fragment, first, scripts, hasScripts, node, doc,
i = 0,
l = this.length,
set = this,
iNoClone = l - 1,
value = args[ 0 ],
isFunction = jQuery.isFunction( value );
// We can't cloneNode fragments that contain checked, in WebKit
if ( isFunction || !( l <= 1 || typeof value !== "string" || jQuery.support.checkClone || !rchecked.test( value ) ) ) {
return this.each(function( index ) {
var self = set.eq( index );
if ( isFunction ) {
args[ 0 ] = value.call( this, index, self.html() );
}
self.domManip( args, callback, allowIntersection );
});
}
if ( l ) {
fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, !allowIntersection && this );
first = fragment.firstChild;
if ( fragment.childNodes.length === 1 ) {
fragment = first;
}
if ( first ) {
scripts = jQuery.map( getAll( fragment, "script" ), disableScript );
hasScripts = scripts.length;
// Use the original fragment for the last item instead of the first because it can end up
// being emptied incorrectly in certain situations (#8070).
for ( ; i < l; i++ ) {
node = fragment;
if ( i !== iNoClone ) {
node = jQuery.clone( node, true, true );
// Keep references to cloned scripts for later restoration
if ( hasScripts ) {
// Support: QtWebKit
// jQuery.merge because core_push.apply(_, arraylike) throws
jQuery.merge( scripts, getAll( node, "script" ) );
}
}
callback.call( this[ i ], node, i );
}
if ( hasScripts ) {
doc = scripts[ scripts.length - 1 ].ownerDocument;
// Reenable scripts
jQuery.map( scripts, restoreScript );
// Evaluate executable scripts on first document insertion
for ( i = 0; i < hasScripts; i++ ) {
node = scripts[ i ];
if ( rscriptType.test( node.type || "" ) &&
!data_priv.access( node, "globalEval" ) && jQuery.contains( doc, node ) ) {
if ( node.src ) {
// Hope ajax is available...
jQuery._evalUrl( node.src );
} else {
jQuery.globalEval( node.textContent.replace( rcleanScript, "" ) );
}
}
}
}
}
}
return this;
}
});
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var elems,
ret = [],
insert = jQuery( selector ),
last = insert.length - 1,
i = 0;
for ( ; i <= last; i++ ) {
elems = i === last ? this : this.clone( true );
jQuery( insert[ i ] )[ original ]( elems );
// Support: QtWebKit
// .get() because core_push.apply(_, arraylike) throws
core_push.apply( ret, elems.get() );
}
return this.pushStack( ret );
};
});
jQuery.extend({
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var i, l, srcElements, destElements,
clone = elem.cloneNode( true ),
inPage = jQuery.contains( elem.ownerDocument, elem );
// Support: IE >= 9
// Fix Cloning issues
if ( !jQuery.support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && !jQuery.isXMLDoc( elem ) ) {
// We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2
destElements = getAll( clone );
srcElements = getAll( elem );
for ( i = 0, l = srcElements.length; i < l; i++ ) {
fixInput( srcElements[ i ], destElements[ i ] );
}
}
// Copy the events from the original to the clone
if ( dataAndEvents ) {
if ( deepDataAndEvents ) {
srcElements = srcElements || getAll( elem );
destElements = destElements || getAll( clone );
for ( i = 0, l = srcElements.length; i < l; i++ ) {
cloneCopyEvent( srcElements[ i ], destElements[ i ] );
}
} else {
cloneCopyEvent( elem, clone );
}
}
// Preserve script evaluation history
destElements = getAll( clone, "script" );
if ( destElements.length > 0 ) {
setGlobalEval( destElements, !inPage && getAll( elem, "script" ) );
}
// Return the cloned set
return clone;
},
buildFragment: function( elems, context, scripts, selection ) {
var elem, tmp, tag, wrap, contains, j,
i = 0,
l = elems.length,
fragment = context.createDocumentFragment(),
nodes = [];
for ( ; i < l; i++ ) {
elem = elems[ i ];
if ( elem || elem === 0 ) {
// Add nodes directly
if ( jQuery.type( elem ) === "object" ) {
// Support: QtWebKit
// jQuery.merge because core_push.apply(_, arraylike) throws
jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem );
// Convert non-html into a text node
} else if ( !rhtml.test( elem ) ) {
nodes.push( context.createTextNode( elem ) );
// Convert html into DOM nodes
} else {
tmp = tmp || fragment.appendChild( context.createElement("div") );
// Deserialize a standard representation
tag = ( rtagName.exec( elem ) || ["", ""] )[ 1 ].toLowerCase();
wrap = wrapMap[ tag ] || wrapMap._default;
tmp.innerHTML = wrap[ 1 ] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[ 2 ];
// Descend through wrappers to the right content
j = wrap[ 0 ];
while ( j-- ) {
tmp = tmp.lastChild;
}
// Support: QtWebKit
// jQuery.merge because core_push.apply(_, arraylike) throws
jQuery.merge( nodes, tmp.childNodes );
// Remember the top-level container
tmp = fragment.firstChild;
// Fixes #12346
// Support: Webkit, IE
tmp.textContent = "";
}
}
}
// Remove wrapper from fragment
fragment.textContent = "";
i = 0;
while ( (elem = nodes[ i++ ]) ) {
// #4087 - If origin and destination elements are the same, and this is
// that element, do not do anything
if ( selection && jQuery.inArray( elem, selection ) !== -1 ) {
continue;
}
contains = jQuery.contains( elem.ownerDocument, elem );
// Append to fragment
tmp = getAll( fragment.appendChild( elem ), "script" );
// Preserve script evaluation history
if ( contains ) {
setGlobalEval( tmp );
}
// Capture executables
if ( scripts ) {
j = 0;
while ( (elem = tmp[ j++ ]) ) {
if ( rscriptType.test( elem.type || "" ) ) {
scripts.push( elem );
}
}
}
}
return fragment;
},
cleanData: function( elems ) {
var data, elem, events, type, key, j,
special = jQuery.event.special,
i = 0;
for ( ; (elem = elems[ i ]) !== undefined; i++ ) {
if ( Data.accepts( elem ) ) {
key = elem[ data_priv.expando ];
if ( key && (data = data_priv.cache[ key ]) ) {
events = Object.keys( data.events || {} );
if ( events.length ) {
for ( j = 0; (type = events[j]) !== undefined; j++ ) {
if ( special[ type ] ) {
jQuery.event.remove( elem, type );
// This is a shortcut to avoid jQuery.event.remove's overhead
} else {
jQuery.removeEvent( elem, type, data.handle );
}
}
}
if ( data_priv.cache[ key ] ) {
// Discard any remaining `private` data
delete data_priv.cache[ key ];
}
}
}
// Discard any remaining `user` data
delete data_user.cache[ elem[ data_user.expando ] ];
}
},
_evalUrl: function( url ) {
return jQuery.ajax({
url: url,
type: "GET",
dataType: "script",
async: false,
global: false,
"throws": true
});
}
});
// Support: 1.x compatibility
// Manipulating tables requires a tbody
function manipulationTarget( elem, content ) {
return jQuery.nodeName( elem, "table" ) &&
jQuery.nodeName( content.nodeType === 1 ? content : content.firstChild, "tr" ) ?
elem.getElementsByTagName("tbody")[0] ||
elem.appendChild( elem.ownerDocument.createElement("tbody") ) :
elem;
}
// Replace/restore the type attribute of script elements for safe DOM manipulation
function disableScript( elem ) {
elem.type = (elem.getAttribute("type") !== null) + "/" + elem.type;
return elem;
}
function restoreScript( elem ) {
var match = rscriptTypeMasked.exec( elem.type );
if ( match ) {
elem.type = match[ 1 ];
} else {
elem.removeAttribute("type");
}
return elem;
}
// Mark scripts as having already been evaluated
function setGlobalEval( elems, refElements ) {
var l = elems.length,
i = 0;
for ( ; i < l; i++ ) {
data_priv.set(
elems[ i ], "globalEval", !refElements || data_priv.get( refElements[ i ], "globalEval" )
);
}
}
function cloneCopyEvent( src, dest ) {
var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events;
if ( dest.nodeType !== 1 ) {
return;
}
// 1. Copy private data: events, handlers, etc.
if ( data_priv.hasData( src ) ) {
pdataOld = data_priv.access( src );
pdataCur = data_priv.set( dest, pdataOld );
events = pdataOld.events;
if ( events ) {
delete pdataCur.handle;
pdataCur.events = {};
for ( type in events ) {
for ( i = 0, l = events[ type ].length; i < l; i++ ) {
jQuery.event.add( dest, type, events[ type ][ i ] );
}
}
}
}
// 2. Copy user data
if ( data_user.hasData( src ) ) {
udataOld = data_user.access( src );
udataCur = jQuery.extend( {}, udataOld );
data_user.set( dest, udataCur );
}
}
function getAll( context, tag ) {
var ret = context.getElementsByTagName ? context.getElementsByTagName( tag || "*" ) :
context.querySelectorAll ? context.querySelectorAll( tag || "*" ) :
[];
return tag === undefined || tag && jQuery.nodeName( context, tag ) ?
jQuery.merge( [ context ], ret ) :
ret;
}
// Support: IE >= 9
function fixInput( src, dest ) {
var nodeName = dest.nodeName.toLowerCase();
// Fails to persist the checked state of a cloned checkbox or radio button.
if ( nodeName === "input" && manipulation_rcheckableType.test( src.type ) ) {
dest.checked = src.checked;
// Fails to return the selected option to the default selected state when cloning options
} else if ( nodeName === "input" || nodeName === "textarea" ) {
dest.defaultValue = src.defaultValue;
}
}
jQuery.fn.extend({
wrapAll: function( html ) {
var wrap;
if ( jQuery.isFunction( html ) ) {
return this.each(function( i ) {
jQuery( this ).wrapAll( html.call(this, i) );
});
}
if ( this[ 0 ] ) {
// The elements to wrap the target around
wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true );
if ( this[ 0 ].parentNode ) {
wrap.insertBefore( this[ 0 ] );
}
wrap.map(function() {
var elem = this;
while ( elem.firstElementChild ) {
elem = elem.firstElementChild;
}
return elem;
}).append( this );
}
return this;
},
wrapInner: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function( i ) {
jQuery( this ).wrapInner( html.call(this, i) );
});
}
return this.each(function() {
var self = jQuery( this ),
contents = self.contents();
if ( contents.length ) {
contents.wrapAll( html );
} else {
self.append( html );
}
});
},
wrap: function( html ) {
var isFunction = jQuery.isFunction( html );
return this.each(function( i ) {
jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html );
});
},
unwrap: function() {
return this.parent().each(function() {
if ( !jQuery.nodeName( this, "body" ) ) {
jQuery( this ).replaceWith( this.childNodes );
}
}).end();
}
});
var curCSS, iframe,
// swappable if display is none or starts with table except "table", "table-cell", or "table-caption"
// see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
rdisplayswap = /^(none|table(?!-c[ea]).+)/,
rmargin = /^margin/,
rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ),
rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ),
rrelNum = new RegExp( "^([+-])=(" + core_pnum + ")", "i" ),
elemdisplay = { BODY: "block" },
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
cssNormalTransform = {
letterSpacing: 0,
fontWeight: 400
},
cssExpand = [ "Top", "Right", "Bottom", "Left" ],
cssPrefixes = [ "Webkit", "O", "Moz", "ms" ];
// return a css property mapped to a potentially vendor prefixed property
function vendorPropName( style, name ) {
// shortcut for names that are not vendor prefixed
if ( name in style ) {
return name;
}
// check for vendor prefixed names
var capName = name.charAt(0).toUpperCase() + name.slice(1),
origName = name,
i = cssPrefixes.length;
while ( i-- ) {
name = cssPrefixes[ i ] + capName;
if ( name in style ) {
return name;
}
}
return origName;
}
function isHidden( elem, el ) {
// isHidden might be called from jQuery#filter function;
// in that case, element will be second argument
elem = el || elem;
return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem );
}
// NOTE: we've included the "window" in window.getComputedStyle
// because jsdom on node.js will break without it.
function getStyles( elem ) {
return window.getComputedStyle( elem, null );
}
function showHide( elements, show ) {
var display, elem, hidden,
values = [],
index = 0,
length = elements.length;
for ( ; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
values[ index ] = data_priv.get( elem, "olddisplay" );
display = elem.style.display;
if ( show ) {
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
if ( !values[ index ] && display === "none" ) {
elem.style.display = "";
}
// Set elements which have been overridden with display: none
// in a stylesheet to whatever the default browser style is
// for such an element
if ( elem.style.display === "" && isHidden( elem ) ) {
values[ index ] = data_priv.access( elem, "olddisplay", css_defaultDisplay(elem.nodeName) );
}
} else {
if ( !values[ index ] ) {
hidden = isHidden( elem );
if ( display && display !== "none" || !hidden ) {
data_priv.set( elem, "olddisplay", hidden ? display : jQuery.css(elem, "display") );
}
}
}
}
// Set the display of most of the elements in a second loop
// to avoid the constant reflow
for ( index = 0; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
if ( !show || elem.style.display === "none" || elem.style.display === "" ) {
elem.style.display = show ? values[ index ] || "" : "none";
}
}
return elements;
}
jQuery.fn.extend({
css: function( name, value ) {
return jQuery.access( this, function( elem, name, value ) {
var styles, len,
map = {},
i = 0;
if ( jQuery.isArray( name ) ) {
styles = getStyles( elem );
len = name.length;
for ( ; i < len; i++ ) {
map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles );
}
return map;
}
return value !== undefined ?
jQuery.style( elem, name, value ) :
jQuery.css( elem, name );
}, name, value, arguments.length > 1 );
},
show: function() {
return showHide( this, true );
},
hide: function() {
return showHide( this );
},
toggle: function( state ) {
if ( typeof state === "boolean" ) {
return state ? this.show() : this.hide();
}
return this.each(function() {
if ( isHidden( this ) ) {
jQuery( this ).show();
} else {
jQuery( this ).hide();
}
});
}
});
jQuery.extend({
// Add in style property hooks for overriding the default
// behavior of getting and setting a style property
cssHooks: {
opacity: {
get: function( elem, computed ) {
if ( computed ) {
// We should always get a number back from opacity
var ret = curCSS( elem, "opacity" );
return ret === "" ? "1" : ret;
}
}
}
},
// Don't automatically add "px" to these possibly-unitless properties
cssNumber: {
"columnCount": true,
"fillOpacity": true,
"fontWeight": true,
"lineHeight": true,
"opacity": true,
"order": true,
"orphans": true,
"widows": true,
"zIndex": true,
"zoom": true
},
// Add in properties whose names you wish to fix before
// setting or getting the value
cssProps: {
// normalize float css property
"float": "cssFloat"
},
// Get and set the style property on a DOM Node
style: function( elem, name, value, extra ) {
// Don't set styles on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
return;
}
// Make sure that we're working with the right name
var ret, type, hooks,
origName = jQuery.camelCase( name ),
style = elem.style;
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// Check if we're setting a value
if ( value !== undefined ) {
type = typeof value;
// convert relative number strings (+= or -=) to relative numbers. #7345
if ( type === "string" && (ret = rrelNum.exec( value )) ) {
value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) );
// Fixes bug #9237
type = "number";
}
// Make sure that NaN and null values aren't set. See: #7116
if ( value == null || type === "number" && isNaN( value ) ) {
return;
}
// If a number was passed in, add 'px' to the (except for certain CSS properties)
if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
value += "px";
}
// Fixes #8908, it can be done more correctly by specifying setters in cssHooks,
// but it would mean to define eight (for every problematic property) identical functions
if ( !jQuery.support.clearCloneStyle && value === "" && name.indexOf("background") === 0 ) {
style[ name ] = "inherit";
}
// If a hook was provided, use that value, otherwise just set the specified value
if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) {
style[ name ] = value;
}
} else {
// If a hook was provided get the non-computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {
return ret;
}
// Otherwise just get the value from the style object
return style[ name ];
}
},
css: function( elem, name, extra, styles ) {
var val, num, hooks,
origName = jQuery.camelCase( name );
// Make sure that we're working with the right name
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// If a hook was provided get the computed value from there
if ( hooks && "get" in hooks ) {
val = hooks.get( elem, true, extra );
}
// Otherwise, if a way to get the computed value exists, use that
if ( val === undefined ) {
val = curCSS( elem, name, styles );
}
//convert "normal" to computed value
if ( val === "normal" && name in cssNormalTransform ) {
val = cssNormalTransform[ name ];
}
// Return, converting to number if forced or a qualifier was provided and val looks numeric
if ( extra === "" || extra ) {
num = parseFloat( val );
return extra === true || jQuery.isNumeric( num ) ? num || 0 : val;
}
return val;
}
});
curCSS = function( elem, name, _computed ) {
var width, minWidth, maxWidth,
computed = _computed || getStyles( elem ),
// Support: IE9
// getPropertyValue is only needed for .css('filter') in IE9, see #12537
ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined,
style = elem.style;
if ( computed ) {
if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) {
ret = jQuery.style( elem, name );
}
// Support: Safari 5.1
// A tribute to the "awesome hack by Dean Edwards"
// Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels
// this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values
if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) {
// Remember the original values
width = style.width;
minWidth = style.minWidth;
maxWidth = style.maxWidth;
// Put in the new values to get a computed value out
style.minWidth = style.maxWidth = style.width = ret;
ret = computed.width;
// Revert the changed values
style.width = width;
style.minWidth = minWidth;
style.maxWidth = maxWidth;
}
}
return ret;
};
function setPositiveNumber( elem, value, subtract ) {
var matches = rnumsplit.exec( value );
return matches ?
// Guard against undefined "subtract", e.g., when used as in cssHooks
Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) :
value;
}
function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) {
var i = extra === ( isBorderBox ? "border" : "content" ) ?
// If we already have the right measurement, avoid augmentation
4 :
// Otherwise initialize for horizontal or vertical properties
name === "width" ? 1 : 0,
val = 0;
for ( ; i < 4; i += 2 ) {
// both box models exclude margin, so add it if we want it
if ( extra === "margin" ) {
val += jQuery.css( elem, extra + cssExpand[ i ], true, styles );
}
if ( isBorderBox ) {
// border-box includes padding, so remove it if we want content
if ( extra === "content" ) {
val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
}
// at this point, extra isn't border nor margin, so remove border
if ( extra !== "margin" ) {
val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
} else {
// at this point, extra isn't content, so add padding
val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
// at this point, extra isn't content nor padding, so add border
if ( extra !== "padding" ) {
val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
}
}
return val;
}
function getWidthOrHeight( elem, name, extra ) {
// Start with offset property, which is equivalent to the border-box value
var valueIsBorderBox = true,
val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
styles = getStyles( elem ),
isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box";
// some non-html elements return undefined for offsetWidth, so check for null/undefined
// svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285
// MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668
if ( val <= 0 || val == null ) {
// Fall back to computed then uncomputed css if necessary
val = curCSS( elem, name, styles );
if ( val < 0 || val == null ) {
val = elem.style[ name ];
}
// Computed unit is not pixels. Stop here and return.
if ( rnumnonpx.test(val) ) {
return val;
}
// we need the check for style in case a browser which returns unreliable values
// for getComputedStyle silently falls back to the reliable elem.style
valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] );
// Normalize "", auto, and prepare for extra
val = parseFloat( val ) || 0;
}
// use the active box-sizing model to add/subtract irrelevant styles
return ( val +
augmentWidthOrHeight(
elem,
name,
extra || ( isBorderBox ? "border" : "content" ),
valueIsBorderBox,
styles
)
) + "px";
}
// Try to determine the default display value of an element
function css_defaultDisplay( nodeName ) {
var doc = document,
display = elemdisplay[ nodeName ];
if ( !display ) {
display = actualDisplay( nodeName, doc );
// If the simple way fails, read from inside an iframe
if ( display === "none" || !display ) {
// Use the already-created iframe if possible
iframe = ( iframe ||
jQuery("<iframe frameborder='0' width='0' height='0'/>")
.css( "cssText", "display:block !important" )
).appendTo( doc.documentElement );
// Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse
doc = ( iframe[0].contentWindow || iframe[0].contentDocument ).document;
doc.write("<!doctype html><html><body>");
doc.close();
display = actualDisplay( nodeName, doc );
iframe.detach();
}
// Store the correct default display
elemdisplay[ nodeName ] = display;
}
return display;
}
// Called ONLY from within css_defaultDisplay
function actualDisplay( name, doc ) {
var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ),
display = jQuery.css( elem[0], "display" );
elem.remove();
return display;
}
jQuery.each([ "height", "width" ], function( i, name ) {
jQuery.cssHooks[ name ] = {
get: function( elem, computed, extra ) {
if ( computed ) {
// certain elements can have dimension info if we invisibly show them
// however, it must have a current display style that would benefit from this
return elem.offsetWidth === 0 && rdisplayswap.test( jQuery.css( elem, "display" ) ) ?
jQuery.swap( elem, cssShow, function() {
return getWidthOrHeight( elem, name, extra );
}) :
getWidthOrHeight( elem, name, extra );
}
},
set: function( elem, value, extra ) {
var styles = extra && getStyles( elem );
return setPositiveNumber( elem, value, extra ?
augmentWidthOrHeight(
elem,
name,
extra,
jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
styles
) : 0
);
}
};
});
// These hooks cannot be added until DOM ready because the support test
// for it is not run until after DOM ready
jQuery(function() {
// Support: Android 2.3
if ( !jQuery.support.reliableMarginRight ) {
jQuery.cssHooks.marginRight = {
get: function( elem, computed ) {
if ( computed ) {
// Support: Android 2.3
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
// Work around by temporarily setting element display to inline-block
return jQuery.swap( elem, { "display": "inline-block" },
curCSS, [ elem, "marginRight" ] );
}
}
};
}
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
// getComputedStyle returns percent when specified for top/left/bottom/right
// rather than make the css module depend on the offset module, we just check for it here
if ( !jQuery.support.pixelPosition && jQuery.fn.position ) {
jQuery.each( [ "top", "left" ], function( i, prop ) {
jQuery.cssHooks[ prop ] = {
get: function( elem, computed ) {
if ( computed ) {
computed = curCSS( elem, prop );
// if curCSS returns percentage, fallback to offset
return rnumnonpx.test( computed ) ?
jQuery( elem ).position()[ prop ] + "px" :
computed;
}
}
};
});
}
});
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.hidden = function( elem ) {
// Support: Opera <= 12.12
// Opera reports offsetWidths and offsetHeights less than zero on some elements
return elem.offsetWidth <= 0 && elem.offsetHeight <= 0;
};
jQuery.expr.filters.visible = function( elem ) {
return !jQuery.expr.filters.hidden( elem );
};
}
// These hooks are used by animate to expand properties
jQuery.each({
margin: "",
padding: "",
border: "Width"
}, function( prefix, suffix ) {
jQuery.cssHooks[ prefix + suffix ] = {
expand: function( value ) {
var i = 0,
expanded = {},
// assumes a single number if not a string
parts = typeof value === "string" ? value.split(" ") : [ value ];
for ( ; i < 4; i++ ) {
expanded[ prefix + cssExpand[ i ] + suffix ] =
parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
}
return expanded;
}
};
if ( !rmargin.test( prefix ) ) {
jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;
}
});
var r20 = /%20/g,
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
rsubmittable = /^(?:input|select|textarea|keygen)/i;
jQuery.fn.extend({
serialize: function() {
return jQuery.param( this.serializeArray() );
},
serializeArray: function() {
return this.map(function(){
// Can add propHook for "elements" to filter or add form elements
var elements = jQuery.prop( this, "elements" );
return elements ? jQuery.makeArray( elements ) : this;
})
.filter(function(){
var type = this.type;
// Use .is(":disabled") so that fieldset[disabled] works
return this.name && !jQuery( this ).is( ":disabled" ) &&
rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) &&
( this.checked || !manipulation_rcheckableType.test( type ) );
})
.map(function( i, elem ){
var val = jQuery( this ).val();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val ){
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}).get();
}
});
//Serialize an array of form elements or a set of
//key/values into a query string
jQuery.param = function( a, traditional ) {
var prefix,
s = [],
add = function( key, value ) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value );
s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
}
// If an array was passed in, assume that it is an array of form elements.
if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
// Serialize the form elements
jQuery.each( a, function() {
add( this.name, this.value );
});
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for ( prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
}
// Return the resulting serialization
return s.join( "&" ).replace( r20, "+" );
};
function buildParams( prefix, obj, traditional, add ) {
var name;
if ( jQuery.isArray( obj ) ) {
// Serialize array item.
jQuery.each( obj, function( i, v ) {
if ( traditional || rbracket.test( prefix ) ) {
// Treat each array item as a scalar.
add( prefix, v );
} else {
// Item is non-scalar (array or object), encode its numeric index.
buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add );
}
});
} else if ( !traditional && jQuery.type( obj ) === "object" ) {
// Serialize object item.
for ( name in obj ) {
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
}
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) {
// Handle event binding
jQuery.fn[ name ] = function( data, fn ) {
return arguments.length > 0 ?
this.on( name, null, data, fn ) :
this.trigger( name );
};
});
jQuery.fn.extend({
hover: function( fnOver, fnOut ) {
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
},
bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
unbind: function( types, fn ) {
return this.off( types, null, fn );
},
delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
},
undelegate: function( selector, types, fn ) {
// ( namespace ) or ( selector, types [, fn] )
return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn );
}
});
var
// Document location
ajaxLocParts,
ajaxLocation,
ajax_nonce = jQuery.now(),
ajax_rquery = /\?/,
rhash = /#.*$/,
rts = /([?&])_=[^&]*/,
rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg,
// #7653, #8125, #8152: local protocol detection
rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
rnoContent = /^(?:GET|HEAD)$/,
rprotocol = /^\/\//,
rurl = /^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,
// Keep a copy of the old load method
_load = jQuery.fn.load,
/* Prefilters
* 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
* 2) These are called:
* - BEFORE asking for a transport
* - AFTER param serialization (s.data is a string if s.processData is true)
* 3) key is the dataType
* 4) the catchall symbol "*" can be used
* 5) execution will start with transport dataType and THEN continue down to "*" if needed
*/
prefilters = {},
/* Transports bindings
* 1) key is the dataType
* 2) the catchall symbol "*" can be used
* 3) selection will start with transport dataType and THEN go to "*" if needed
*/
transports = {},
// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
allTypes = "*/".concat("*");
// #8138, IE may throw an exception when accessing
// a field from window.location if document.domain has been set
try {
ajaxLocation = location.href;
} catch( e ) {
// Use the href attribute of an A element
// since IE will modify it given document.location
ajaxLocation = document.createElement( "a" );
ajaxLocation.href = "";
ajaxLocation = ajaxLocation.href;
}
// Segment location into parts
ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];
// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
function addToPrefiltersOrTransports( structure ) {
// dataTypeExpression is optional and defaults to "*"
return function( dataTypeExpression, func ) {
if ( typeof dataTypeExpression !== "string" ) {
func = dataTypeExpression;
dataTypeExpression = "*";
}
var dataType,
i = 0,
dataTypes = dataTypeExpression.toLowerCase().match( core_rnotwhite ) || [];
if ( jQuery.isFunction( func ) ) {
// For each dataType in the dataTypeExpression
while ( (dataType = dataTypes[i++]) ) {
// Prepend if requested
if ( dataType[0] === "+" ) {
dataType = dataType.slice( 1 ) || "*";
(structure[ dataType ] = structure[ dataType ] || []).unshift( func );
// Otherwise append
} else {
(structure[ dataType ] = structure[ dataType ] || []).push( func );
}
}
}
};
}
// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) {
var inspected = {},
seekingTransport = ( structure === transports );
function inspect( dataType ) {
var selected;
inspected[ dataType ] = true;
jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) {
var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR );
if( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) {
options.dataTypes.unshift( dataTypeOrTransport );
inspect( dataTypeOrTransport );
return false;
} else if ( seekingTransport ) {
return !( selected = dataTypeOrTransport );
}
});
return selected;
}
return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" );
}
// A special extend for ajax options
// that takes "flat" options (not to be deep extended)
// Fixes #9887
function ajaxExtend( target, src ) {
var key, deep,
flatOptions = jQuery.ajaxSettings.flatOptions || {};
for ( key in src ) {
if ( src[ key ] !== undefined ) {
( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ];
}
}
if ( deep ) {
jQuery.extend( true, target, deep );
}
return target;
}
jQuery.fn.load = function( url, params, callback ) {
if ( typeof url !== "string" && _load ) {
return _load.apply( this, arguments );
}
var selector, type, response,
self = this,
off = url.indexOf(" ");
if ( off >= 0 ) {
selector = url.slice( off );
url = url.slice( 0, off );
}
// If it's a function
if ( jQuery.isFunction( params ) ) {
// We assume that it's the callback
callback = params;
params = undefined;
// Otherwise, build a param string
} else if ( params && typeof params === "object" ) {
type = "POST";
}
// If we have elements to modify, make the request
if ( self.length > 0 ) {
jQuery.ajax({
url: url,
// if "type" variable is undefined, then "GET" method will be used
type: type,
dataType: "html",
data: params
}).done(function( responseText ) {
// Save response for use in complete callback
response = arguments;
self.html( selector ?
// If a selector was specified, locate the right elements in a dummy div
// Exclude scripts to avoid IE 'Permission Denied' errors
jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) :
// Otherwise use the full result
responseText );
}).complete( callback && function( jqXHR, status ) {
self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] );
});
}
return this;
};
// Attach a bunch of functions for handling common AJAX events
jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ){
jQuery.fn[ type ] = function( fn ){
return this.on( type, fn );
};
});
jQuery.extend({
// Counter for holding the number of active queries
active: 0,
// Last-Modified header cache for next request
lastModified: {},
etag: {},
ajaxSettings: {
url: ajaxLocation,
type: "GET",
isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
global: true,
processData: true,
async: true,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
/*
timeout: 0,
data: null,
dataType: null,
username: null,
password: null,
cache: null,
throws: false,
traditional: false,
headers: {},
*/
accepts: {
"*": allTypes,
text: "text/plain",
html: "text/html",
xml: "application/xml, text/xml",
json: "application/json, text/javascript"
},
contents: {
xml: /xml/,
html: /html/,
json: /json/
},
responseFields: {
xml: "responseXML",
text: "responseText",
json: "responseJSON"
},
// Data converters
// Keys separate source (or catchall "*") and destination types with a single space
converters: {
// Convert anything to text
"* text": String,
// Text to html (true = no transformation)
"text html": true,
// Evaluate text as a json expression
"text json": jQuery.parseJSON,
// Parse text as xml
"text xml": jQuery.parseXML
},
// For options that shouldn't be deep extended:
// you can add your own custom options here if
// and when you create one that shouldn't be
// deep extended (see ajaxExtend)
flatOptions: {
url: true,
context: true
}
},
// Creates a full fledged settings object into target
// with both ajaxSettings and settings fields.
// If target is omitted, writes into ajaxSettings.
ajaxSetup: function( target, settings ) {
return settings ?
// Building a settings object
ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) :
// Extending ajaxSettings
ajaxExtend( jQuery.ajaxSettings, target );
},
ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
ajaxTransport: addToPrefiltersOrTransports( transports ),
// Main method
ajax: function( url, options ) {
// If url is an object, simulate pre-1.5 signature
if ( typeof url === "object" ) {
options = url;
url = undefined;
}
// Force options to be an object
options = options || {};
var transport,
// URL without anti-cache param
cacheURL,
// Response headers
responseHeadersString,
responseHeaders,
// timeout handle
timeoutTimer,
// Cross-domain detection vars
parts,
// To know if global events are to be dispatched
fireGlobals,
// Loop variable
i,
// Create the final options object
s = jQuery.ajaxSetup( {}, options ),
// Callbacks context
callbackContext = s.context || s,
// Context for global events is callbackContext if it is a DOM node or jQuery collection
globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ?
jQuery( callbackContext ) :
jQuery.event,
// Deferreds
deferred = jQuery.Deferred(),
completeDeferred = jQuery.Callbacks("once memory"),
// Status-dependent callbacks
statusCode = s.statusCode || {},
// Headers (they are sent all at once)
requestHeaders = {},
requestHeadersNames = {},
// The jqXHR state
state = 0,
// Default abort message
strAbort = "canceled",
// Fake xhr
jqXHR = {
readyState: 0,
// Builds headers hashtable if needed
getResponseHeader: function( key ) {
var match;
if ( state === 2 ) {
if ( !responseHeaders ) {
responseHeaders = {};
while ( (match = rheaders.exec( responseHeadersString )) ) {
responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
}
}
match = responseHeaders[ key.toLowerCase() ];
}
return match == null ? null : match;
},
// Raw string
getAllResponseHeaders: function() {
return state === 2 ? responseHeadersString : null;
},
// Caches the header
setRequestHeader: function( name, value ) {
var lname = name.toLowerCase();
if ( !state ) {
name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
requestHeaders[ name ] = value;
}
return this;
},
// Overrides response content-type header
overrideMimeType: function( type ) {
if ( !state ) {
s.mimeType = type;
}
return this;
},
// Status-dependent callbacks
statusCode: function( map ) {
var code;
if ( map ) {
if ( state < 2 ) {
for ( code in map ) {
// Lazy-add the new callback in a way that preserves old ones
statusCode[ code ] = [ statusCode[ code ], map[ code ] ];
}
} else {
// Execute the appropriate callbacks
jqXHR.always( map[ jqXHR.status ] );
}
}
return this;
},
// Cancel the request
abort: function( statusText ) {
var finalText = statusText || strAbort;
if ( transport ) {
transport.abort( finalText );
}
done( 0, finalText );
return this;
}
};
// Attach deferreds
deferred.promise( jqXHR ).complete = completeDeferred.add;
jqXHR.success = jqXHR.done;
jqXHR.error = jqXHR.fail;
// Remove hash character (#7531: and string promotion)
// Add protocol if not provided (prefilters might expect it)
// Handle falsy url in the settings object (#10093: consistency with old signature)
// We also use the url parameter if available
s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" )
.replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
// Alias method option to type as per ticket #12004
s.type = options.method || options.type || s.method || s.type;
// Extract dataTypes list
s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( core_rnotwhite ) || [""];
// A cross-domain request is in order when we have a protocol:host:port mismatch
if ( s.crossDomain == null ) {
parts = rurl.exec( s.url.toLowerCase() );
s.crossDomain = !!( parts &&
( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] ||
( parts[ 3 ] || ( parts[ 1 ] === "http:" ? "80" : "443" ) ) !==
( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? "80" : "443" ) ) )
);
}
// Convert data if not already a string
if ( s.data && s.processData && typeof s.data !== "string" ) {
s.data = jQuery.param( s.data, s.traditional );
}
// Apply prefilters
inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
// If request was aborted inside a prefilter, stop there
if ( state === 2 ) {
return jqXHR;
}
// We can fire global events as of now if asked to
fireGlobals = s.global;
// Watch for a new set of requests
if ( fireGlobals && jQuery.active++ === 0 ) {
jQuery.event.trigger("ajaxStart");
}
// Uppercase the type
s.type = s.type.toUpperCase();
// Determine if request has content
s.hasContent = !rnoContent.test( s.type );
// Save the URL in case we're toying with the If-Modified-Since
// and/or If-None-Match header later on
cacheURL = s.url;
// More options handling for requests with no content
if ( !s.hasContent ) {
// If data is available, append data to url
if ( s.data ) {
cacheURL = ( s.url += ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + s.data );
// #9682: remove data so that it's not used in an eventual retry
delete s.data;
}
// Add anti-cache in url if needed
if ( s.cache === false ) {
s.url = rts.test( cacheURL ) ?
// If there is already a '_' parameter, set its value
cacheURL.replace( rts, "$1_=" + ajax_nonce++ ) :
// Otherwise add one to the end
cacheURL + ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ajax_nonce++;
}
}
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
if ( jQuery.lastModified[ cacheURL ] ) {
jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] );
}
if ( jQuery.etag[ cacheURL ] ) {
jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] );
}
}
// Set the correct header, if data is being sent
if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
jqXHR.setRequestHeader( "Content-Type", s.contentType );
}
// Set the Accepts header for the server, depending on the dataType
jqXHR.setRequestHeader(
"Accept",
s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
s.accepts[ "*" ]
);
// Check for headers option
for ( i in s.headers ) {
jqXHR.setRequestHeader( i, s.headers[ i ] );
}
// Allow custom headers/mimetypes and early abort
if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
// Abort if not done already and return
return jqXHR.abort();
}
// aborting is no longer a cancellation
strAbort = "abort";
// Install callbacks on deferreds
for ( i in { success: 1, error: 1, complete: 1 } ) {
jqXHR[ i ]( s[ i ] );
}
// Get transport
transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
// If no transport, we auto-abort
if ( !transport ) {
done( -1, "No Transport" );
} else {
jqXHR.readyState = 1;
// Send global event
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
}
// Timeout
if ( s.async && s.timeout > 0 ) {
timeoutTimer = setTimeout(function() {
jqXHR.abort("timeout");
}, s.timeout );
}
try {
state = 1;
transport.send( requestHeaders, done );
} catch ( e ) {
// Propagate exception as error if not done
if ( state < 2 ) {
done( -1, e );
// Simply rethrow otherwise
} else {
throw e;
}
}
}
// Callback for when everything is done
function done( status, nativeStatusText, responses, headers ) {
var isSuccess, success, error, response, modified,
statusText = nativeStatusText;
// Called once
if ( state === 2 ) {
return;
}
// State is "done" now
state = 2;
// Clear timeout if it exists
if ( timeoutTimer ) {
clearTimeout( timeoutTimer );
}
// Dereference transport for early garbage collection
// (no matter how long the jqXHR object will be used)
transport = undefined;
// Cache response headers
responseHeadersString = headers || "";
// Set readyState
jqXHR.readyState = status > 0 ? 4 : 0;
// Determine if successful
isSuccess = status >= 200 && status < 300 || status === 304;
// Get response data
if ( responses ) {
response = ajaxHandleResponses( s, jqXHR, responses );
}
// Convert no matter what (that way responseXXX fields are always set)
response = ajaxConvert( s, response, jqXHR, isSuccess );
// If successful, handle type chaining
if ( isSuccess ) {
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
modified = jqXHR.getResponseHeader("Last-Modified");
if ( modified ) {
jQuery.lastModified[ cacheURL ] = modified;
}
modified = jqXHR.getResponseHeader("etag");
if ( modified ) {
jQuery.etag[ cacheURL ] = modified;
}
}
// if no content
if ( status === 204 || s.type === "HEAD" ) {
statusText = "nocontent";
// if not modified
} else if ( status === 304 ) {
statusText = "notmodified";
// If we have data, let's convert it
} else {
statusText = response.state;
success = response.data;
error = response.error;
isSuccess = !error;
}
} else {
// We extract error from statusText
// then normalize statusText and status for non-aborts
error = statusText;
if ( status || !statusText ) {
statusText = "error";
if ( status < 0 ) {
status = 0;
}
}
}
// Set data for the fake xhr object
jqXHR.status = status;
jqXHR.statusText = ( nativeStatusText || statusText ) + "";
// Success/Error
if ( isSuccess ) {
deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
} else {
deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
}
// Status-dependent callbacks
jqXHR.statusCode( statusCode );
statusCode = undefined;
if ( fireGlobals ) {
globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError",
[ jqXHR, s, isSuccess ? success : error ] );
}
// Complete
completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
// Handle the global AJAX counter
if ( !( --jQuery.active ) ) {
jQuery.event.trigger("ajaxStop");
}
}
}
return jqXHR;
},
getJSON: function( url, data, callback ) {
return jQuery.get( url, data, callback, "json" );
},
getScript: function( url, callback ) {
return jQuery.get( url, undefined, callback, "script" );
}
});
jQuery.each( [ "get", "post" ], function( i, method ) {
jQuery[ method ] = function( url, data, callback, type ) {
// shift arguments if data argument was omitted
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = undefined;
}
return jQuery.ajax({
url: url,
type: method,
dataType: type,
data: data,
success: callback
});
};
});
/* Handles responses to an ajax request:
* - finds the right dataType (mediates between content-type and expected dataType)
* - returns the corresponding response
*/
function ajaxHandleResponses( s, jqXHR, responses ) {
var ct, type, finalDataType, firstDataType,
contents = s.contents,
dataTypes = s.dataTypes;
// Remove auto dataType and get content-type in the process
while( dataTypes[ 0 ] === "*" ) {
dataTypes.shift();
if ( ct === undefined ) {
ct = s.mimeType || jqXHR.getResponseHeader("Content-Type");
}
}
// Check if we're dealing with a known content-type
if ( ct ) {
for ( type in contents ) {
if ( contents[ type ] && contents[ type ].test( ct ) ) {
dataTypes.unshift( type );
break;
}
}
}
// Check to see if we have a response for the expected dataType
if ( dataTypes[ 0 ] in responses ) {
finalDataType = dataTypes[ 0 ];
} else {
// Try convertible dataTypes
for ( type in responses ) {
if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
finalDataType = type;
break;
}
if ( !firstDataType ) {
firstDataType = type;
}
}
// Or just use first one
finalDataType = finalDataType || firstDataType;
}
// If we found a dataType
// We add the dataType to the list if needed
// and return the corresponding response
if ( finalDataType ) {
if ( finalDataType !== dataTypes[ 0 ] ) {
dataTypes.unshift( finalDataType );
}
return responses[ finalDataType ];
}
}
/* Chain conversions given the request and the original response
* Also sets the responseXXX fields on the jqXHR instance
*/
function ajaxConvert( s, response, jqXHR, isSuccess ) {
var conv2, current, conv, tmp, prev,
converters = {},
// Work with a copy of dataTypes in case we need to modify it for conversion
dataTypes = s.dataTypes.slice();
// Create converters map with lowercased keys
if ( dataTypes[ 1 ] ) {
for ( conv in s.converters ) {
converters[ conv.toLowerCase() ] = s.converters[ conv ];
}
}
current = dataTypes.shift();
// Convert to each sequential dataType
while ( current ) {
if ( s.responseFields[ current ] ) {
jqXHR[ s.responseFields[ current ] ] = response;
}
// Apply the dataFilter if provided
if ( !prev && isSuccess && s.dataFilter ) {
response = s.dataFilter( response, s.dataType );
}
prev = current;
current = dataTypes.shift();
if ( current ) {
// There's only work to do if current dataType is non-auto
if ( current === "*" ) {
current = prev;
// Convert response if prev dataType is non-auto and differs from current
} else if ( prev !== "*" && prev !== current ) {
// Seek a direct converter
conv = converters[ prev + " " + current ] || converters[ "* " + current ];
// If none found, seek a pair
if ( !conv ) {
for ( conv2 in converters ) {
// If conv2 outputs current
tmp = conv2.split( " " );
if ( tmp[ 1 ] === current ) {
// If prev can be converted to accepted input
conv = converters[ prev + " " + tmp[ 0 ] ] ||
converters[ "* " + tmp[ 0 ] ];
if ( conv ) {
// Condense equivalence converters
if ( conv === true ) {
conv = converters[ conv2 ];
// Otherwise, insert the intermediate dataType
} else if ( converters[ conv2 ] !== true ) {
current = tmp[ 0 ];
dataTypes.unshift( tmp[ 1 ] );
}
break;
}
}
}
}
// Apply converter (if not an equivalence)
if ( conv !== true ) {
// Unless errors are allowed to bubble, catch and return them
if ( conv && s[ "throws" ] ) {
response = conv( response );
} else {
try {
response = conv( response );
} catch ( e ) {
return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current };
}
}
}
}
}
}
return { state: "success", data: response };
}
// Install script dataType
jQuery.ajaxSetup({
accepts: {
script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
},
contents: {
script: /(?:java|ecma)script/
},
converters: {
"text script": function( text ) {
jQuery.globalEval( text );
return text;
}
}
});
// Handle cache's special case and crossDomain
jQuery.ajaxPrefilter( "script", function( s ) {
if ( s.cache === undefined ) {
s.cache = false;
}
if ( s.crossDomain ) {
s.type = "GET";
}
});
// Bind script tag hack transport
jQuery.ajaxTransport( "script", function( s ) {
// This transport only deals with cross domain requests
if ( s.crossDomain ) {
var script, callback;
return {
send: function( _, complete ) {
script = jQuery("<script>").prop({
async: true,
charset: s.scriptCharset,
src: s.url
}).on(
"load error",
callback = function( evt ) {
script.remove();
callback = null;
if ( evt ) {
complete( evt.type === "error" ? 404 : 200, evt.type );
}
}
);
document.head.appendChild( script[ 0 ] );
},
abort: function() {
if ( callback ) {
callback();
}
}
};
}
});
var oldCallbacks = [],
rjsonp = /(=)\?(?=&|$)|\?\?/;
// Default jsonp settings
jQuery.ajaxSetup({
jsonp: "callback",
jsonpCallback: function() {
var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( ajax_nonce++ ) );
this[ callback ] = true;
return callback;
}
});
// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
var callbackName, overwritten, responseContainer,
jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ?
"url" :
typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data"
);
// Handle iff the expected data type is "jsonp" or we have a parameter to set
if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) {
// Get callback name, remembering preexisting value associated with it
callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ?
s.jsonpCallback() :
s.jsonpCallback;
// Insert callback into url or form data
if ( jsonProp ) {
s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName );
} else if ( s.jsonp !== false ) {
s.url += ( ajax_rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName;
}
// Use data converter to retrieve json after script execution
s.converters["script json"] = function() {
if ( !responseContainer ) {
jQuery.error( callbackName + " was not called" );
}
return responseContainer[ 0 ];
};
// force json dataType
s.dataTypes[ 0 ] = "json";
// Install callback
overwritten = window[ callbackName ];
window[ callbackName ] = function() {
responseContainer = arguments;
};
// Clean-up function (fires after converters)
jqXHR.always(function() {
// Restore preexisting value
window[ callbackName ] = overwritten;
// Save back as free
if ( s[ callbackName ] ) {
// make sure that re-using the options doesn't screw things around
s.jsonpCallback = originalSettings.jsonpCallback;
// save the callback name for future use
oldCallbacks.push( callbackName );
}
// Call if it was a function and we have a response
if ( responseContainer && jQuery.isFunction( overwritten ) ) {
overwritten( responseContainer[ 0 ] );
}
responseContainer = overwritten = undefined;
});
// Delegate to script
return "script";
}
});
jQuery.ajaxSettings.xhr = function() {
try {
return new XMLHttpRequest();
} catch( e ) {}
};
var xhrSupported = jQuery.ajaxSettings.xhr(),
xhrSuccessStatus = {
// file protocol always yields status code 0, assume 200
0: 200,
// Support: IE9
// #1450: sometimes IE returns 1223 when it should be 204
1223: 204
},
// Support: IE9
// We need to keep track of outbound xhr and abort them manually
// because IE is not smart enough to do it all by itself
xhrId = 0,
xhrCallbacks = {};
if ( window.ActiveXObject ) {
jQuery( window ).on( "unload", function() {
for( var key in xhrCallbacks ) {
xhrCallbacks[ key ]();
}
xhrCallbacks = undefined;
});
}
jQuery.support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
jQuery.support.ajax = xhrSupported = !!xhrSupported;
jQuery.ajaxTransport(function( options ) {
var callback;
// Cross domain only allowed if supported through XMLHttpRequest
if ( jQuery.support.cors || xhrSupported && !options.crossDomain ) {
return {
send: function( headers, complete ) {
var i, id,
xhr = options.xhr();
xhr.open( options.type, options.url, options.async, options.username, options.password );
// Apply custom fields if provided
if ( options.xhrFields ) {
for ( i in options.xhrFields ) {
xhr[ i ] = options.xhrFields[ i ];
}
}
// Override mime type if needed
if ( options.mimeType && xhr.overrideMimeType ) {
xhr.overrideMimeType( options.mimeType );
}
// X-Requested-With header
// For cross-domain requests, seeing as conditions for a preflight are
// akin to a jigsaw puzzle, we simply never set it to be sure.
// (it can always be set on a per-request basis or even using ajaxSetup)
// For same-domain requests, won't change header if already provided.
if ( !options.crossDomain && !headers["X-Requested-With"] ) {
headers["X-Requested-With"] = "XMLHttpRequest";
}
// Set headers
for ( i in headers ) {
xhr.setRequestHeader( i, headers[ i ] );
}
// Callback
callback = function( type ) {
return function() {
if ( callback ) {
delete xhrCallbacks[ id ];
callback = xhr.onload = xhr.onerror = null;
if ( type === "abort" ) {
xhr.abort();
} else if ( type === "error" ) {
complete(
// file protocol always yields status 0, assume 404
xhr.status || 404,
xhr.statusText
);
} else {
complete(
xhrSuccessStatus[ xhr.status ] || xhr.status,
xhr.statusText,
// Support: IE9
// #11426: When requesting binary data, IE9 will throw an exception
// on any attempt to access responseText
typeof xhr.responseText === "string" ? {
text: xhr.responseText
} : undefined,
xhr.getAllResponseHeaders()
);
}
}
};
};
// Listen to events
xhr.onload = callback();
xhr.onerror = callback("error");
// Create the abort callback
callback = xhrCallbacks[( id = xhrId++ )] = callback("abort");
// Do send the request
// This may raise an exception which is actually
// handled in jQuery.ajax (so no try/catch here)
xhr.send( options.hasContent && options.data || null );
},
abort: function() {
if ( callback ) {
callback();
}
}
};
}
});
var fxNow, timerId,
rfxtypes = /^(?:toggle|show|hide)$/,
rfxnum = new RegExp( "^(?:([+-])=|)(" + core_pnum + ")([a-z%]*)$", "i" ),
rrun = /queueHooks$/,
animationPrefilters = [ defaultPrefilter ],
tweeners = {
"*": [function( prop, value ) {
var tween = this.createTween( prop, value ),
target = tween.cur(),
parts = rfxnum.exec( value ),
unit = parts && parts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ),
// Starting value computation is required for potential unit mismatches
start = ( jQuery.cssNumber[ prop ] || unit !== "px" && +target ) &&
rfxnum.exec( jQuery.css( tween.elem, prop ) ),
scale = 1,
maxIterations = 20;
if ( start && start[ 3 ] !== unit ) {
// Trust units reported by jQuery.css
unit = unit || start[ 3 ];
// Make sure we update the tween properties later on
parts = parts || [];
// Iteratively approximate from a nonzero starting point
start = +target || 1;
do {
// If previous iteration zeroed out, double until we get *something*
// Use a string for doubling factor so we don't accidentally see scale as unchanged below
scale = scale || ".5";
// Adjust and apply
start = start / scale;
jQuery.style( tween.elem, prop, start + unit );
// Update scale, tolerating zero or NaN from tween.cur()
// And breaking the loop if scale is unchanged or perfect, or if we've just had enough
} while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations );
}
// Update tween properties
if ( parts ) {
start = tween.start = +start || +target || 0;
tween.unit = unit;
// If a +=/-= token was provided, we're doing a relative animation
tween.end = parts[ 1 ] ?
start + ( parts[ 1 ] + 1 ) * parts[ 2 ] :
+parts[ 2 ];
}
return tween;
}]
};
// Animations created synchronously will run synchronously
function createFxNow() {
setTimeout(function() {
fxNow = undefined;
});
return ( fxNow = jQuery.now() );
}
function createTween( value, prop, animation ) {
var tween,
collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ),
index = 0,
length = collection.length;
for ( ; index < length; index++ ) {
if ( (tween = collection[ index ].call( animation, prop, value )) ) {
// we're done with this property
return tween;
}
}
}
function Animation( elem, properties, options ) {
var result,
stopped,
index = 0,
length = animationPrefilters.length,
deferred = jQuery.Deferred().always( function() {
// don't match elem in the :animated selector
delete tick.elem;
}),
tick = function() {
if ( stopped ) {
return false;
}
var currentTime = fxNow || createFxNow(),
remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ),
// archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497)
temp = remaining / animation.duration || 0,
percent = 1 - temp,
index = 0,
length = animation.tweens.length;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( percent );
}
deferred.notifyWith( elem, [ animation, percent, remaining ]);
if ( percent < 1 && length ) {
return remaining;
} else {
deferred.resolveWith( elem, [ animation ] );
return false;
}
},
animation = deferred.promise({
elem: elem,
props: jQuery.extend( {}, properties ),
opts: jQuery.extend( true, { specialEasing: {} }, options ),
originalProperties: properties,
originalOptions: options,
startTime: fxNow || createFxNow(),
duration: options.duration,
tweens: [],
createTween: function( prop, end ) {
var tween = jQuery.Tween( elem, animation.opts, prop, end,
animation.opts.specialEasing[ prop ] || animation.opts.easing );
animation.tweens.push( tween );
return tween;
},
stop: function( gotoEnd ) {
var index = 0,
// if we are going to the end, we want to run all the tweens
// otherwise we skip this part
length = gotoEnd ? animation.tweens.length : 0;
if ( stopped ) {
return this;
}
stopped = true;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( 1 );
}
// resolve when we played the last frame
// otherwise, reject
if ( gotoEnd ) {
deferred.resolveWith( elem, [ animation, gotoEnd ] );
} else {
deferred.rejectWith( elem, [ animation, gotoEnd ] );
}
return this;
}
}),
props = animation.props;
propFilter( props, animation.opts.specialEasing );
for ( ; index < length ; index++ ) {
result = animationPrefilters[ index ].call( animation, elem, props, animation.opts );
if ( result ) {
return result;
}
}
jQuery.map( props, createTween, animation );
if ( jQuery.isFunction( animation.opts.start ) ) {
animation.opts.start.call( elem, animation );
}
jQuery.fx.timer(
jQuery.extend( tick, {
elem: elem,
anim: animation,
queue: animation.opts.queue
})
);
// attach callbacks from options
return animation.progress( animation.opts.progress )
.done( animation.opts.done, animation.opts.complete )
.fail( animation.opts.fail )
.always( animation.opts.always );
}
function propFilter( props, specialEasing ) {
var index, name, easing, value, hooks;
// camelCase, specialEasing and expand cssHook pass
for ( index in props ) {
name = jQuery.camelCase( index );
easing = specialEasing[ name ];
value = props[ index ];
if ( jQuery.isArray( value ) ) {
easing = value[ 1 ];
value = props[ index ] = value[ 0 ];
}
if ( index !== name ) {
props[ name ] = value;
delete props[ index ];
}
hooks = jQuery.cssHooks[ name ];
if ( hooks && "expand" in hooks ) {
value = hooks.expand( value );
delete props[ name ];
// not quite $.extend, this wont overwrite keys already present.
// also - reusing 'index' from above because we have the correct "name"
for ( index in value ) {
if ( !( index in props ) ) {
props[ index ] = value[ index ];
specialEasing[ index ] = easing;
}
}
} else {
specialEasing[ name ] = easing;
}
}
}
jQuery.Animation = jQuery.extend( Animation, {
tweener: function( props, callback ) {
if ( jQuery.isFunction( props ) ) {
callback = props;
props = [ "*" ];
} else {
props = props.split(" ");
}
var prop,
index = 0,
length = props.length;
for ( ; index < length ; index++ ) {
prop = props[ index ];
tweeners[ prop ] = tweeners[ prop ] || [];
tweeners[ prop ].unshift( callback );
}
},
prefilter: function( callback, prepend ) {
if ( prepend ) {
animationPrefilters.unshift( callback );
} else {
animationPrefilters.push( callback );
}
}
});
function defaultPrefilter( elem, props, opts ) {
/* jshint validthis: true */
var prop, value, toggle, tween, hooks, oldfire,
anim = this,
orig = {},
style = elem.style,
hidden = elem.nodeType && isHidden( elem ),
dataShow = data_priv.get( elem, "fxshow" );
// handle queue: false promises
if ( !opts.queue ) {
hooks = jQuery._queueHooks( elem, "fx" );
if ( hooks.unqueued == null ) {
hooks.unqueued = 0;
oldfire = hooks.empty.fire;
hooks.empty.fire = function() {
if ( !hooks.unqueued ) {
oldfire();
}
};
}
hooks.unqueued++;
anim.always(function() {
// doing this makes sure that the complete handler will be called
// before this completes
anim.always(function() {
hooks.unqueued--;
if ( !jQuery.queue( elem, "fx" ).length ) {
hooks.empty.fire();
}
});
});
}
// height/width overflow pass
if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) {
// Make sure that nothing sneaks out
// Record all 3 overflow attributes because IE9-10 do not
// change the overflow attribute when overflowX and
// overflowY are set to the same value
opts.overflow = [ style.overflow, style.overflowX, style.overflowY ];
// Set display property to inline-block for height/width
// animations on inline elements that are having width/height animated
if ( jQuery.css( elem, "display" ) === "inline" &&
jQuery.css( elem, "float" ) === "none" ) {
style.display = "inline-block";
}
}
if ( opts.overflow ) {
style.overflow = "hidden";
anim.always(function() {
style.overflow = opts.overflow[ 0 ];
style.overflowX = opts.overflow[ 1 ];
style.overflowY = opts.overflow[ 2 ];
});
}
// show/hide pass
for ( prop in props ) {
value = props[ prop ];
if ( rfxtypes.exec( value ) ) {
delete props[ prop ];
toggle = toggle || value === "toggle";
if ( value === ( hidden ? "hide" : "show" ) ) {
// If there is dataShow left over from a stopped hide or show and we are going to proceed with show, we should pretend to be hidden
if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) {
hidden = true;
} else {
continue;
}
}
orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop );
}
}
if ( !jQuery.isEmptyObject( orig ) ) {
if ( dataShow ) {
if ( "hidden" in dataShow ) {
hidden = dataShow.hidden;
}
} else {
dataShow = data_priv.access( elem, "fxshow", {} );
}
// store state if its toggle - enables .stop().toggle() to "reverse"
if ( toggle ) {
dataShow.hidden = !hidden;
}
if ( hidden ) {
jQuery( elem ).show();
} else {
anim.done(function() {
jQuery( elem ).hide();
});
}
anim.done(function() {
var prop;
data_priv.remove( elem, "fxshow" );
for ( prop in orig ) {
jQuery.style( elem, prop, orig[ prop ] );
}
});
for ( prop in orig ) {
tween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim );
if ( !( prop in dataShow ) ) {
dataShow[ prop ] = tween.start;
if ( hidden ) {
tween.end = tween.start;
tween.start = prop === "width" || prop === "height" ? 1 : 0;
}
}
}
}
}
function Tween( elem, options, prop, end, easing ) {
return new Tween.prototype.init( elem, options, prop, end, easing );
}
jQuery.Tween = Tween;
Tween.prototype = {
constructor: Tween,
init: function( elem, options, prop, end, easing, unit ) {
this.elem = elem;
this.prop = prop;
this.easing = easing || "swing";
this.options = options;
this.start = this.now = this.cur();
this.end = end;
this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" );
},
cur: function() {
var hooks = Tween.propHooks[ this.prop ];
return hooks && hooks.get ?
hooks.get( this ) :
Tween.propHooks._default.get( this );
},
run: function( percent ) {
var eased,
hooks = Tween.propHooks[ this.prop ];
if ( this.options.duration ) {
this.pos = eased = jQuery.easing[ this.easing ](
percent, this.options.duration * percent, 0, 1, this.options.duration
);
} else {
this.pos = eased = percent;
}
this.now = ( this.end - this.start ) * eased + this.start;
if ( this.options.step ) {
this.options.step.call( this.elem, this.now, this );
}
if ( hooks && hooks.set ) {
hooks.set( this );
} else {
Tween.propHooks._default.set( this );
}
return this;
}
};
Tween.prototype.init.prototype = Tween.prototype;
Tween.propHooks = {
_default: {
get: function( tween ) {
var result;
if ( tween.elem[ tween.prop ] != null &&
(!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) {
return tween.elem[ tween.prop ];
}
// passing an empty string as a 3rd parameter to .css will automatically
// attempt a parseFloat and fallback to a string if the parse fails
// so, simple values such as "10px" are parsed to Float.
// complex values such as "rotate(1rad)" are returned as is.
result = jQuery.css( tween.elem, tween.prop, "" );
// Empty strings, null, undefined and "auto" are converted to 0.
return !result || result === "auto" ? 0 : result;
},
set: function( tween ) {
// use step hook for back compat - use cssHook if its there - use .style if its
// available and use plain properties where available
if ( jQuery.fx.step[ tween.prop ] ) {
jQuery.fx.step[ tween.prop ]( tween );
} else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) {
jQuery.style( tween.elem, tween.prop, tween.now + tween.unit );
} else {
tween.elem[ tween.prop ] = tween.now;
}
}
}
};
// Support: IE9
// Panic based approach to setting things on disconnected nodes
Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
set: function( tween ) {
if ( tween.elem.nodeType && tween.elem.parentNode ) {
tween.elem[ tween.prop ] = tween.now;
}
}
};
jQuery.each([ "toggle", "show", "hide" ], function( i, name ) {
var cssFn = jQuery.fn[ name ];
jQuery.fn[ name ] = function( speed, easing, callback ) {
return speed == null || typeof speed === "boolean" ?
cssFn.apply( this, arguments ) :
this.animate( genFx( name, true ), speed, easing, callback );
};
});
jQuery.fn.extend({
fadeTo: function( speed, to, easing, callback ) {
// show any hidden elements after setting opacity to 0
return this.filter( isHidden ).css( "opacity", 0 ).show()
// animate to the value specified
.end().animate({ opacity: to }, speed, easing, callback );
},
animate: function( prop, speed, easing, callback ) {
var empty = jQuery.isEmptyObject( prop ),
optall = jQuery.speed( speed, easing, callback ),
doAnimation = function() {
// Operate on a copy of prop so per-property easing won't be lost
var anim = Animation( this, jQuery.extend( {}, prop ), optall );
// Empty animations, or finishing resolves immediately
if ( empty || data_priv.get( this, "finish" ) ) {
anim.stop( true );
}
};
doAnimation.finish = doAnimation;
return empty || optall.queue === false ?
this.each( doAnimation ) :
this.queue( optall.queue, doAnimation );
},
stop: function( type, clearQueue, gotoEnd ) {
var stopQueue = function( hooks ) {
var stop = hooks.stop;
delete hooks.stop;
stop( gotoEnd );
};
if ( typeof type !== "string" ) {
gotoEnd = clearQueue;
clearQueue = type;
type = undefined;
}
if ( clearQueue && type !== false ) {
this.queue( type || "fx", [] );
}
return this.each(function() {
var dequeue = true,
index = type != null && type + "queueHooks",
timers = jQuery.timers,
data = data_priv.get( this );
if ( index ) {
if ( data[ index ] && data[ index ].stop ) {
stopQueue( data[ index ] );
}
} else {
for ( index in data ) {
if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) {
stopQueue( data[ index ] );
}
}
}
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) {
timers[ index ].anim.stop( gotoEnd );
dequeue = false;
timers.splice( index, 1 );
}
}
// start the next in the queue if the last step wasn't forced
// timers currently will call their complete callbacks, which will dequeue
// but only if they were gotoEnd
if ( dequeue || !gotoEnd ) {
jQuery.dequeue( this, type );
}
});
},
finish: function( type ) {
if ( type !== false ) {
type = type || "fx";
}
return this.each(function() {
var index,
data = data_priv.get( this ),
queue = data[ type + "queue" ],
hooks = data[ type + "queueHooks" ],
timers = jQuery.timers,
length = queue ? queue.length : 0;
// enable finishing flag on private data
data.finish = true;
// empty the queue first
jQuery.queue( this, type, [] );
if ( hooks && hooks.stop ) {
hooks.stop.call( this, true );
}
// look for any active animations, and finish them
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && timers[ index ].queue === type ) {
timers[ index ].anim.stop( true );
timers.splice( index, 1 );
}
}
// look for any animations in the old queue and finish them
for ( index = 0; index < length; index++ ) {
if ( queue[ index ] && queue[ index ].finish ) {
queue[ index ].finish.call( this );
}
}
// turn off finishing flag
delete data.finish;
});
}
});
// Generate parameters to create a standard animation
function genFx( type, includeWidth ) {
var which,
attrs = { height: type },
i = 0;
// if we include width, step value is 1 to do all cssExpand values,
// if we don't include width, step value is 2 to skip over Left and Right
includeWidth = includeWidth? 1 : 0;
for( ; i < 4 ; i += 2 - includeWidth ) {
which = cssExpand[ i ];
attrs[ "margin" + which ] = attrs[ "padding" + which ] = type;
}
if ( includeWidth ) {
attrs.opacity = attrs.width = type;
}
return attrs;
}
// Generate shortcuts for custom animations
jQuery.each({
slideDown: genFx("show"),
slideUp: genFx("hide"),
slideToggle: genFx("toggle"),
fadeIn: { opacity: "show" },
fadeOut: { opacity: "hide" },
fadeToggle: { opacity: "toggle" }
}, function( name, props ) {
jQuery.fn[ name ] = function( speed, easing, callback ) {
return this.animate( props, speed, easing, callback );
};
});
jQuery.speed = function( speed, easing, fn ) {
var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : {
complete: fn || !fn && easing ||
jQuery.isFunction( speed ) && speed,
duration: speed,
easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing
};
opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default;
// normalize opt.queue - true/undefined/null -> "fx"
if ( opt.queue == null || opt.queue === true ) {
opt.queue = "fx";
}
// Queueing
opt.old = opt.complete;
opt.complete = function() {
if ( jQuery.isFunction( opt.old ) ) {
opt.old.call( this );
}
if ( opt.queue ) {
jQuery.dequeue( this, opt.queue );
}
};
return opt;
};
jQuery.easing = {
linear: function( p ) {
return p;
},
swing: function( p ) {
return 0.5 - Math.cos( p*Math.PI ) / 2;
}
};
jQuery.timers = [];
jQuery.fx = Tween.prototype.init;
jQuery.fx.tick = function() {
var timer,
timers = jQuery.timers,
i = 0;
fxNow = jQuery.now();
for ( ; i < timers.length; i++ ) {
timer = timers[ i ];
// Checks the timer has not already been removed
if ( !timer() && timers[ i ] === timer ) {
timers.splice( i--, 1 );
}
}
if ( !timers.length ) {
jQuery.fx.stop();
}
fxNow = undefined;
};
jQuery.fx.timer = function( timer ) {
if ( timer() && jQuery.timers.push( timer ) ) {
jQuery.fx.start();
}
};
jQuery.fx.interval = 13;
jQuery.fx.start = function() {
if ( !timerId ) {
timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval );
}
};
jQuery.fx.stop = function() {
clearInterval( timerId );
timerId = null;
};
jQuery.fx.speeds = {
slow: 600,
fast: 200,
// Default speed
_default: 400
};
// Back Compat <1.8 extension point
jQuery.fx.step = {};
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.animated = function( elem ) {
return jQuery.grep(jQuery.timers, function( fn ) {
return elem === fn.elem;
}).length;
};
}
jQuery.fn.offset = function( options ) {
if ( arguments.length ) {
return options === undefined ?
this :
this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
var docElem, win,
elem = this[ 0 ],
box = { top: 0, left: 0 },
doc = elem && elem.ownerDocument;
if ( !doc ) {
return;
}
docElem = doc.documentElement;
// Make sure it's not a disconnected DOM node
if ( !jQuery.contains( docElem, elem ) ) {
return box;
}
// If we don't have gBCR, just use 0,0 rather than error
// BlackBerry 5, iOS 3 (original iPhone)
if ( typeof elem.getBoundingClientRect !== core_strundefined ) {
box = elem.getBoundingClientRect();
}
win = getWindow( doc );
return {
top: box.top + win.pageYOffset - docElem.clientTop,
left: box.left + win.pageXOffset - docElem.clientLeft
};
};
jQuery.offset = {
setOffset: function( elem, options, i ) {
var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition,
position = jQuery.css( elem, "position" ),
curElem = jQuery( elem ),
props = {};
// Set position first, in-case top/left are set even on static elem
if ( position === "static" ) {
elem.style.position = "relative";
}
curOffset = curElem.offset();
curCSSTop = jQuery.css( elem, "top" );
curCSSLeft = jQuery.css( elem, "left" );
calculatePosition = ( position === "absolute" || position === "fixed" ) && ( curCSSTop + curCSSLeft ).indexOf("auto") > -1;
// Need to be able to calculate position if either top or left is auto and position is either absolute or fixed
if ( calculatePosition ) {
curPosition = curElem.position();
curTop = curPosition.top;
curLeft = curPosition.left;
} else {
curTop = parseFloat( curCSSTop ) || 0;
curLeft = parseFloat( curCSSLeft ) || 0;
}
if ( jQuery.isFunction( options ) ) {
options = options.call( elem, i, curOffset );
}
if ( options.top != null ) {
props.top = ( options.top - curOffset.top ) + curTop;
}
if ( options.left != null ) {
props.left = ( options.left - curOffset.left ) + curLeft;
}
if ( "using" in options ) {
options.using.call( elem, props );
} else {
curElem.css( props );
}
}
};
jQuery.fn.extend({
position: function() {
if ( !this[ 0 ] ) {
return;
}
var offsetParent, offset,
elem = this[ 0 ],
parentOffset = { top: 0, left: 0 };
// Fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is it's only offset parent
if ( jQuery.css( elem, "position" ) === "fixed" ) {
// We assume that getBoundingClientRect is available when computed position is fixed
offset = elem.getBoundingClientRect();
} else {
// Get *real* offsetParent
offsetParent = this.offsetParent();
// Get correct offsets
offset = this.offset();
if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) {
parentOffset = offsetParent.offset();
}
// Add offsetParent borders
parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true );
parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true );
}
// Subtract parent offsets and element margins
return {
top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ),
left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true )
};
},
offsetParent: function() {
return this.map(function() {
var offsetParent = this.offsetParent || docElem;
while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position") === "static" ) ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || docElem;
});
}
});
// Create scrollLeft and scrollTop methods
jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) {
var top = "pageYOffset" === prop;
jQuery.fn[ method ] = function( val ) {
return jQuery.access( this, function( elem, method, val ) {
var win = getWindow( elem );
if ( val === undefined ) {
return win ? win[ prop ] : elem[ method ];
}
if ( win ) {
win.scrollTo(
!top ? val : window.pageXOffset,
top ? val : window.pageYOffset
);
} else {
elem[ method ] = val;
}
}, method, val, arguments.length, null );
};
});
function getWindow( elem ) {
return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 && elem.defaultView;
}
// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) {
// margin is only for outerHeight, outerWidth
jQuery.fn[ funcName ] = function( margin, value ) {
var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ),
extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" );
return jQuery.access( this, function( elem, type, value ) {
var doc;
if ( jQuery.isWindow( elem ) ) {
// As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there
// isn't a whole lot we can do. See pull request at this URL for discussion:
// https://github.com/jquery/jquery/pull/764
return elem.document.documentElement[ "client" + name ];
}
// Get document width or height
if ( elem.nodeType === 9 ) {
doc = elem.documentElement;
// Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height],
// whichever is greatest
return Math.max(
elem.body[ "scroll" + name ], doc[ "scroll" + name ],
elem.body[ "offset" + name ], doc[ "offset" + name ],
doc[ "client" + name ]
);
}
return value === undefined ?
// Get width or height on the element, requesting but not forcing parseFloat
jQuery.css( elem, type, extra ) :
// Set width or height on the element
jQuery.style( elem, type, value, extra );
}, type, chainable ? margin : undefined, chainable, null );
};
});
});
// Limit scope pollution from any deprecated API
// (function() {
// The number of elements contained in the matched element set
jQuery.fn.size = function() {
return this.length;
};
jQuery.fn.andSelf = jQuery.fn.addBack;
// })();
if ( typeof module === "object" && module && typeof module.exports === "object" ) {
// Expose jQuery as module.exports in loaders that implement the Node
// module pattern (including browserify). Do not create the global, since
// the user will be storing it themselves locally, and globals are frowned
// upon in the Node module world.
module.exports = jQuery;
} else {
// Register as a named AMD module, since jQuery can be concatenated with other
// files that may use define, but not via a proper concatenation script that
// understands anonymous AMD modules. A named AMD is safest and most robust
// way to register. Lowercase jquery is used because AMD module names are
// derived from file names, and jQuery is normally delivered in a lowercase
// file name. Do this after creating the global so that if an AMD module wants
// to call noConflict to hide this version of jQuery, it will work.
if ( typeof define === "function" && define.amd ) {
define( "jquery", [], function () { return jQuery; } );
}
}
// If there is a window object, that at least has a document property,
// define jQuery and $ identifiers
if ( typeof window === "object" && typeof window.document === "object" ) {
window.jQuery = window.$ = jQuery;
}
})( window );
| mfit/PdfTableAnnotator | src/main/webapp/lib/jquery/jquery.js | JavaScript | apache-2.0 | 242,234 |
import debug from 'debug';
import React from 'react';
import classNames from 'classnames';
import { connect } from 'react-redux';
import { Map as makeMap } from 'immutable';
import { clickCloseDetails, clickShowTopologyForNode } from '../actions/app-actions';
import { brightenColor, getNeutralColor, getNodeColorDark } from '../utils/color-utils';
import { isGenericTable, isPropertyList } from '../utils/node-details-utils';
import { resetDocumentTitle, setDocumentTitle } from '../utils/title-utils';
import Overlay from './overlay';
import MatchedText from './matched-text';
import NodeDetailsControls from './node-details/node-details-controls';
import NodeDetailsGenericTable from './node-details/node-details-generic-table';
import NodeDetailsPropertyList from './node-details/node-details-property-list';
import NodeDetailsHealth from './node-details/node-details-health';
import NodeDetailsInfo from './node-details/node-details-info';
import NodeDetailsRelatives from './node-details/node-details-relatives';
import NodeDetailsTable from './node-details/node-details-table';
import Warning from './warning';
import CloudFeature from './cloud-feature';
import NodeDetailsImageStatus from './node-details/node-details-image-status';
const log = debug('scope:node-details');
function getTruncationText(count) {
return 'This section was too long to be handled efficiently and has been truncated'
+ ` (${count} extra entries not included). We are working to remove this limitation.`;
}
class NodeDetails extends React.Component {
handleClickClose = (ev) => {
ev.preventDefault();
this.props.clickCloseDetails(this.props.nodeId);
}
handleShowTopologyForNode = (ev) => {
ev.preventDefault();
this.props.clickShowTopologyForNode(this.props.topologyId, this.props.nodeId);
}
componentDidMount() {
this.updateTitle();
}
componentWillUnmount() {
resetDocumentTitle();
}
renderTools() {
const showSwitchTopology = this.props.nodeId !== this.props.selectedNodeId;
const topologyTitle = `View ${this.props.label} in ${this.props.topologyId}`;
return (
<div className="node-details-tools-wrapper">
<div className="node-details-tools">
{showSwitchTopology &&
<span
title={topologyTitle}
className="fa fa-long-arrow-left"
onClick={this.handleShowTopologyForNode}>
<span>Show in <span>{this.props.topologyId.replace(/-/g, ' ')}</span></span>
</span>
}
<span
title="Close details"
className="fa fa-close close-details"
onClick={this.handleClickClose}
/>
</div>
</div>
);
}
renderLoading() {
const node = this.props.nodes.get(this.props.nodeId);
const label = node ? node.get('label') : this.props.label;
// NOTE: If we start the fa-spin animation before the node details panel has been
// mounted, the spinner is displayed blurred the whole time in Chrome (possibly
// caused by a bug having to do with animating the details panel).
const spinnerClassName = classNames('fa fa-circle-o-notch', { 'fa-spin': this.props.mounted });
const nodeColor = (node ?
getNodeColorDark(node.get('rank'), label, node.get('pseudo')) :
getNeutralColor());
const tools = this.renderTools();
const styles = {
header: {
backgroundColor: nodeColor
}
};
return (
<div className="node-details">
{tools}
<div className="node-details-header" style={styles.header}>
<div className="node-details-header-wrapper">
<h2 className="node-details-header-label truncate">
{label}
</h2>
<div className="node-details-relatives truncate">
Loading...
</div>
</div>
</div>
<div className="node-details-content">
<div className="node-details-content-loading">
<span className={spinnerClassName} />
</div>
</div>
</div>
);
}
renderNotAvailable() {
const tools = this.renderTools();
return (
<div className="node-details">
{tools}
<div className="node-details-header node-details-header-notavailable">
<div className="node-details-header-wrapper">
<h2 className="node-details-header-label">
{this.props.label}
</h2>
<div className="node-details-relatives truncate">
n/a
</div>
</div>
</div>
<div className="node-details-content">
<p className="node-details-content-info">
<strong>{this.props.label}</strong> is not visible to Scope when it
is not communicating.
Details will become available here when it communicates again.
</p>
</div>
<Overlay faded={this.props.transitioning} />
</div>
);
}
render() {
if (this.props.notFound) {
return this.renderNotAvailable();
}
if (this.props.details) {
return this.renderDetails();
}
return this.renderLoading();
}
renderDetails() {
const {
details, nodeControlStatus, nodeMatches = makeMap(), topologyId
} = this.props;
const showControls = details.controls && details.controls.length > 0;
const nodeColor = getNodeColorDark(details.rank, details.label, details.pseudo);
const {error, pending} = nodeControlStatus ? nodeControlStatus.toJS() : {};
const tools = this.renderTools();
const styles = {
controls: {
backgroundColor: brightenColor(nodeColor)
},
header: {
backgroundColor: nodeColor
}
};
return (
<div className="tour-step-anchor node-details">
{tools}
<div className="node-details-header" style={styles.header}>
<div className="node-details-header-wrapper">
<h2 className="node-details-header-label truncate" title={details.label}>
<MatchedText text={details.label} match={nodeMatches.get('label')} />
</h2>
<div className="node-details-header-relatives">
{details.parents && <NodeDetailsRelatives
matches={nodeMatches.get('parents')}
relatives={details.parents} />}
</div>
</div>
</div>
{showControls &&
<div className="tour-step-anchor node-details-controls-wrapper" style={styles.controls}>
<NodeDetailsControls
nodeId={this.props.nodeId}
controls={details.controls}
pending={pending}
error={error} />
</div>
}
<div className="node-details-content">
{details.metrics &&
<div className="node-details-content-section">
<div className="node-details-content-section-header">Status</div>
<NodeDetailsHealth
metrics={details.metrics}
topologyId={topologyId}
/>
</div>
}
{details.metadata &&
<div className="node-details-content-section">
<div className="node-details-content-section-header">Info</div>
<NodeDetailsInfo rows={details.metadata} matches={nodeMatches.get('metadata')} />
</div>
}
{details.connections && details.connections.filter(cs => cs.connections.length > 0)
.map(connections => (
<div className="node-details-content-section" key={connections.id}>
<NodeDetailsTable
{...connections}
nodes={connections.connections}
nodeIdKey="nodeId"
/>
</div>
))}
{details.children && details.children.map(children => (
<div className="node-details-content-section" key={children.topologyId}>
<NodeDetailsTable {...children} />
</div>
))}
{details.tables && details.tables.length > 0 && details.tables.map((table) => {
if (table.rows.length > 0) {
return (
<div className="node-details-content-section" key={table.id}>
<div className="node-details-content-section-header">
{table.label && table.label.length > 0 && table.label}
{table.truncationCount > 0 &&
<span
className="node-details-content-section-header-warning">
<Warning text={getTruncationText(table.truncationCount)} />
</span>
}
</div>
{this.renderTable(table)}
</div>
);
}
return null;
})}
<CloudFeature>
<NodeDetailsImageStatus
name={details.label}
metadata={details.metadata}
pseudo={details.pseudo}
topologyId={topologyId}
/>
</CloudFeature>
</div>
<Overlay faded={this.props.transitioning} />
</div>
);
}
renderTable(table) {
const { nodeMatches = makeMap() } = this.props;
if (isGenericTable(table)) {
return (
<NodeDetailsGenericTable
rows={table.rows}
columns={table.columns}
matches={nodeMatches.get('tables')}
/>
);
} else if (isPropertyList(table)) {
return (
<NodeDetailsPropertyList
rows={table.rows}
controls={table.controls}
matches={nodeMatches.get('property-lists')}
/>
);
}
log(`Undefined type '${table.type}' for table ${table.id}`);
return null;
}
componentDidUpdate() {
this.updateTitle();
}
updateTitle() {
setDocumentTitle(this.props.details && this.props.details.label);
}
}
function mapStateToProps(state, ownProps) {
const currentTopologyId = state.get('currentTopologyId');
return {
transitioning: state.get('pausedAt') !== ownProps.timestamp,
nodeMatches: state.getIn(['searchNodeMatches', currentTopologyId, ownProps.id]),
nodes: state.get('nodes'),
selectedNodeId: state.get('selectedNodeId'),
};
}
export default connect(
mapStateToProps,
{ clickCloseDetails, clickShowTopologyForNode }
)(NodeDetails);
| kinvolk/scope | client/app/scripts/components/node-details.js | JavaScript | apache-2.0 | 10,493 |
'use strict';
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var PrescriptionsSchema = new Schema({
date: { type: Date, default: Date.now } ,
med_dosage_list: [{ medicine: { type: mongoose.Schema.Types.ObjectId, ref: 'Medicine' }, dosage: 'String', howTo: 'String' }],
status: { type: 'String', default: 'Pending' },
patient: { type: mongoose.Schema.Types.ObjectId, ref: 'Patient' },
doctor: { type: 'String', default: 'Anonymous' },
pharmacist: { type: 'String', default: 'Anonymous' }
});
module.exports = mongoose.model('Prescription', PrescriptionsSchema); | mexeniz/hellose-opd | models/model-prescriptions.js | JavaScript | apache-2.0 | 605 |
module.exports = [{"isId":true,"priority":100100.0104,"key":"winSetting","style":{backgroundColor:Alloy.Globals.ThemeStyles.win.backgroundColor,}}]; | sjfranzen/yurapp | Resources/android/alloy/styles/adrSetting.js | JavaScript | apache-2.0 | 148 |
sap.ui.define("fixture.ModuleWaiter", [
"sap/ui/test/autowaiter/WaiterBase"
], function (WaiterBase) {
"use strict";
var ModuleWaiter = WaiterBase.extend("fixture.ModuleWaiter");
return new ModuleWaiter();
});
| SAP/openui5 | src/sap.ui.core/test/sap/ui/core/qunit/opa/fixture/waiters.js | JavaScript | apache-2.0 | 215 |
/*
Copyright 2015 Stefano Terna
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.
*/
'use strict';
describe('Directive: iottlytypeselector', function () {
// load the directive's module
beforeEach(module('consoleApp'));
var element,
scope;
beforeEach(inject(function ($rootScope) {
scope = $rootScope.$new();
}));
it('should make hidden element visible', inject(function ($compile) {
element = angular.element('<iottlytypeselector></iottlytypeselector>');
element = $compile(element)(scope);
expect(element.text()).toBe('this is the iottlytypeselector directive');
}));
});
| iottly/iottly-console | iottly_console/iottly_project/test/spec/directives/iottlytypeselector.js | JavaScript | apache-2.0 | 1,091 |
exports.up = function (db, cb) {
db.runSql(
`
INSERT INTO role_permission (role_id, permission_id, environment)
SELECT
(SELECT id as role_id from roles WHERE name = 'Owner' LIMIT 1),
p.id as permission_id,
e.name as environment
FROM permissions p
CROSS JOIN environments e
WHERE p.permission IN
('CREATE_FEATURE_STRATEGY',
'UPDATE_FEATURE_STRATEGY',
'DELETE_FEATURE_STRATEGY',
'UPDATE_FEATURE_ENVIRONMENT');
INSERT INTO role_permission (role_id, permission_id, environment)
SELECT
(SELECT id as role_id from roles WHERE name = 'Member' LIMIT 1),
p.id as permission_id,
e.name as environment
FROM permissions p
CROSS JOIN environments e
WHERE p.permission IN
('CREATE_FEATURE_STRATEGY',
'UPDATE_FEATURE_STRATEGY',
'DELETE_FEATURE_STRATEGY',
'UPDATE_FEATURE_ENVIRONMENT');
`,
cb,
);
};
exports.down = function (db, cb) {
db.runSql(
`
`,
cb,
);
};
| Unleash/unleash | src/migrations/20220103134659-add-permissions-to-project-roles.js | JavaScript | apache-2.0 | 1,153 |
({
setUp : function(component) {
var completed = false;
$A.storageService.getStorage("actions").clear()
.then(
function() { completed = true; },
function(err) { $A.test.fail("Test setUp() failed to clear storage: " + err);
});
$A.test.addWaitFor(true, function() { return completed; });
},
resetCounter:function(cmp, _testName){
var a = cmp.get('c.resetCounter');
a.setParams({ testName: _testName });
$A.test.enqueueAction(a);
$A.test.addWaitFor(true, function(){ return $A.test.areActionsComplete([a])});
},
executeAction:function(cmp, actionName, actionParam, additionalProperties, extraCallback){
var helper = cmp.getDef().getHelper();
return helper.executeAction.call(helper, cmp, actionName, actionParam, additionalProperties, extraCallback);
},
findAndSetText:function(cmp, targetCmpId, msg){
cmp.find(targetCmpId).getElement().innerHTML = msg;
},
/**
* Verify the default adapter selected when auraStorage:init is used without
* any specification.
*/
testDefaultAdapterSelection : {
test : function(cmp) {
var storage = $A.storageService.getStorage("defaultAdapter");
$A.test.assertTruthy(storage, "Failed to fetch named storage.");
$A.test.assertEquals("memory", storage.getName());
}
},
/**
* Register two auraStorage:init components with the same name but different
* config, establish which one stands W-1560182: Is it okay that we allow
* duplicate registration using auraStorage:init with same name but, we do
* not allow dups using $A.storageService.initStorage()? we do not allow dup
* named auraStorage:init in templates?
*/
// auraErrorsExpectedDuringInit is not supported.
_testDuplicateNamedStorage : {
auraErrorsExpectedDuringInit : ["Storage named 'dupNamedStorage' already exists!"],
attributes : {
dupNamedStorage : true
},
test : [
function(cmp) {
$A.test.assertTruthy(cmp.find("dupNamedStorage1"));
$A.test.assertTruthy(cmp.find("dupNamedStorage2"),
"Duplicate named storage not registered using auraStorage:init");
},
function(cmp) {
//FIXME: W-1689002
//var storage = $A.storageService.getStorage("dupNamedStorage");
//$A.test.assertEquals(9999, storage.getMaxSize(),
// "storage config was overriden by duplicate registrations.");
} ]
},
testActionStorageProperties : {
test : [
function(cmp) {
$A.test.assertTruthy($A.storageService, "Aura Storage service is undefined.");
var storage = $A.storageService.getStorage("actions");
$A.test.assertTruthy(storage, "Aura Storage object is undefined.");
$A.test.assertEquals("memory", storage.getName());
this.resetCounter(cmp, "testBasicStorageServiceInitialization");
},
function(cmp) {
// Verify API for server actions
var a = cmp.get("c.fetchDataRecord");
$A.test.assertTrue(a.getDef().isServerAction());
$A.test.assertFalse(a.isStorable(), "By default action should not be marked for storage.");
a.setStorable();
$A.test.assertTrue(a.isStorable(), "Failed to mark action for storage.");
},
function(cmp) {
// Verify API for client actions
var a = cmp.get("c.forceActionAtServer");
try {
a.setStorable();
$A.test.fail("Client actions cannot be marked for storage.");
} catch (e) {
$A.test.assert(e.message.indexOf("Assertion Failed!: setStorable() cannot be called on a client action.") === 0);
}
$A.test.assertFalse(a.isStorable());
} ]
},
/**
* Verify Action.isStorable()
*/
testIsStorableAPI : {
test : [ function(cmp) {
var a = cmp.get("c.fetchDataRecord");
a.setStorable();
$A.test.assertTrue(a.isStorable(), "Failed to mark action as storable.");
a.setStorable({
"ignoreExisting" : true
});
$A.test.assertFalse(a.isStorable(), "Failed to use ignoreExisting as config.");
a.setStorable({
"ignoreExisting" : false
});
$A.test.assertTrue(a.isStorable(), "Action was marked to not ignore existing storage config.");
} ]
},
textForName : function(cmp, name) {
var subcmp = cmp.find(name);
if(!subcmp) {
subcmp = cmp.getSuper().find(name);
}
if(!subcmp) {
return null;
}
return $A.test.getText(subcmp.getElement());
},
/**
* Verify Action.setStorable() and auto refresh setStorage() accepts
* configuration. These configuration are helpful for follow up actions but
* not the first action to be stored.
*
* {ignoreExisting: "Ignore existing stored response, but cache my response
* after the action is complete" "refresh": "Time in seconds to override
* action's current storage expiration"}
*
* We crank up the default refresh and expiration to make them irrelevant here.
*/
testSetStorableAPI : {
attributes : {
defaultExpiration : "600",
defaultAutoRefreshInterval : "600"
},
test : [ function(cmp) {
//
// Reset everything.
//
$A.test.setTestTimeout(30000);
this.resetCounter(cmp, "testSetStorableAPI");
}, function(cmp) {
//
// Run a single 'fetch', and store the result. This should never run from
// storage, and should always give a zero response.
//
$A.test.setTestTimeout(30000);
var fetch1 = cmp.get("c.fetchDataRecord");
fetch1.setParams({testName : "testSetStorableAPI"});
fetch1.setStorable();
$A.test.enqueueAction(fetch1);
$A.test.addWaitFor(true, function() { return $A.test.areActionsComplete([fetch1]); },
function(){
$A.test.assertEquals("SUCCESS", fetch1.getState());
$A.test.assertFalse(fetch1.isFromStorage(), "Failed to excute action at server");
$A.test.assertEquals(0, fetch1.getReturnValue().Counter, "Wrong counter value seen in response");
//Set response stored time
cmp._requestStoredTime = new Date().getTime();
});
}, function(cmp) {
//
// Now, go and get it again, we should always get a response from storage, and we should never
// cause a refresh.
//
$A.test.setTestTimeout(30000);
var fetch2 = cmp.get("c.fetchDataRecord");
var that = this;
fetch2.setParams({testName : "testSetStorableAPI"});
fetch2.setStorable();
$A.test.enqueueAction(fetch2);
$A.test.addWaitFor(true, function() { return $A.test.areActionsComplete([fetch2]); },
function(){
$A.test.assertEquals("SUCCESS", fetch2.getState());
$A.test.assertEquals(0, fetch2.getReturnValue().Counter, "fetch 2 response invalid.");
$A.test.assertEquals("", that.textForName(cmp, "refreshBegin"),
"refreshBegin fired unexpectedly");
$A.test.assertEquals("", that.textForName(cmp, "refreshEnd"),
"refreshEnd fired unexpectedly");
});
}, function(cmp) {
//
// Now that we have tested a stored response, make sure that refresh still has not fired,
// and go ahead and put in a blocking request, followed by a request for the data record.
// This should give us an immediate callback for the stored response, along with a refresh
// event, followed by a wait.
//
// Once we get the refresh event, we send a resume to the server, ensuring that we unblock
// the server.
//
var that = this;
$A.test.setTestTimeout(30000);
$A.test.assertEquals("", this.textForName(cmp, "refreshBegin"),
"refreshBegin fired unexpectedly");
$A.test.assertEquals("", this.textForName(cmp, "refreshEnd"),
"refreshEnd fired unexpectedly");
var block = cmp.get("c.block");
var refreshState = "none";
block.setParams({testName : "testSetStorableAPI"});
$A.test.callServerAction(block, true);
var requestTime;
//Wait till the block action is executed
$A.test.addWaitFor(true, function() { return $A.test.areActionsComplete([block]); },
function(){
$A.test.assertEquals("", this.textForName(cmp, "refreshBegin"),
"refreshBegin fired unexpectedly");
$A.test.assertEquals("", this.textForName(cmp, "refreshEnd"),
"refreshEnd fired unexpectedly");
var aThird = cmp.get("c.fetchDataRecord");
aThird.setParams({testName : "testSetStorableAPI"});
//Keeping the auto refresh time to 0, helps testing the override
aThird.setStorable({"refresh": 0});
requestTime = new Date().getTime();
$A.test.enqueueAction(aThird);
$A.test.addWaitFor(true, function() { return $A.test.areActionsComplete([aThird]); },
function(){
$A.test.assertEquals("SUCCESS", aThird.getState());
$A.test.assertTrue(aThird.isFromStorage(), "failed to fetch cached response");
});
});
//Verify that refreshBegin was fired
$A.test.addWaitFor("refreshBegin", function(){ return that.textForName(cmp, "refreshBegin"); },
function(){
var refreshTime = new Date().getTime();
//Verify that the refresh begin event kicked off
$A.test.assertEquals(refreshState, "none");
refreshState = "start";
$A.test.assertTrue((refreshTime-requestTime)< 6000,
"Expected refresh within 5 seconds, got "+((refreshTime-requestTime)/1000) );
//resume controller only after refreshBegin
var resume = cmp.get("c.resume");
resume.setParams({testName : "testSetStorableAPI"});
$A.test.callServerAction(resume, true);
});
//Verify that refreshEnd was fired
$A.test.addWaitFor("refreshEnd", function(){ return that.textForName(cmp, "refreshEnd"); },
function(){
$A.test.assertEquals(refreshState, "start");
refreshState = "end";
});
}, function(cmp) {
$A.test.setTestTimeout(30000);
var aFourth = cmp.get("c.fetchDataRecord");
aFourth.setParams({testName : "testSetStorableAPI"});
aFourth.setStorable();
$A.test.enqueueAction(aFourth);
$A.test.addWaitForWithFailureMessage(true, function() { return $A.test.areActionsComplete([aFourth]); },
"Expected action to become SUCCESSful.",
function(){
$A.test.assertEquals("SUCCESS", aFourth.getState());
$A.test.assertTrue(aFourth.isFromStorage(), "aFourth should have been from storage");
}
);
// Storage is asynchronous; therefore, the Action may be SUCCESS before the value is stored.
$A.test.addWaitForWithFailureMessage(1,
function() { return aFourth.getReturnValue().Counter; },
"aFourth should have fetched a refreshed response.");
} ]
},
/**
* Refresh action which refresh the response of stored action can be configured to not call the callback.
* This test case verified that.
*/
testSetStorableAPI_executeCallbackIfUpdated : {
attributes : {
defaultExpiration : 60,
defaultAutoRefreshInterval : 0 // refresh every action
},
test : [function(cmp) {
cmp._testName = "testSkipCallbackOnRefresh";
this.resetCounter(cmp, "testSkipCallbackOnRefresh");
}, function(cmp) {
//First action which fetches the response from server.
var a = this.executeAction(cmp, "c.fetchDataRecord",
{testName:cmp._testName},
function(a){a.setStorable();});
//Wait for first callback
$A.test.addWaitFor("1", function() { return $A.test.getText(cmp.find("callbackCounter").getElement()); },
function() {
$A.test.assertEquals("0", $A.test.getText(cmp.find("staticCounter").getElement()));
$A.test.assertEquals("false", $A.test.getText(cmp.find("isFromStorage").getElement()));
$A.storageService.getStorage("actions").get(a.getStorageKey()).then(
function(item){
cmp._originalExpiration = item.expires;
});
});
}, function(cmp) {
// Specify that callback should not be called in case of refresh, so callback count should be 1 (for get())
var a = this.executeAction(cmp, "c.fetchDataRecord",
{testName:cmp._testName}, function(a) { a.setStorable({"executeCallbackIfUpdated":false}); });
$A.test.addWaitFor("refreshEnd", function(){return $A.test.getText(cmp.find("refreshEnd").getElement());},
function() {
//From cached response
$A.test.assertEquals("0", $A.test.getText(cmp.find("staticCounter").getElement()));
//Once for the original action and second action which was fetched from storage. None for refresh action
$A.test.assertEquals("2", $A.test.getText(cmp.find("callbackCounter").getElement()));
$A.storageService.getStorage("actions").get(a.getStorageKey()).then(
function(item){
$A.test.assertEquals(1, item.value.returnValue.Counter,
"Refresh action response not stored in storage");
if(item.expires <= cmp._originalExpiration){
$A.test.fail("storage expiration was not updated after refresh " +
item.expires+" != "+cmp._originalExpiration);
}
});
});
} ]
},
/**
* Providing empty config doesn't change the default behavior. The default refresh interval will be used.
*/
testSetStorableAPI_Empty : {
attributes : {
defaultExpiration : "60",
defaultAutoRefreshInterval : "0"
},
test : [
function(cmp) {
$A.test.setTestTimeout(30000);
this.resetCounter(cmp, "testSetStorableAPI_Empty");
},
function(cmp) {
var a = cmp.get("c.fetchDataRecord");
a.setParams({
testName : "testSetStorableAPI_Empty"
});
// Empty settings
a.setStorable({});
$A.test.enqueueAction(a);
$A.test.addWaitFor(false, $A.test.isActionPending);
},
function(cmp) {
var aSecond = cmp.get("c.fetchDataRecord");
aSecond.setParams({
testName : "testSetStorableAPI_Empty"
});
// Empty settings
aSecond.setStorable({});
$A.test.assertTrue(aSecond.isStorable());
$A.test.enqueueAction(aSecond);
$A.test.addWaitFor(true, function() { return $A.test.areActionsComplete([aSecond]); },
function() {
$A.test.assertEquals("SUCCESS", aSecond.getState(), "failed to fetch cached response");
$A.test.assertTrue(aSecond.isFromStorage(), "failed to fetch cached response");
//Refresh interval should default to 0 and refresh should happen.
$A.test.addWaitFor("refreshEnd", function() {
return $A.test.getText(cmp.find("refreshEnd").getElement());
});
});
}
]
},
testSetStorableAPI_Undefined : {
attributes : {
defaultExpiration : "60",
defaultAutoRefreshInterval : "0"
},
test : [
function(cmp) {
$A.test.setTestTimeout(30000);
this.resetCounter(cmp, "testSetStorableAPI_Undefined");
},
function(cmp) {
var aUndefined = cmp.get("c.fetchDataRecord");
aUndefined.setParams({ testName : "testSetStorableAPI_Undefined" });
// Undefined
aUndefined.setStorable(undefined);
$A.test.assertTrue(aUndefined.isStorable());
$A.test.enqueueAction(aUndefined);
$A.test.addWaitFor("SUCCESS", function() {
return aUndefined.getState();
}, function() {
$A.test.assertFalse(aUndefined.isFromStorage(), "failed to fetch cached response");
$A.test.assertEquals("", $A.test.getText(cmp.find("refreshBegin").getElement()),
"refreshBegin fired unexpectedly");
$A.test.assertEquals("", $A.test.getText(cmp.find("refreshEnd").getElement()),
"refreshEnd fired unexpectedly");
});
},
function(cmp) {
var aUndefinedSecond = cmp.get("c.fetchDataRecord");
aUndefinedSecond.setParams({ testName : "testSetStorableAPI_Undefined" });
aUndefinedSecond.setStorable(undefined);
$A.test.assertTrue(aUndefinedSecond.isStorable());
$A.test.enqueueAction(aUndefinedSecond);
// Make sure refreshEnd has not fired.
$A.test.assertEquals("", $A.test.getText(cmp.find("refreshEnd").getElement()),
"refreshEnd fired unexpectedly");
$A.test.addWaitFor("SUCCESS", function() { return aUndefinedSecond.getState(); },
function() {
$A.test.assertTrue(aUndefinedSecond.isFromStorage(), "failed to fetch cached response");
});
$A.test.addWaitFor("refreshEnd", function() {
return $A.test.getText(cmp.find("refreshEnd").getElement());
});
},
function(cmp) {
var aUndefinedThird = cmp.get("c.fetchDataRecord");
aUndefinedThird.setParams({ testName : "testSetStorableAPI_Undefined" });
aUndefinedThird.setStorable(undefined);
$A.test.assertTrue(aUndefinedThird.isStorable());
$A.test.enqueueAction(aUndefinedThird);
$A.test.addWaitFor("SUCCESS", function() { return aUndefinedThird.getState(); },
function() {
$A.log(aUndefinedThird.getReturnValue());
$A.test.assertTrue(aUndefinedThird.isFromStorage(),
"aUndefinedThird should have been from storage");
$A.test.assertEquals(1, aUndefinedThird.getReturnValue().Counter,
"aUndefinedThird should have fetched refreshed response");
});
} ]
},
testSetStorableAPI_UndefinedProps : {
attributes : {
defaultExpiration : "60",
defaultAutoRefreshInterval : "0"
},
test : [
function(cmp) {
$A.test.setTestTimeout(30000);
this.resetCounter(cmp, "testSetStorableAPI_UndefinedProps");
},
function(cmp) {
var aUndefined = cmp.get("c.fetchDataRecord");
aUndefined.setParams({
testName : "testSetStorableAPI_UndefinedProps"
});
// Undefined parts
aUndefined.setStorable({
"IgnoreExisting" : undefined,
"refresh" : undefined
});
$A.test.assertTrue(aUndefined.isStorable());
$A.test.enqueueAction(aUndefined);
$A.test.addWaitFor("SUCCESS", function() {
return aUndefined.getState();
}, function() {
$A.test.assertFalse(aUndefined.isFromStorage(), "failed to fetch cached response");
$A.test.assertEquals("", $A.test.getText(cmp.find("refreshBegin").getElement()),
"refreshBegin fired unexpectedly");
$A.test.assertEquals("", $A.test.getText(cmp.find("refreshEnd").getElement()),
"refreshEnd fired unexpectedly");
});
},
function(cmp) {
var aUndefinedSecond = cmp.get("c.fetchDataRecord");
aUndefinedSecond.setParams({
testName : "testSetStorableAPI_UndefinedProps"
});
aUndefinedSecond.setStorable({
"IgnoreExisting" : undefined,
"refresh" : undefined
});
$A.test.assertTrue(aUndefinedSecond.isStorable());
$A.test.enqueueAction(aUndefinedSecond);
$A.test.addWaitFor("SUCCESS", function() {
return aUndefinedSecond.getState();
}, function() {
$A.test.assertTrue(aUndefinedSecond.isFromStorage(), "failed to fetch cached response");
}, function() {
$A.test.addWaitFor("refreshEnd",
function() {
return $A.test.getText(cmp.find("refreshEnd").getElement());
}, function() {
var aUndefinedThird = cmp.get("c.fetchDataRecord");
aUndefinedThird.setParams({
testName : "testSetStorableAPI_UndefinedProps"
});
aUndefinedThird.setStorable({
"IgnoreExisting" : undefined,
"refresh" : undefined
});
$A.test.enqueueAction(aUndefinedThird);
$A.test.addWaitFor("SUCCESS", function() {
return aUndefinedThird.getState();
}, function() {
$A.test.assertTrue(aUndefinedThird.isFromStorage(),
"aUndefinedThird should have been from storage");
$A.test.assertEquals(1, aUndefinedThird.getReturnValue().Counter,
"aUndefinedThird should have fetched refreshed response");
});
}
);
});
} ]
},
/**
* Verify that an action can bypass the storage service when its not marked
* a Storable. Verify isFromStorage() API on Action.
*/
testForceActionAtServer : {
attributes : {
defaultExpiration : 30
},
test : [
function(cmp) {
$A.test.setTestTimeout(30000);
cmp._testName = "testForceActionAtServer";
this.resetCounter(cmp, "testForceActionAtServer");
},
function(cmp) {
// Run the action and mark it as storable.
var btn = cmp.find("RunActionAndStore");
var evt = btn.get("e.press");
var storage = $A.storageService.getStorage("actions");
var completed = false;
evt.fire();
$A.test.addWaitFor(false, $A.test.isActionPending, function() {
$A.test.assertEquals("StorageController", $A.test.getText(cmp.find("responseData").getElement()));
$A.test.assertEquals("0", $A.test.getText(cmp.find("staticCounter").getElement()));
$A.test.assertEquals("false", $A.test.getText(cmp.find("isFromStorage").getElement()));
$A.test.assertEquals("1", $A.test.getText(cmp.find("callbackCounter").getElement()));
storage.getSize()
.then(function(size) {
$A.test.assertTrue(size > 0, "Expected first action to be stored in storage service.");
})
.then(function() {
completed = true;
})
["catch"](function(error) { $A.test.fail(error.toString()); });
});
$A.test.addWaitFor(true, function() { return completed; });
},
function(cmp) {
// Re-Run the action without marking it as storable, this
// should force the action to by pass memory service.
var btn = cmp.find("ForceActionAtServer");
var evt = btn.get("e.press");
evt.fire();
$A.test.addWaitFor(false, $A.test.isActionPending, function() {
$A.test.assertEquals("StorageController", $A.test
.getText(cmp.find("responseData").getElement()));
$A.test.assertEquals("1", $A.test.getText(cmp.find("staticCounter").getElement()),
"Failed to force a previously cached action to run at server.");
$A.test.assertEquals("false", $A.test.getText(cmp.find("isFromStorage").getElement()));
$A.test.assertEquals("2", $A.test.getText(cmp.find("callbackCounter").getElement()));
});
}, function(cmp) {
// Re-Run the action and mark it as storable. Expect to see
// the cached response.
var btn = cmp.find("RunActionAndStore");
var evt = btn.get("e.press");
evt.fire();
$A.test.addWaitFor("0", function() {
return $A.test.getText(cmp.find("staticCounter").getElement());
}, function() {
$A.test.assertEquals("true", $A.test.getText(cmp.find("isFromStorage").getElement()));
$A.test.assertEquals("3", $A.test.getText(cmp.find("callbackCounter").getElement()));
});
}
]
},
testUnmarkedActionAreNotStored : {
test : [
function(cmp) {
var completed = false;
cmp._testName = "testUnmarkedActionAreNotStored";
this.resetCounter(cmp, "testUnmarkedActionAreNotStored");
var storage = $A.storageService.getStorage("actions");
storage.getSize()
.then(function(size) { $A.test.assertEquals(0, size); })
.then(function() { completed = true; })
["catch"](function(error) { $A.test.fail(error.toString()); });
$A.test.addWaitFor(true, function() { return completed; });
},
function(cmp) {
// Run the action without marking it as storable.
var btn = cmp.find("ForceActionAtServer");
var evt = btn.get("e.press");
var storage = $A.storageService.getStorage("actions");
var completed = false;
evt.fire();
$A.test.addWaitFor(false, $A.test.isActionPending, function() {
$A.test.assertEquals(
"StorageController",
$A.test.getText(cmp.find("responseData").getElement())
);
$A.test.assertEquals(
"0",
$A.test.getText(cmp.find("staticCounter").getElement()),
"Failed to inoke server action."
);
storage.getSize()
.then(function(size) { $A.test.assertEquals(0, size, "Storage service saw an increase in size."); })
.then(function() { completed = true; })
["catch"](function(error) { $A.test.fail(error.toString()); });
});
$A.test.addWaitFor(true, function() { return completed; });
}, function(cmp) {
var btn = cmp.find("ForceActionAtServer");
var evt = btn.get("e.press");
evt.fire();
$A.test.addWaitFor("1", function() {
return $A.test.getText(cmp.find("staticCounter").getElement());
});
} ]
},
/**
* When offline, should not purge cached data.
*/
testCacheDataNotPurgedWhenOffline : {
attributes : {
defaultExpiration : 5, // I am king
defaultAutoRefreshInterval : 60 // Very high but doesn't matter
},
test : [
function(cmp) {
$A.test.setTestTimeout(30000);
this.resetCounter(cmp, "testCacheDataNotPurgedWhenOffline");
},
function(cmp) {
// Run the action and mark it as storable.
var a = cmp.get("c.fetchDataRecord");
a.setParams({ testName : "testCacheDataNotPurgedWhenOffline" });
a.setStorable();
$A.test.enqueueAction(a);
$A.test.addWaitFor(false, $A.test.isActionPending, function() {
$A.test.assertFalse(a.isFromStorage(), "Should not be using cached data");
$A.test.assertEquals(0, a.getReturnValue().Counter, "Wrong counter value seen in response");
});
},
function(cmp) {
// Wait for atleast 5 seconds after the response has been
// stored
$A.test.addWaitFor(true, function() {
var now = new Date().getTime();
var storageModified = $A.test.getText(cmp.find("storageModified").getElement());
return (now - parseInt(storageModified, 10)) > 5000;
});
},
function(cmp) {
// Create an offline event,
var connectionLostEvent = $A.get("e.aura:connectionLost");
connectionLostEvent.fire();
},
function(cmp) {
// Run the action and verify that cached data is not purged
var a = cmp.get("c.fetchDataRecord");
a.setParams({
testName : "testCacheDataNotPurgedWhenOffline"
});
a.setStorable();
$A.test.enqueueAction(a);
$A.test.addWaitFor("SUCCESS", function() {
return a.getState();
}, function() {
$A.test.assertEquals(0, a.getReturnValue().Counter,
"Offline, second response should not be available.");
$A.test.assertTrue(a.isFromStorage(), "Should use cached data because offline");
});
} ]
},
/**
* Go offline (should not purge cached data), then go back online, should
* use cached data.
*/
testCacheDataUsedWhenConnectionResumed : {
attributes : {
defaultExpiration : 50,
defaultAutoRefreshInterval : 60
},
test : [ function(cmp) {
$A.test.setTestTimeout(30000);
this.resetCounter(cmp, "testCacheDataUsedWhenConnectionResumed");
}, function(cmp) {
// Run the action and mark it as storable.
var a = cmp.get("c.fetchDataRecord");
a.setParams({
testName : "testCacheDataUsedWhenConnectionResumed"
});
a.setStorable();
$A.test.enqueueAction(a);
$A.test.addWaitFor(false, $A.test.isActionPending, function() {
$A.test.assertFalse(a.isFromStorage(), "Should not be using cached data");
$A.test.assertEquals(0, a.getReturnValue().Counter, "Wrong counter value seen in response");
});
}, function(cmp) {
// Create an offline event,
var connectionLostEvent = $A.get("e.aura:connectionLost");
connectionLostEvent.fire();
}, function(cmp) {
// go back online
var connectionResumed = $A.get("e.aura:connectionResumed");
connectionResumed.fire();
// Run the action and verify that cache data is still being used
var a = cmp.get("c.fetchDataRecord");
a.setParams({
testName : "testCacheDataUsedWhenConnectionResumed"
});
a.setStorable();
$A.test.enqueueAction(a);
$A.test.addWaitFor("SUCCESS", function() {
return a.getState();
}, function() {
$A.test.assertTrue(a.isFromStorage(), "Connection resumed but should still use cached data");
});
} ]
},
/**
* Verify stored items are overwritten with identical action keys
*/
testActionKeyOverloading : {
test : [ function(cmp) {
$A.test.setTestTimeout(30000);
this.resetCounter(cmp, "testActionKeyOverloading");
}, function(cmp) {
var a = cmp.get("c.substring");
a.setParams({testName : "testActionKeyOverloading", param1 : 999});
a.setStorable();
$A.test.enqueueAction(a);
$A.test.addWaitFor(false, $A.test.isActionPending,
function(){
$A.test.assertFalse(a.isFromStorage(), "Failed to excute action at server");
$A.test.assertEquals(0, a.getReturnValue()[0], "Wrong counter value seen in response");
$A.test.assertEquals(999, a.getReturnValue()[1]);
});
}, function(cmp) {
//Controller name is a substring of previous controller
var a = cmp.get("c.string");
a.setParams({testName : "testActionKeyOverloading", param1 : 999});
a.setStorable();
$A.test.enqueueAction(a);
$A.test.addWaitFor(false, $A.test.isActionPending,
function(){
$A.test.assertFalse(a.isFromStorage(), "should not have fetched from cache");
$A.test.assertEquals(1, a.getReturnValue()[0], "Wrong counter value seen in response");
$A.test.assertEquals(999, a.getReturnValue()[1]);
});
}, function(cmp) {
//Controller name is the same as previous controller but different parameter value
var a = cmp.get("c.string");
a.setParams({testName : "testActionKeyOverloading", param1 : 9999});
a.setStorable();
$A.test.enqueueAction(a);
$A.test.addWaitFor(false, $A.test.isActionPending,
function(){
$A.test.assertFalse(a.isFromStorage(), "Failed to excute action at server");
$A.test.assertEquals(2, a.getReturnValue()[0], "Wrong counter value seen in response");
$A.test.assertEquals(9999, a.getReturnValue()[1]);
});
} ]
},
/**
* Grouping multiple actions and setting them to be storable.
*/
testActionGrouping : {
attributes : {
defaultExpiration : 60,
defaultAutoRefreshInterval : 60
},
test : [ function(cmp) {
$A.test.setTestTimeout(30000);
this.resetCounter(cmp, "testActionGrouping_A");
this.resetCounter(cmp, "testActionGrouping_B");
this.resetCounter(cmp, "testActionGrouping_notStored");
}, function(cmp) {
var a1 = cmp.get("c.substring");
a1.setParams({testName : "testActionGrouping_A", param1 : 999});
a1.setStorable();
$A.enqueueAction(a1);
var b1 = cmp.get("c.string");
b1.setParams({testName : "testActionGrouping_B", param1 : 666});
b1.setStorable();
$A.enqueueAction(b1);
//1 Unstored action
var notStored = cmp.get("c.fetchDataRecord");
notStored.setParams({testName : "testActionGrouping_notStored"});
$A.enqueueAction(notStored);
$A.test.addWaitFor(false, $A.test.isActionPending);
}, function(cmp) {
//Run a action whose response has been previously stored
var a2 = cmp.get("c.substring");
a2.setParams({testName : "testActionGrouping_A", param1 : 999});
a2.setStorable();
$A.test.enqueueAction(a2);
$A.test.addWaitFor("SUCCESS", function() { return a2.getState(); },
function(){
$A.log($A.storageService.getStorage("actions"));
$A.test.assertTrue(a2.isFromStorage(), "Failed to fetch action from storage");
$A.test.assertEquals(0, a2.getReturnValue()[0], "Wrong counter value seen in response");
$A.test.assertEquals(999, a2.getReturnValue()[1]);
});
}, function(cmp) {
//Run a action whose response has been previously stored
var b2 = cmp.get("c.string");
b2.setParams({testName : "testActionGrouping_B", param1 : 666});
b2.setStorable();
$A.enqueueAction(b2);
//Run a action which was previously not marked to be stored and group it with the one above
var notStoredAgain = cmp.get("c.fetchDataRecord");
notStoredAgain.setParams({testName : "testActionGrouping_notStored"});
$A.test.enqueueAction(notStoredAgain);
$A.test.addWaitFor("SUCCESS", function() { return b2.getState(); },
function(){
$A.test.assertTrue(b2.isFromStorage(), "failed to fetch action from cache");
$A.test.assertEquals(0, b2.getReturnValue()[0], "Wrong counter value seen in response");
$A.test.assertEquals(666, b2.getReturnValue()[1]);
});
$A.test.addWaitFor(false, $A.test.isActionPending,
function(){
$A.test.assertFalse(notStoredAgain.isFromStorage(), "Failed to group stored actions and unstored actions.");
$A.test.assertEquals(1, notStoredAgain.getReturnValue().Counter,
"Counter value should have been incremented for unstored action");
});
} ]
},
/**
* If a refresh contains the same response as what is stored, then skip
* replaying the callback. The callback for the stored response is still
* executed.
* Case: Simple action with no components involved
*/
testRefresh_ResponseSameAsStored : {
attributes : {
defaultExpiration : 60,
defaultAutoRefreshInterval : 0 // refresh every action
},
test : [function(cmp) {
cmp._testName = "testSkipReplayOnIdenticalRefresh";
this.resetCounter(cmp, "testSkipReplayOnIdenticalRefresh");
}, function(cmp) {
var a = this.executeAction(cmp, "c.fetchDataRecord", {testName:cmp._testName}, function(a) { a.setStorable(); });
$A.test.addWaitFor("1", function() { return $A.test.getText(cmp.find("callbackCounter").getElement()); },
function() {
$A.test.assertEquals("0", $A.test.getText(cmp.find("staticCounter").getElement()));
$A.test.assertEquals("false", $A.test.getText(cmp.find("isFromStorage").getElement()));
$A.storageService.getStorage("actions").get(a.getStorageKey())
.then(function(item){ cmp._originalExpiration = item.expires; });
});
}, function(cmp) {
// reset so next response will be same as first
cmp._testName = "testSkipReplayOnIdenticalRefresh";
this.resetCounter(cmp, "testSkipReplayOnIdenticalRefresh");
// wait for the timer to tick over
var now = new Date().getTime();
$A.test.addWaitFor(true, function() { return now < new Date().getTime(); }, function(){});
}, function(cmp) {
var a = this.executeAction(cmp, "c.fetchDataRecord", {testName:cmp._testName},
function(a){a.setStorable({"executeCallbackIfUpdated":true});});
$A.test.addWaitFor("refreshEnd", function(){return $A.test.getText(cmp.find("refreshEnd").getElement());},
function() {
$A.test.assertEquals("0", $A.test.getText(cmp.find("staticCounter").getElement()));
$A.test.assertEquals("2", $A.test.getText(cmp.find("callbackCounter").getElement()));
$A.test.assertEquals("true", $A.test.getText(cmp.find("isFromStorage").getElement()));
$A.storageService.getStorage("actions").get(a.getStorageKey()).then(
function(item){
if(item.expires <= cmp._originalExpiration){
$A.test.fail("storage expiration was not updated after refresh " +
item.expires+" != "+cmp._originalExpiration);
}
});
});
} ]
},
/**
* If a refresh response differs from what is stored, process the callback.
*/
testRefresh_ResponseDiffersFromStore : {
attributes : {
defaultExpiration : 60,
defaultAutoRefreshInterval : 0 // refresh every action
},
test : [function(cmp) {
cmp._testName = "testDontSkipReplayOnNonIdenticalRefresh";
this.resetCounter(cmp, "testDontSkipReplayOnNonIdenticalRefresh");
}, function(cmp) {
var a = this.executeAction(cmp, "c.fetchDataRecord",
{testName:cmp._testName}, function(a){a.setStorable();});
$A.test.addWaitFor("1", function(){return $A.test.getText(cmp.find("callbackCounter").getElement()); },
function() {
$A.test.assertEquals("0", $A.test.getText(cmp.find("staticCounter").getElement()));
$A.test.assertEquals("false", $A.test.getText(cmp.find("isFromStorage").getElement()));
$A.storageService.getStorage("actions").get(a.getStorageKey()).then(
function(item) { cmp._originalExpiration = item.expires; });
});
}, function(cmp) {
// this response will be different so callback count should be +2 (for get(), then refresh())
var a = this.executeAction(cmp, "c.fetchDataRecord",
{testName:cmp._testName}, function(a){a.setStorable();});
$A.test.addWaitFor("3", function(){ return $A.test.getText(cmp.find("callbackCounter").getElement()); },
function() {
$A.test.assertEquals("1", $A.test.getText(cmp.find("staticCounter").getElement()));
$A.test.assertEquals("false", $A.test.getText(cmp.find("isFromStorage").getElement()));
$A.storageService.getStorage("actions").get(a.getStorageKey()).then(
function(item){
if(item.expires <= cmp._originalExpiration){
$A.test.fail("storage expiration was not updated after refresh");
}
});
});
} ]
},
/**
* If a refresh contains the same response as what is stored, then skip
* replaying the callback. The callback for the stored response is still
* executed.
* Case: Action returns a component instance in the response
*/
testRefresh_ResponseWithComponentsSameAsStored : {
attributes : {
defaultExpiration : 60,
defaultAutoRefreshInterval : 0 // refresh every action
},
test : [function(cmp) {
$A.test.setTestTimeout(30000);
cmp._testName = "testSkipReplayOnIdenticalRefreshWithComponents";
this.resetCounter(cmp, "testSkipReplayOnIdenticalRefreshWithComponents");
}, function(cmp) {
var a = this.executeAction(cmp, "c.fetchDataRecordWithComponents", {testName:cmp._testName},
function(a){a.setStorable();},
function(a){$A.test.clearAndAssertComponentConfigs(a);});
$A.test.addWaitFor("1", function() { return $A.test.getText(cmp.find("callbackCounter").getElement()); },
function() {
$A.test.assertEquals("0", $A.test.getText(cmp.find("staticCounter").getElement()));
$A.test.assertEquals("false", $A.test.getText(cmp.find("isFromStorage").getElement()));
$A.storageService.getStorage("actions").get(a.getStorageKey()).then(
function(item) { cmp._originalExpiration = item.expires; });
});
}, function(cmp) {
// reset so next response will be same as first
cmp._testName = "testSkipReplayOnIdenticalRefreshWithComponents";
this.resetCounter(cmp, "testSkipReplayOnIdenticalRefreshWithComponents");
// wait for the timer to tick over
var now = new Date().getTime();
$A.test.addWaitFor(true, function() { return now < new Date().getTime(); }, function(){});
}, function(cmp) {
var a = this.executeAction(cmp, "c.fetchDataRecordWithComponents", {testName:cmp._testName},
function(a){a.setStorable();},
function(a){$A.test.clearAndAssertComponentConfigs(a);});
$A.test.addWaitFor("refreshEnd", function(){return $A.test.getText(cmp.find("refreshEnd").getElement());},
function() {
$A.test.assertEquals("0", $A.test.getText(cmp.find("staticCounter").getElement()));
$A.test.assertEquals("2", $A.test.getText(cmp.find("callbackCounter").getElement()));
$A.test.assertEquals("true", $A.test.getText(cmp.find("isFromStorage").getElement()));
$A.storageService.getStorage("actions").get(a.getStorageKey()).then(
function(item){
if(item.expires <= cmp._originalExpiration){
$A.test.fail("storage expiration was not updated after refresh " +
item.expires+" != "+cmp._originalExpiration);
}
});
});
} ]
},
/**
* If a action had the same return value but different components were created during the execution of action,
* then the response from refresh action replaces the stored response.
*/
testRefresh_ResponseWithSameReturnValueButAdditionalComponents: {
attributes : {
defaultExpiration : 60,
defaultAutoRefreshInterval : 0 // refresh every action
},
test : [function(cmp) {
$A.test.setTestTimeout(30000);
cmp._testName = "testDontSkipReplayOnNonIdenticalComponentsInRefresh";
this.resetCounter(cmp, "testDontSkipReplayOnNonIdenticalComponentsInRefresh");
}, function(cmp) {
var a = this.executeAction(cmp, "c.fetchDataRecordWithComponents",
{testName:cmp._testName, extraComponentsCreated:true}, function(a){a.setStorable();},
function(a){$A.test.clearAndAssertComponentConfigs(a);});
$A.test.addWaitFor("1", function() { return $A.test.getText(cmp.find("callbackCounter").getElement()); },
function() {
$A.test.assertEquals("0", $A.test.getText(cmp.find("staticCounter").getElement()));
$A.test.assertEquals("false", $A.test.getText(cmp.find("isFromStorage").getElement()));
$A.storageService.getStorage("actions").get(a.getStorageKey()).then(
function(item) { cmp._originalExpiration = item.expires; });
});
}, function(cmp) {
// this response will be different(has extra component but same return value) so callback count should be +2 (for get(), then refresh())
var a = this.executeAction(cmp, "c.fetchDataRecordWithComponents",
{testName:cmp._testName, extraComponentsCreated:true},
function(a){ a.setStorable(); },
function(a){ $A.test.clearAndAssertComponentConfigs(a); });
var completed = false;
$A.test.addWaitFor(
"3",
function() { return $A.test.getText(cmp.find("callbackCounter").getElement()); },
function() {
$A.test.assertEquals("false", $A.test.getText(cmp.find("isFromStorage").getElement()));
$A.storageService.getStorage("actions").get(a.getStorageKey())
.then(function(item) {
if (item.expires <= cmp._originalExpiration) {
$A.test.fail("storage expiration was not updated after refresh");
}
completed = true;
});
}
);
$A.test.addWaitFor(true, function() { return completed; });
} ]
},
/**
* Refresh error not stored, so subsequent refresh will still replay.
*/
testRefreshErrorResponseNotStored : {
mocks : [{
type : "ACTION",
stubs : [{
method : { name : "fetchDataRecord" },
answers : [{
value : "anything really"
},{
error : "java.lang.IllegalStateException"
},{
value : "anything really, but something new"
}]
}]
}],
attributes : {
defaultExpiration : 60,
defaultAutoRefreshInterval : 0 // refresh every action
},
test : [function(cmp) {
$A.test.setTestTimeout(300000);
this.resetCounter(cmp, "testRefreshErrorResponseNotStored");
},function(cmp) {
var a = cmp.get("c.fetchDataRecord");
var that = this;
a.setParams({testName : "testRefreshErrorResponseNotStored"});
a.setStorable();
a.setCallback(cmp, function(action){
//sanity check
$A.test.assertEquals(action.getReturnValue(),"anything really","we are not using the correct stub");
that.findAndSetText(cmp, "callbackCounter",
parseInt(cmp.find("callbackCounter").getElement().innerHTML,10)+1);
});
$A.test.enqueueAction(a);
$A.test.addWaitFor("1", function() { return $A.test.getText(cmp.find("callbackCounter").getElement()); },
function() {
$A.storageService.getStorage("actions").get(a.getStorageKey()).then(
function(item){ cmp._originalExpiration = item.expires; });
});
}, function(cmp) {
var a = cmp.get("c.fetchDataRecord");
var that = this;
a.setParams({testName : "testRefreshErrorResponseNotStored"});
a.setStorable();
a.setCallback(cmp, function(action){
that.findAndSetText(cmp, "callbackCounter",
parseInt(cmp.find("callbackCounter").getElement().innerHTML,10)+1);
});
$A.test.enqueueAction(a);
$A.test.addWaitFor("3", function() { return $A.test.getText(cmp.find("callbackCounter").getElement()); },
function(){
$A.storageService.getStorage("actions").get(a.getStorageKey()).then(
function(item){
$A.test.assertEquals(cmp._originalExpiration, item.expires,
"stored item should not have had expiration modified");
});
});
// wait for the timer to tick over
var now = new Date().getTime();
$A.test.addWaitFor(true, function() { return now < new Date().getTime(); }, function(){});
}, function(cmp) {
var a = cmp.get("c.fetchDataRecord");
var that = this;
a.setParams({testName : "testRefreshErrorResponseNotStored"});
a.setStorable();
a.setCallback(cmp, function(action){
var newCount = parseInt(cmp.find("callbackCounter").getElement().innerHTML,10) + 1;
that.findAndSetText(cmp, "callbackCounter", newCount);
// first action run will be stored refresh action
if (newCount == 4) {
$A.storageService.getStorage("actions").get(a.getStorageKey()).then(
function(item){
$A.test.assertEquals(cmp._originalExpiration, item.expires, "Refresh action not run");
});
}
});
$A.test.enqueueAction(a);
$A.test.addWaitFor("5", function() { return $A.test.getText(cmp.find("callbackCounter").getElement()); },
function(){
$A.storageService.getStorage("actions").get(a.getStorageKey()).then(function(){},
function(item){
// after new action is run, it is stored with new expires time
$A.test.assertTrue(cmp._originalExpiration < item.expires,
"storage expiration was not updated after refresh");
});
});
} ]
}
})
| badlogicmanpreet/aura | aura-components/src/test/components/auraStorageTest/initTest/initTestTest.js | JavaScript | apache-2.0 | 56,275 |
export const createTestDB = `
-- USER
CREATE TABLE IF NOT EXISTS user_app
(
id serial NOT NULL,
user_name character varying(256),
street character varying(256),
street_number character varying(256),
zip_code character varying(5),
city character varying(256),
user_since timestamp with time zone,
customer_since timestamp with time zone,
name character varying(256),
external_uid character varying(256),
province_id integer,
CONSTRAINT user_app_pkey PRIMARY KEY (id)
);
-- VISIT
CREATE TABLE IF NOT EXISTS visit
(
id character varying(256) NOT NULL,
user_app_id integer,
time_spent time without time zone,
datetime timestamp with time zone,
device character varying(256),
application character varying(256),
CONSTRAINT visit_pkey PRIMARY KEY (id),
CONSTRAINT fk_child_user_app_id FOREIGN KEY (user_app_id)
REFERENCES user_app (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
);
-- PAGEVIEW
CREATE TABLE IF NOT EXISTS page_view
(
id character varying(256) NOT NULL,
visit_id character varying(256),
time_spent time without time zone,
datetime timestamp with time zone,
device character varying(256),
application character varying(256),
page_name character varying(256),
CONSTRAINT page_view_pkey PRIMARY KEY (id),
CONSTRAINT fk_child_visit_id FOREIGN KEY (visit_id)
REFERENCES visit (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
);
`;
| innowatio/iwwa-lambda-interactions-rds | scripts/create-tables.js | JavaScript | apache-2.0 | 1,693 |
var mongo = require('mongoskin');
module.exports = mongo.db('localhost:27017/gtags?auto_reconnect');
| silkroad/gtags | src/db.js | JavaScript | apache-2.0 | 102 |
import React from 'react';
import ReactDOM from 'react-dom';
import ChatActions from '../events/chat-actions';
var $ = require('jquery');
var NewGroupDialog = React.createClass({
createGroup: function () {
var groupName = ReactDOM.findDOMNode(this.refs.groupName).value.trim();
if (groupName && !/\s/.test(groupName)) {
$.ajax({
type: "POST",
url: "/json/group/add",
data: JSON.stringify(groupName),
contentType: "application/json",
success: function (group) {
ChatActions.newGroup(group, true);
},
fail: function (e) {
console.error(e);
}
});
this.props.trigger.setState({
isOverlayShown: false
});
ReactDOM.findDOMNode(this.refs.groupName).value = "";
}
},
onKeyPress: function (event) {
if (event.which == 13) {
this.createGroup();
}
},
componentDidMount: function () {
$(ReactDOM.findDOMNode(this.refs.groupName)).focus();
},
render: function () {
return (
<div className="new-group-popover">
<input ref="groupName" type="text" className="group-name" placeholder="Name..."
onKeyPress={this.onKeyPress}/>
<div className="group-label">Must be 21 characters or less. No spaces or periods.</div>
<a className='btn btn-default btn-sm' onClick={this.createGroup}>Create group</a>
</div>
);
}
});
export default NewGroupDialog; | JetChat/JetChat | public/javascripts/components/new-group-dialog.js | JavaScript | apache-2.0 | 1,676 |
'use strict';
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
concat: {
options: {
separator: ';\n'
},
distEpg: {
src: ['src/epg.js', 'src/ng-stay.js', 'src/calendar.js', 'src/search.js'],
dest: 'dist/js/<%= pkg.name %>.js'
},
distEpgOmb: {
src: ['src/epg.js', 'src/stay-omb.js', 'src/calendar.js', 'src/search.js'],
dest: 'dist/js/<%= pkg.name %>-omb.js'
}
},
uglify: {
options: {
preserveComments: 'some'
},
dist: {
files: {
'dist/js/<%= pkg.name %>.min.js': ['<%= concat.distEpg.dest %>'],
'dist/js/<%= pkg.name %>-omb.min.js': ['<%= concat.distEpgOmb.dest %>'],
'dist/js/ng-infinite-scroll-h-fix.min.js': ['js/ng-infinite-scroll-h-fix.js']
}
}
},
jshint: {
files: ['Gruntfile.js', 'src/**/*.js', 'test/**/*.js'],
options: {
// options here to override JSHint defaults
globalstrict: true,
globals: {
console: false,
module: false,
document: false,
window: false,
CustomEvent: false,
angular: false,
jsHandler: false,
fireTvJsHandler: false,
setPosition: true,
setTimeout: true,
// TODO: maybe can remove these globals?
epgDebug: true,
menuOpen: true,
menuProgId: true,
detailsOpen: true,
setPopup: true,
popHide: true,
preventProgramBindings: true
}
}
},
'string-replace': {
dist: {
files: {
'dist/guide.html': ['guide.html'],
'dist/guide-omb.html': ['guide-omb.html']
},
options: {
replacements: [{
pattern: /<script src="src\/ng-stay.js"[^]*<\/script>/m,
replacement: '<script src="js/<%= pkg.name%>.js"></script>'
}, {
pattern: /<script src="src\/stay-omb.js"[^]*<\/script>/m,
replacement: '<script src="js/<%= pkg.name%>-omb.js"></script>'
}, {
pattern: /<script src="js\/(.*).js".*<\/script>/,
replacement: '<script src="js/$1.min.js"></script>'
}, {
pattern: /<script src="bower_components\/(.*).js".*<\/script>/g,
replacement: '<script src="js/$1.min.js"></script>'
}]
}
}
},
copy: {
dist: {
files: [{
expand: true,
src: [ 'css/**/*', 'images/**/*', 'views/**/*', 'js/**/*' ],
dest: 'dist'
}, {
expand: true,
cwd: 'bower_components',
src: [ '**/*.min.js', '!angular-bootstrap/ui-bootstrap.min.js' ],
dest: 'dist/js'
}, {
expand: true,
cwd: 'src',
src: [ 'epg-device.js', 'epg-firetv.js' ],
dest: 'dist/js'
}]
},
'push-gh-pages': {
files: [{
expand: true,
cwd: 'dist',
src: [ '**/*' ],
dest: 'c:/git/mythling-gh-pages/epg/'
}]
},
'push-mythling': {
files: [{
expand: true,
cwd: 'dist',
src: [ '**/*', '!**/demo/**', '!js/mythling-epg.min.js', '!mythling-epg-omb.min.js' ],
dest: 'c:/git/mythling/assets/mythling-epg/'
}]
}
},
compress: {
dist: {
options: {
mode: 'zip',
archive: 'c:/git/mythling-gh-pages/epg/dist/<%= pkg.name %>-<%= pkg.version %>.zip'
},
expand: true,
cwd: 'dist/',
src: [ '**/*', '!**/demo/**' ]
}
},
watch: {
files: ['<%= jshint.files %>'],
tasks: ['jshint']
},
'demo-data': { // grunt demo-data --mythling-password=<pw>
dist: {
baseUrl: 'http://192.168.0.69',
iconBaseUrl: 'http://192.168.0.69:6544',
user: 'mythling',
password: '<%= grunt.option("mythling-password") %>',
startDate: new Date(),
guideInterval: 24,
requestCount: 14, // 2 weeks at 24 hours per
mythlingServices: true,
dest: 'dist/demo/guide-data'
}
}
});
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-compress');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-string-replace');
grunt.loadTasks('tasks');
grunt.registerTask('test', ['jshint']);
grunt.registerTask('default', ['jshint', 'concat', 'uglify', 'string-replace', 'copy:dist']);
grunt.registerTask('push', ['copy:push-gh-pages', 'copy:push-mythling', 'compress']);
}; | oakesville/mythling-epg | Gruntfile.js | JavaScript | apache-2.0 | 4,860 |
'use strict';
function SwaggerResolver() {
let fs = require('fs');
let YAML = require('js-yaml');
let resolve = require('json-refs').resolveRefs;
let self = {};
self.resolve = function(path, done) {
if(!fs.existsSync(path)) {
return done(null, {});
}
let options = {
location: path,
loaderOptions: {
processContent: (content, callback) => {
let parsed = YAML.load(content.text);
callback(null, parsed);
}
}
};
let root = YAML.load(fs.readFileSync(path).toString());
resolve(root, options).then((results) => {
let refs = Object.keys(results.refs);
for(var x = 0; x < refs.length; x++) {
let ref = results.refs[refs[x]];
// Dirty hack to resolve https://github.com/whitlockjc/json-refs/issues/115
if(ref.error && !ref.error.startsWith('JSON Pointer points to missing location: #/definitions')) {
return done(new Error(ref.error));
}
}
done(null, results.resolved);
}, done);
};
return Object.freeze(self);
}
module.exports = SwaggerResolver;
| techops-peopledata/td.core | lib/swagger/swaggerResolver.js | JavaScript | apache-2.0 | 1,110 |
import {
details,
mergeInEmptyDraft,
defaultReactions,
} from "../detail-definitions.js";
import * as jsonLdUtils from "../../app/service/jsonld-utils.js";
import vocab from "../../app/service/vocab.js";
import { getIn } from "../../app/utils.js";
import { sparqlQuery } from "../../app/sparql-builder-utils.js";
import ico36_uc_transport_offer from "../../images/won-icons/ico36_uc_transport_offer.svg";
export const goodsTransportOffer = {
identifier: "goodsTransportOffer",
label: "Offer goods transport",
icon: ico36_uc_transport_offer,
doNotMatchAfter: jsonLdUtils.findLatestIntervallEndInJsonLdOrNowAndAddMillis,
draft: {
...mergeInEmptyDraft({
content: {
type: ["http://www.wikidata.org/entity/Q7590"],
},
}),
},
reactions: {
...defaultReactions,
[vocab.CHAT.ChatSocketCompacted]: {
[vocab.CHAT.ChatSocketCompacted]: {
useCaseIdentifiers: ["goodsTransportSearch", "persona"],
refuseOwned: true,
},
},
},
details: {
title: { ...details.title },
location: { ...details.location },
},
seeksDetails: {
tags: { ...details.tags },
description: { ...details.description },
},
generateQuery: (draft, resultName) => {
const location = getIn(draft, ["content", "location"]);
let filter;
if (location && location.lat && location.lng) {
filter = {
// to select seeks-branch
prefixes: {
won: vocab.defaultContext["won"],
s: vocab.defaultContext["s"],
geo: "http://www.bigdata.com/rdf/geospatial#",
xsd: "http://www.w3.org/2001/XMLSchema#",
con: vocab.defaultContext["con"],
match: vocab.defaultContext["match"],
},
operations: [
`${resultName} a won:Atom.`,
`${resultName} a <http://www.wikidata.org/entity/Q319224>.`,
`${resultName} match:seeks ?seeks.`,
"?seeks con:travelAction/s:fromLocation ?fromLocation.",
"?seeks con:travelAction/s:toLocation ?toLocation.",
"?fromLocation s:geo ?fromLocation_geo.",
"?fromLocation_geo s:latitude ?fromLocation_lat;",
"s:longitude ?fromLocation_lon;",
`bind (abs(xsd:decimal(?fromLocation_lat) - ${
location.lat
}) as ?fromLatDiffRaw)`,
`bind (abs(xsd:decimal(?fromLocation_lon) - ${
location.lng
}) as ?fromLonDiff)`,
"bind (if ( ?fromLatDiffRaw > 180, 360 - ?fromLatDiffRaw, ?fromLatDiffRaw ) as ?fromLatDiff)",
"bind ( ?fromLatDiff * ?fromLatDiff + ?fromLonDiff * ?fromLonDiff as ?fromLocation_geoDistanceScore)",
"?toLocation s:geo ?toLocation_geo.",
"?toLocation_geo s:latitude ?toLocation_lat;",
"s:longitude ?toLocation_lon;",
`bind (abs(xsd:decimal(?toLocation_lat) - ${
location.lat
}) as ?toLatDiffRaw)`,
`bind (abs(xsd:decimal(?toLocation_lon) - ${
location.lng
}) as ?toLonDiff)`,
"bind (if ( ?toLatDiffRaw > 180, 360 - ?toLatDiffRaw, ?toLatDiffRaw ) as ?toLatDiff)",
"bind ( ?toLatDiff * ?toLatDiff + ?toLonDiff * ?toLonDiff as ?toLocation_geoDistanceScore)",
"bind (?toLocation_geoDistanceScore + ?fromLocation_geoDistanceScore as ?distScore)",
],
};
} else {
filter = {
// to select seeks-branch
prefixes: {
won: vocab.defaultContext["won"],
},
operations: [
`${resultName} a won:Atom.`,
`${resultName} a <http://www.wikidata.org/entity/Q319224>.`,
],
};
}
return sparqlQuery({
prefixes: filter.prefixes,
distinct: true,
variables: [resultName],
where: filter.operations,
orderBy: [
{
order: "ASC",
variable: "?distScore",
},
],
});
},
};
| researchstudio-sat/webofneeds | webofneeds/won-owner-webapp/src/main/webapp/config/usecases/uc-goods-transport-offer.js | JavaScript | apache-2.0 | 3,892 |
$(document).ready(function()
{
setRequiredFields();
/* Enable default ajax options. */
$.setAjaxForm('#ajaxForm');
$.setAjaxDeleter('.deleter');
$.setReload('.reload');
$.setReloadDeleter('.reloadDeleter');
$.setAjaxLoader('.loadInModal', '#ajaxModal');
/* run code if desktop. */
if(typeof $.ipsStart != 'undefined')
{
/* Set ping keep online. */
setInterval('ping()', 1000 * config.pingInterval);
ping();
}
else
{
/* bind app-btn events. */
$(document).on('click', '.app-btn', function(event)
{
if($(this).attr('data-id'))
{
$.openEntry($(this).attr('data-id'), $(this).data('url') || $(this).attr('href'));
return false;
}
});
}
/* Enable tooltip */
$('body').tooltip({html: true,selector: "[data-toggle='tooltip']",container: "body"});
fixTableHeader();
condensedForm();
setPageActions();
/* Reload modal. */
$(document).on('click', '.reloadModal', function(){$.reloadAjaxModal()});
/* Support iframe modal shortcut */
$(document).on('click', 'a.iframe', function(e)
{
var $this = $(this);
if (!$this.data('zui.modaltrigger'))
{
var modalWidth = '';
var modalHeight = '';
if($this.attr('width') != 'undefined') modalWidth = $this.attr('width');
if($this.attr('height') != 'undefined') modalHeight = $this.attr('width');
$this.modalTrigger(
{
width: modalWidth,
height: modalHeight,
show: true
});
}
else
{
$this.trigger('.toggle.' + 'zui.modaltrigger');
}
e.preventDefault();
});
setMenu();
initSearch();
});
$(document).on('keyup', function(e)
{
if(e.keyCode == '37')
{
/* left, go to pre object. */
if($('#ajaxModal').css('display') == 'block') return false;
preLink = ($('#pre').attr("href"));
if(typeof(preLink) != 'undefined') location.href = preLink;
}
if(e.keyCode == '39')
{
/* right, go to next object. */
if($('#ajaxModal').css('display') == 'block') return false;
nextLink = ($('#next').attr("href"));
if(typeof(nextLink) != 'undefined') location.href = nextLink;
}
});
/**
* Show or hide more items.
*
* @access public
* @return void
*/
function switchMore()
{
$('#search').width($('#search').width()).focus();
$('#moreMenu').width($('#defaultMenu').outerWidth());
$('#searchResult').toggleClass('show-more');
}
/**
* Init search form
*
* @access public
* @return void
*/
function initSearch()
{
$searchTab = $('#bysearchTab');
if($searchTab.data('initSearch')) return;
if(!$searchTab.closest('#menu').length)
{
$('#menu > ul:first').append($searchTab);
}
var $queryBox = $('#querybox');
if(!$queryBox.length)
{
$queryBox = $("<div id='querybox' class='hidden'/>").insertAfter($('#menu'));
}
if(v && v.mode == 'bysearch')
{
$('#menu > ul > li.active').removeClass('active');
ajaxGetSearchForm($queryBox);
$searchTab.addClass('active').find('a').attr('href', '#bysearch');
$queryBox.removeClass('hidden');
}
$searchTab.on('click', function()
{
if($searchTab.hasClass('active'))
{
var $oldTab = $searchTab.data('oldTab');
$searchTab.removeClass('active');
if($oldTab)
{
$oldTab.addClass('active');
}
else
{
$searchTab.addClass('selected');
}
$queryBox.addClass('hidden');
}
else
{
$searchTab.data('oldTab', $('#menu > ul > li.active').removeClass('active')).addClass('active');
ajaxGetSearchForm($queryBox);
$queryBox.removeClass('hidden');
}
});
$searchTab.data('initSearch', true);
}
/**
* Ajax get search form
*
* @param string $queryBox
* @param callback $callback
* @access public
* @return void
*/
function ajaxGetSearchForm($queryBox, callback)
{
if(!$queryBox) $queryBox = $('#querybox');
if($queryBox.html() == '')
{
$.get(createLink('search', 'buildForm'), function(data)
{
$queryBox.html(data);
callback && callback();
});
}
}
/**
* Set menu
*
* @access public
* @return void
*/
function setMenu()
{
$menuTitle = $('#menuTitle');
$menu = $('#menu');
if($menu.length && $menuTitle.length)
{
$menu.children('ul.nav:not(.pull-right)').hide();
$menu.prepend($menuTitle.addClass('nav'));
}
}
/**
* Start cron.
*
* @access public
* @return void
*/
function startCron()
{
$.ajax({type:"GET", timeout:100, url:createLink('cron', 'ajaxExec')});
}
| leowh/colla | www/js/my.js | JavaScript | apache-2.0 | 5,007 |
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux'
import page from './page'
import {fetchGraphData} from 'store/entities/hmqGraph/actions'
function mapStateToProps( state ) {
const {hmqGraph, hmqStatistic} = state
return {hmqGraph, hmqStatistic};
}
function mapDispatchToProps(dispatch) {
const actions = bindActionCreators({fetchGraphData}, dispatch)
return {...actions};
}
export default connect(mapStateToProps, mapDispatchToProps)(page);
| humaniq/humaniq-pwa-website | src/components/pages/HmqHome/container.js | JavaScript | apache-2.0 | 481 |
function comment(avatar, nickname, msg, userid) {
var data;
if (CheckUser()) {
data = '<div class="comment">'
+ '<div class="col-lg-2 col-md-2 col-sm-2 col-xs-2">'
+ '<img src="' + avatar + '"> </div>'
+ '<div class="col-lg-2 col-md-2 col-sm-2 col-xs-2">'
+ '<p class="big"> ' + nickname + '</div>'
+ '<div class="col-lg-6 col-md-6 col-sm-6 col-xs-6">'
+ '<p class="big" >' + msg + '</p></div>'
+ '<div class="col-lg-2 col-md-2 col-sm-2 col-xs-2 send">'
+ '<button class="btn btn-info big" onclick="send(this)">送给Ta</button>'
+ '<p class="hidden">' + userid + '</p>'
+ '</div> </div>';
}
else {
data = '<div class="comment">'
+ '<div class="col-lg-2 col-md-2 col-sm-2 col-xs-2">'
+ '<img src="' + avatar + '"> </div>'
+ '<div class="col-lg-2 col-md-2 col-sm-2 col-xs-2">'
+ '<p class="big"> ' + nickname + '</div>'
+ '<div class="col-lg-6 col-md-6 col-sm-6 col-xs-6">'
+ '<p class="big" >' + msg + '</p></div>'
+ '</div> '
+ '<p class="hidden">' + userid + '</p>';
}
return data;
}
function details(page) {
var url = '../../PHP/Service/GiveService/GetComment.php';
var id = getCookie('master');
$.getJSON(url, {
page: page,
giveid: id
}, function (data) {
var num = data.num;
var sum = 0;
var userid;
var avatar;
var msg;
$("#comment")[0].innerHTML = '';
setInterval(function () {
if (sum != num) {
msg = data[sum].GetInformation;
userid = data[sum].UserId;
url = '../../PHP/Service/UserService/GetData.php?userid=' + userid;
$.getJSON(url, function (data2) {
avatar = data2.UserPhoto;
msg = comment(avatar, data2.NickName, msg, userid);
$("#comment")[0].innerHTML += msg;
});
sum++;
}
}, 1);
});
$("#loading").fadeOut();
}
function submit() {
var url = '../../PHP/Service/GiveService/Get.php';
var id = getCookie('master');
$.post(url, {
giveid: id,
getinformation: $("#input-content").val()
}, function (data) {
if (data[0] != '1') {
$("#word").text(data);
}
else {
location.reload();
}
})
}
function send(obj) {
var id = obj.nextElementSibling.innerHTML;
var giveid = getCookie('master');
$.post('../../PHP/Service/GiveService/Select.php', {
giveid: giveid,
getuser: id
}, function (data) {
if (data[0] == '1') {
$("#alert").click();
}
})
}
function CheckUser() {
var userid = getCookie('userid');
var id = getCookie('masterID');
if (userid == id) {
$("#com").addClass('hidden');
return 1;
}
else return 0;
}
| yuban12315/LoveUniversity | js/service/details.js | JavaScript | apache-2.0 | 3,053 |
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you 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.
*/
/* Finite Field arithmetic */
/* AMCL mod p functions */
var FP = function(ctx) {
"use strict";
/* General purpose Constructor */
var FP = function(x) {
if (x instanceof FP) {
this.f = new ctx.BIG(x.f);
this.XES = x.XES;
} else {
this.f = new ctx.BIG(x);
this.XES = 1;
if (!this.f.iszilch()) this.nres();
}
};
FP.NOT_SPECIAL = 0;
FP.PSEUDO_MERSENNE = 1;
FP.GENERALISED_MERSENNE = 2;
FP.MONTGOMERY_FRIENDLY = 3;
FP.ZERO = 0;
FP.ONE = 1;
FP.SPARSER = 2;
FP.SPARSE = 3;
FP.DENSE = 4;
FP.MODBITS = ctx.config["@NBT"];
FP.MOD8 = ctx.config["@M8"];
FP.MODTYPE = ctx.config["@MT"];
FP.FEXCESS = (1 << ctx.config["@SH"]) - 1; // 2^(BASEBITS*NLEN-MODBITS)-1
FP.OMASK = -1 << FP.TBITS;
FP.TBITS = FP.MODBITS % ctx.BIG.BASEBITS;
FP.TMASK = (1 << FP.TBITS) - 1;
FP.prototype = {
/* set this=0 */
zero: function() {
this.XES = 1;
this.f.zero();
},
/* copy from a ctx.BIG in ROM */
rcopy: function(y) {
this.f.rcopy(y);
this.nres();
},
/* copy from another ctx.BIG */
bcopy: function(y) {
this.f.copy(y);
this.nres();
},
/* copy from another FP */
copy: function(y) {
this.XES = y.XES;
this.f.copy(y.f);
},
/* conditional swap of a and b depending on d */
cswap: function(b, d) {
this.f.cswap(b.f, d);
var t,
c = d;
c = ~(c - 1);
t = c & (this.XES ^ b.XES);
this.XES ^= t;
b.XES ^= t;
},
/* conditional copy of b to a depending on d */
cmove: function(b, d) {
var c = d;
c = ~(c - 1);
this.f.cmove(b.f, d);
this.XES ^= (this.XES ^ b.XES) & c;
},
/* convert to Montgomery n-residue form */
nres: function() {
var r, d;
if (FP.MODTYPE != FP.PSEUDO_MERSENNE && FP.MODTYPE != FP.GENERALISED_MERSENNE) {
r = new ctx.BIG();
r.rcopy(ctx.ROM_FIELD.R2modp);
d = ctx.BIG.mul(this.f, r);
this.f.copy(FP.mod(d));
this.XES = 2;
} else {
this.XES = 1;
}
return this;
},
/* convert back to regular form */
redc: function() {
var r = new ctx.BIG(0),
d,
w;
r.copy(this.f);
if (FP.MODTYPE != FP.PSEUDO_MERSENNE && FP.MODTYPE != FP.GENERALISED_MERSENNE) {
d = new ctx.DBIG(0);
d.hcopy(this.f);
w = FP.mod(d);
r.copy(w);
}
return r;
},
/* convert this to string */
toString: function() {
var s = this.redc().toString();
return s;
},
/* test this=0 */
iszilch: function() {
var c = new FP(0);
c.copy(this);
c.reduce();
return c.f.iszilch();
},
/* reduce this mod Modulus */
reduce: function() {
var q,
carry,
sr,
sb,
m = new ctx.BIG(0);
m.rcopy(ctx.ROM_FIELD.Modulus);
var r = new ctx.BIG(0);
r.rcopy(ctx.ROM_FIELD.Modulus);
this.f.norm();
if (this.XES > 16) {
q = FP.quo(this.f, m);
carry = r.pmul(q);
r.w[ctx.BIG.NLEN - 1] += carry << ctx.BIG.BASEBITS; // correction - put any carry out back in again
this.f.sub(r);
this.f.norm();
sb = 2;
} else {
sb = FP.logb2(this.XES - 1);
}
m.fshl(sb);
while (sb > 0) {
// constant time...
sr = ctx.BIG.ssn(r, this.f, m); // optimized combined shift, subtract and norm
this.f.cmove(r, 1 - sr);
sb--;
}
this.XES = 1;
},
/* set this=1 */
one: function() {
this.f.one();
this.nres();
},
/* normalise this */
norm: function() {
return this.f.norm();
},
/* this*=b mod Modulus */
mul: function(b) {
var d;
if (this.XES * b.XES > FP.FEXCESS) {
this.reduce();
}
d = ctx.BIG.mul(this.f, b.f);
this.f.copy(FP.mod(d));
this.XES = 2;
return this;
},
/* this*=c mod Modulus where c is an int */
imul: function(c) {
var s = false,
d,
n;
if (c < 0) {
c = -c;
s = true;
}
if (FP.MODTYPE == FP.PSEUDO_MERSENNE || FP.MODTYPE == FP.GENERALISED_MERSENNE) {
d = this.f.pxmul(c);
this.f.copy(FP.mod(d));
this.XES = 2;
} else {
if (this.XES * c <= FP.FEXCESS) {
this.f.pmul(c);
this.XES *= c;
} else {
n = new FP(c);
this.mul(n);
}
}
if (s) {
this.neg();
this.norm();
}
return this;
},
/* this*=this mod Modulus */
sqr: function() {
var d, t;
if (this.XES * this.XES > FP.FEXCESS) {
this.reduce();
}
d = ctx.BIG.sqr(this.f);
t = FP.mod(d);
this.f.copy(t);
this.XES = 2;
return this;
},
/* this+=b */
add: function(b) {
this.f.add(b.f);
this.XES += b.XES;
if (this.XES > FP.FEXCESS) {
this.reduce();
}
return this;
},
/* this=-this mod Modulus */
neg: function() {
var m = new ctx.BIG(0),
sb;
m.rcopy(ctx.ROM_FIELD.Modulus);
sb = FP.logb2(this.XES - 1);
m.fshl(sb);
this.XES = (1 << sb) + 1;
this.f.rsub(m);
if (this.XES > FP.FEXCESS) {
this.reduce();
}
return this;
},
/* this-=b */
sub: function(b) {
var n = new FP(0);
n.copy(b);
n.neg();
this.add(n);
return this;
},
rsub: function(b) {
var n = new FP(0);
n.copy(this);
n.neg();
this.copy(b);
this.add(n);
},
/* this/=2 mod Modulus */
div2: function() {
var p;
if (this.f.parity() === 0) {
this.f.fshr(1);
} else {
p = new ctx.BIG(0);
p.rcopy(ctx.ROM_FIELD.Modulus);
this.f.add(p);
this.f.norm();
this.f.fshr(1);
}
return this;
},
// return this^(p-3)/4 or this^(p-5)/8
// See https://eprint.iacr.org/2018/1038
fpow: function() {
var i, j, k, bw, w, c, nw, lo, m, n;
var xp = [];
var ac = [1, 2, 3, 6, 12, 15, 30, 60, 120, 240, 255];
// phase 1
xp[0] = new FP(this); // 1
xp[1] = new FP(this);
xp[1].sqr(); // 2
xp[2] = new FP(xp[1]);
xp[2].mul(this); //3
xp[3] = new FP(xp[2]);
xp[3].sqr(); // 6
xp[4] = new FP(xp[3]);
xp[4].sqr(); // 12
xp[5] = new FP(xp[4]);
xp[5].mul(xp[2]); // 15
xp[6] = new FP(xp[5]);
xp[6].sqr(); // 30
xp[7] = new FP(xp[6]);
xp[7].sqr(); // 60
xp[8] = new FP(xp[7]);
xp[8].sqr(); // 120
xp[9] = new FP(xp[8]);
xp[9].sqr(); // 240
xp[10] = new FP(xp[9]);
xp[10].mul(xp[5]); // 255
n = FP.MODBITS;
if (FP.MODTYPE == FP.GENERALISED_MERSENNE)
// Goldilocks ONLY
n /= 2;
if (FP.MOD8 == 5) {
n -= 3;
c = (ctx.ROM_FIELD.MConst + 5) / 8;
} else {
n -= 2;
c = (ctx.ROM_FIELD.MConst + 3) / 4;
}
bw = 0;
w = 1;
while (w < c) {
w *= 2;
bw += 1;
}
k = w - c;
i = 10;
var key = new FP(0);
if (k != 0) {
while (ac[i] > k) i--;
key.copy(xp[i]);
k -= ac[i];
}
while (k != 0) {
i--;
if (ac[i] > k) continue;
key.mul(xp[i]);
k -= ac[i];
}
// phase 2
xp[1].copy(xp[2]);
xp[2].copy(xp[5]);
xp[3].copy(xp[10]);
j = 3;
m = 8;
nw = n - bw;
var t = new FP(0);
while (2 * m < nw) {
t.copy(xp[j++]);
for (i = 0; i < m; i++) t.sqr();
xp[j].copy(xp[j - 1]);
xp[j].mul(t);
m *= 2;
}
lo = nw - m;
var r = new FP(xp[j]);
while (lo != 0) {
m /= 2;
j--;
if (lo < m) continue;
lo -= m;
t.copy(r);
for (i = 0; i < m; i++) t.sqr();
r.copy(t);
r.mul(xp[j]);
}
// phase 3
if (bw != 0) {
for (i = 0; i < bw; i++) r.sqr();
r.mul(key);
}
if (FP.MODTYPE == FP.GENERALISED_MERSENNE) {
// Goldilocks ONLY
key.copy(r);
r.sqr();
r.mul(this);
for (i = 0; i < n + 1; i++) r.sqr();
r.mul(key);
}
return r;
},
/* this=1/this mod Modulus */
inverse: function() {
if (FP.MODTYPE == FP.PSEUDO_MERSENNE || FP.MODTYPE == FP.GENERALISED_MERSENNE) {
var y = this.fpow();
if (FP.MOD8 == 5) {
var t = new FP(this);
t.sqr();
this.mul(t);
y.sqr();
}
y.sqr();
y.sqr();
this.mul(y);
return this;
} else {
var m2 = new ctx.BIG(0);
m2.rcopy(ctx.ROM_FIELD.Modulus);
m2.dec(2);
m2.norm();
this.copy(this.pow(m2));
return this;
}
},
/* return TRUE if this==a */
equals: function(a) {
var ft = new FP(0);
ft.copy(this);
var sd = new FP(0);
sd.copy(a);
ft.reduce();
sd.reduce();
if (ctx.BIG.comp(ft.f, sd.f) === 0) {
return true;
}
return false;
},
/* return this^e mod Modulus */
pow: function(e) {
var i,
w = [],
tb = [],
t = new ctx.BIG(e),
nb,
lsbs,
r;
this.norm();
t.norm();
nb = 1 + Math.floor((t.nbits() + 3) / 4);
for (i = 0; i < nb; i++) {
lsbs = t.lastbits(4);
t.dec(lsbs);
t.norm();
w[i] = lsbs;
t.fshr(4);
}
tb[0] = new FP(1);
tb[1] = new FP(this);
for (i = 2; i < 16; i++) {
tb[i] = new FP(tb[i - 1]);
tb[i].mul(this);
}
r = new FP(tb[w[nb - 1]]);
for (i = nb - 2; i >= 0; i--) {
r.sqr();
r.sqr();
r.sqr();
r.sqr();
r.mul(tb[w[i]]);
}
r.reduce();
return r;
},
/* return jacobi symbol (this/Modulus) */
jacobi: function() {
var p = new ctx.BIG(0),
w = this.redc();
p.rcopy(ctx.ROM_FIELD.Modulus);
return w.jacobi(p);
},
/* return sqrt(this) mod Modulus */
sqrt: function() {
var i, v, r;
this.reduce();
if (FP.MOD8 == 5) {
i = new FP(0);
i.copy(this);
i.f.shl(1);
if (FP.MODTYPE == FP.PSEUDO_MERSENNE || FP.MODTYPE == FP.GENERALISED_MERSENNE) {
v = i.fpow();
} else {
var b = new ctx.BIG(0);
b.rcopy(ctx.ROM_FIELD.Modulus);
b.dec(5);
b.norm();
b.shr(3);
v = i.pow(b);
}
i.mul(v);
i.mul(v);
i.f.dec(1);
r = new FP(0);
r.copy(this);
r.mul(v);
r.mul(i);
r.reduce();
return r;
} else {
if (FP.MODTYPE == FP.PSEUDO_MERSENNE || FP.MODTYPE == FP.GENERALISED_MERSENNE) {
var r = this.fpow();
r.mul(this);
return r;
} else {
var b = new ctx.BIG(0);
b.rcopy(ctx.ROM_FIELD.Modulus);
b.inc(1);
b.norm();
b.shr(2);
return this.pow(b);
}
}
},
};
FP.logb2 = function(v) {
var r;
v |= v >>> 1;
v |= v >>> 2;
v |= v >>> 4;
v |= v >>> 8;
v |= v >>> 16;
v = v - ((v >>> 1) & 0x55555555);
v = (v & 0x33333333) + ((v >>> 2) & 0x33333333);
r = (((v + (v >>> 4)) & 0xf0f0f0f) * 0x1010101) >>> 24;
return r;
};
FP.quo = function(n, m) {
var num,
den,
hb = ctx.BIG.CHUNK >> 1;
if (FP.TBITS < hb) {
var sh = hb - FP.TBITS;
num = (n.w[ctx.BIG.NLEN - 1] << sh) | (n.w[ctx.BIG.NLEN - 2] >> (ctx.BIG.BASEBITS - sh));
den = (m.w[ctx.BIG.NLEN - 1] << sh) | (m.w[ctx.BIG.NLEN - 2] >> (ctx.BIG.BASEBITS - sh));
} else {
num = n.w[ctx.BIG.NLEN - 1];
den = m.w[ctx.BIG.NLEN - 1];
}
return Math.floor(num / (den + 1));
};
/* reduce a ctx.DBIG to a ctx.BIG using a "special" modulus */
FP.mod = function(d) {
var b = new ctx.BIG(0),
i,
t,
v,
tw,
tt,
lo,
carry,
m,
dd;
if (FP.MODTYPE == FP.PSEUDO_MERSENNE) {
t = d.split(FP.MODBITS);
b.hcopy(d);
if (ctx.ROM_FIELD.MConst != 1) {
v = t.pmul(ctx.ROM_FIELD.MConst);
} else {
v = 0;
}
t.add(b);
t.norm();
tw = t.w[ctx.BIG.NLEN - 1];
t.w[ctx.BIG.NLEN - 1] &= FP.TMASK;
t.inc(ctx.ROM_FIELD.MConst * ((tw >> FP.TBITS) + (v << (ctx.BIG.BASEBITS - FP.TBITS))));
// b.add(t);
t.norm();
return t;
}
if (FP.MODTYPE == FP.MONTGOMERY_FRIENDLY) {
for (i = 0; i < ctx.BIG.NLEN; i++) {
d.w[ctx.BIG.NLEN + i] += d.muladd(
d.w[i],
ctx.ROM_FIELD.MConst - 1,
d.w[i],
ctx.BIG.NLEN + i - 1
);
}
for (i = 0; i < ctx.BIG.NLEN; i++) {
b.w[i] = d.w[ctx.BIG.NLEN + i];
}
b.norm();
}
if (FP.MODTYPE == FP.GENERALISED_MERSENNE) {
// GoldiLocks Only
t = d.split(FP.MODBITS);
b.hcopy(d);
b.add(t);
dd = new ctx.DBIG(0);
dd.hcopy(t);
dd.shl(FP.MODBITS / 2);
tt = dd.split(FP.MODBITS);
lo = new ctx.BIG();
lo.hcopy(dd);
b.add(tt);
b.add(lo);
//b.norm();
tt.shl(FP.MODBITS / 2);
b.add(tt);
carry = b.w[ctx.BIG.NLEN - 1] >> FP.TBITS;
b.w[ctx.BIG.NLEN - 1] &= FP.TMASK;
b.w[0] += carry;
b.w[Math.floor(224 / ctx.BIG.BASEBITS)] += carry << 224 % ctx.BIG.BASEBITS;
b.norm();
}
if (FP.MODTYPE == FP.NOT_SPECIAL) {
m = new ctx.BIG(0);
m.rcopy(ctx.ROM_FIELD.Modulus);
b.copy(ctx.BIG.monty(m, ctx.ROM_FIELD.MConst, d));
}
return b;
};
return FP;
};
// CommonJS module exports
if (typeof module !== "undefined" && typeof module.exports !== "undefined") {
module.exports.FP = FP;
}
| miracl/amcl | version3/js/fp.js | JavaScript | apache-2.0 | 14,959 |
/**
* Default client.
*/
module.exports = function (_) {
var xhrClient = require('./xhr')(_);
return function (request) {
return (request.client || xhrClient)(request);
};
};
| gefangshuai/WiseMenuFramework | server-platform-app/src/main/resources/public/js/plugins/vue-resource/src/client/default.js | JavaScript | apache-2.0 | 201 |
import $ from 'jquery'
export let coords = {
corner: null,
top: null,
left: null,
bottom: null,
right: null
}
/**
* init selector element
*/
export function initSelector(eBase) {
eBase.etable.selector.top = $("<div>").css({height: 2}).addClass("etable-selector2")
eBase.etable.selector.left = $("<div>").css({width: 2}).addClass("etable-selector2")
eBase.etable.selector.bottom = $("<div>").css({height: 2}).addClass("etable-selector2")
eBase.etable.selector.right = $("<div>").css({width: 2}).addClass("etable-selector2")
$.each([
eBase.etable.selector.top,
eBase.etable.selector.left,
eBase.etable.selector.bottom,
eBase.etable.selector.right
], function () {
eBase.etable.container.append(this)
})
eBase.etable.selector.corner = $("<div>")
eBase.etable.selector.corner.addClass("etable-corner")
eBase.etable.selector.corner.prop("draggable", true)
eBase.etable.selector.corner.on("dragstart", function (e) {
let position = eBase.etable.selector.top.position()
eBase.etable.settings.selector.top = position.top
eBase.etable.settings.selector.left = position.left
})
eBase.etable.container.append(eBase.etable.selector.corner)
}
/**
* Position of the selector
*
* @param etable
* @param nw
*/
export function setSelectorPosition(etable, nw) {
let cw2 = 5
let ch2 = 5
let top = nw.top
let bottom = nw.bottom
if (nw.top + 1 == nw.bottom) {
top = nw.top - nw.height
} else if (nw.top > nw.bottom) {
top = nw.bottom - nw.height
bottom = nw.top
}
let left = nw.left
let right = nw.right
if (nw.left >= nw.right) {
if (nw.left - 1 == nw.right) {
left = nw.left - nw.width
} else {
left = nw.right - nw.width
right = nw.left
}
}
top += etable.container.scrollTop()
bottom += etable.container.scrollTop()
etable.selector.corner.css({"top": bottom - ch2, "left": right - cw2})
etable.selector.top.css({
"top": top,
"left": left,
"width": right - left - 1
})
etable.selector.bottom.css({
"top": bottom,
"left": left,
"width": right - left - 1
})
etable.selector.left.css({
"top": top,
"left": left,
"height": bottom - top
})
etable.selector.right.css({
"top": top,
"left": right - 1,
"height": bottom - top
})
} | Rhocutan/etable | src/app/org/etable/modules/selector.js | JavaScript | apache-2.0 | 2,339 |
// modules are defined as an array
// [ module function, map of requireuires ]
//
// map of requireuires is short require name -> numeric require
//
// anything defined in a previous bundle is accessed via the
// orig method which is the requireuire for previous bundles
(function outer (modules, cache, entry) {
// Save the require from previous bundle to this closure if any
var previousRequire = typeof require == "function" && require;
function findProxyquireifyName() {
var deps = Object.keys(modules)
.map(function (k) { return modules[k][1]; });
for (var i = 0; i < deps.length; i++) {
var pq = deps[i]['proxyquireify'];
if (pq) return pq;
}
}
var proxyquireifyName = findProxyquireifyName();
function newRequire(name, jumped){
// Find the proxyquireify module, if present
var pqify = (proxyquireifyName != null) && cache[proxyquireifyName];
// Proxyquireify provides a separate cache that is used when inside
// a proxyquire call, and is set to null outside a proxyquire call.
// This allows the regular caching semantics to work correctly both
// inside and outside proxyquire calls while keeping the cached
// modules isolated.
// When switching from one proxyquire call to another, it clears
// the cache to prevent contamination between different sets
// of stubs.
var currentCache = (pqify && pqify.exports._cache) || cache;
if(!currentCache[name]) {
if(!modules[name]) {
// if we cannot find the the module within our internal map or
// cache jump to the current global require ie. the last bundle
// that was added to the page.
var currentRequire = typeof require == "function" && require;
if (!jumped && currentRequire) return currentRequire(name, true);
// If there are other bundles on this page the require from the
// previous one is saved to 'previousRequire'. Repeat this as
// many times as there are bundles until the module is found or
// we exhaust the require chain.
if (previousRequire) return previousRequire(name, true);
var err = new Error('Cannot find module \'' + name + '\'');
err.code = 'MODULE_NOT_FOUND';
throw err;
}
var m = currentCache[name] = {exports:{}};
// The normal browserify require function
var req = function(x){
var id = modules[name][1][x];
return newRequire(id ? id : x);
};
// The require function substituted for proxyquireify
var moduleRequire = function(x){
var pqify = (proxyquireifyName != null) && cache[proxyquireifyName];
// Only try to use the proxyquireify version if it has been `require`d
if (pqify && pqify.exports._proxy) {
return pqify.exports._proxy(req, x);
} else {
return req(x);
}
};
modules[name][0].call(m.exports,moduleRequire,m,m.exports,outer,modules,currentCache,entry);
}
return currentCache[name].exports;
}
for(var i=0;i<entry.length;i++) newRequire(entry[i]);
// Override the current require with this new one
return newRequire;
})
({1:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var ctor = ( typeof Float32Array === 'function' ) ? Float32Array : void 0; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = ctor;
},{}],2:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Typed array constructor which returns a typed array representing an array of single-precision floating-point numbers in the platform byte order.
*
* @module @stdlib/array/float32
*
* @example
* var ctor = require( '@stdlib/array/float32' );
*
* var arr = new ctor( 10 );
* // returns <Float32Array>
*/
// MODULES //
var hasFloat32ArraySupport = require( '@stdlib/assert/has-float32array-support' );
var builtin = require( './float32array.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var ctor;
if ( hasFloat32ArraySupport() ) {
ctor = builtin;
} else {
ctor = polyfill;
}
// EXPORTS //
module.exports = ctor;
},{"./float32array.js":1,"./polyfill.js":3,"@stdlib/assert/has-float32array-support":33}],3:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// TODO: write polyfill
// MAIN //
/**
* Typed array which represents an array of single-precision floating-point numbers in the platform byte order.
*
* @throws {Error} not implemented
*/
function polyfill() {
throw new Error( 'not implemented' );
}
// EXPORTS //
module.exports = polyfill;
},{}],4:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var ctor = ( typeof Float64Array === 'function' ) ? Float64Array : void 0; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = ctor;
},{}],5:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Typed array constructor which returns a typed array representing an array of double-precision floating-point numbers in the platform byte order.
*
* @module @stdlib/array/float64
*
* @example
* var ctor = require( '@stdlib/array/float64' );
*
* var arr = new ctor( 10 );
* // returns <Float64Array>
*/
// MODULES //
var hasFloat64ArraySupport = require( '@stdlib/assert/has-float64array-support' );
var builtin = require( './float64array.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var ctor;
if ( hasFloat64ArraySupport() ) {
ctor = builtin;
} else {
ctor = polyfill;
}
// EXPORTS //
module.exports = ctor;
},{"./float64array.js":4,"./polyfill.js":6,"@stdlib/assert/has-float64array-support":36}],6:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// TODO: write polyfill
// MAIN //
/**
* Typed array which represents an array of double-precision floating-point numbers in the platform byte order.
*
* @throws {Error} not implemented
*/
function polyfill() {
throw new Error( 'not implemented' );
}
// EXPORTS //
module.exports = polyfill;
},{}],7:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Typed array constructor which returns a typed array representing an array of twos-complement 16-bit signed integers in the platform byte order.
*
* @module @stdlib/array/int16
*
* @example
* var ctor = require( '@stdlib/array/int16' );
*
* var arr = new ctor( 10 );
* // returns <Int16Array>
*/
// MODULES //
var hasInt16ArraySupport = require( '@stdlib/assert/has-int16array-support' );
var builtin = require( './int16array.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var ctor;
if ( hasInt16ArraySupport() ) {
ctor = builtin;
} else {
ctor = polyfill;
}
// EXPORTS //
module.exports = ctor;
},{"./int16array.js":8,"./polyfill.js":9,"@stdlib/assert/has-int16array-support":41}],8:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var ctor = ( typeof Int16Array === 'function' ) ? Int16Array : void 0; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = ctor;
},{}],9:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// TODO: write polyfill
// MAIN //
/**
* Typed array which represents an array of twos-complement 16-bit signed integers in the platform byte order.
*
* @throws {Error} not implemented
*/
function polyfill() {
throw new Error( 'not implemented' );
}
// EXPORTS //
module.exports = polyfill;
},{}],10:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Typed array constructor which returns a typed array representing an array of twos-complement 32-bit signed integers in the platform byte order.
*
* @module @stdlib/array/int32
*
* @example
* var ctor = require( '@stdlib/array/int32' );
*
* var arr = new ctor( 10 );
* // returns <Int32Array>
*/
// MODULES //
var hasInt32ArraySupport = require( '@stdlib/assert/has-int32array-support' );
var builtin = require( './int32array.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var ctor;
if ( hasInt32ArraySupport() ) {
ctor = builtin;
} else {
ctor = polyfill;
}
// EXPORTS //
module.exports = ctor;
},{"./int32array.js":11,"./polyfill.js":12,"@stdlib/assert/has-int32array-support":44}],11:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var ctor = ( typeof Int32Array === 'function' ) ? Int32Array : void 0; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = ctor;
},{}],12:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// TODO: write polyfill
// MAIN //
/**
* Typed array which represents an array of twos-complement 32-bit signed integers in the platform byte order.
*
* @throws {Error} not implemented
*/
function polyfill() {
throw new Error( 'not implemented' );
}
// EXPORTS //
module.exports = polyfill;
},{}],13:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Typed array constructor which returns a typed array representing an array of twos-complement 8-bit signed integers in the platform byte order.
*
* @module @stdlib/array/int8
*
* @example
* var ctor = require( '@stdlib/array/int8' );
*
* var arr = new ctor( 10 );
* // returns <Int8Array>
*/
// MODULES //
var hasInt8ArraySupport = require( '@stdlib/assert/has-int8array-support' );
var builtin = require( './int8array.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var ctor;
if ( hasInt8ArraySupport() ) {
ctor = builtin;
} else {
ctor = polyfill;
}
// EXPORTS //
module.exports = ctor;
},{"./int8array.js":14,"./polyfill.js":15,"@stdlib/assert/has-int8array-support":47}],14:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var ctor = ( typeof Int8Array === 'function' ) ? Int8Array : void 0; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = ctor;
},{}],15:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// TODO: write polyfill
// MAIN //
/**
* Typed array which represents an array of twos-complement 8-bit signed integers in the platform byte order.
*
* @throws {Error} not implemented
*/
function polyfill() {
throw new Error( 'not implemented' );
}
// EXPORTS //
module.exports = polyfill;
},{}],16:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var Int8Array = require( '@stdlib/array/int8' );
var Uint8Array = require( '@stdlib/array/uint8' );
var Uint8ClampedArray = require( '@stdlib/array/uint8c' );
var Int16Array = require( '@stdlib/array/int16' );
var Uint16Array = require( '@stdlib/array/uint16' );
var Int32Array = require( '@stdlib/array/int32' );
var Uint32Array = require( '@stdlib/array/uint32' );
var Float32Array = require( '@stdlib/array/float32' );
var Float64Array = require( '@stdlib/array/float64' );
// MAIN //
var CTORS = [
[ Float64Array, 'Float64Array' ],
[ Float32Array, 'Float32Array' ],
[ Int32Array, 'Int32Array' ],
[ Uint32Array, 'Uint32Array' ],
[ Int16Array, 'Int16Array' ],
[ Uint16Array, 'Uint16Array' ],
[ Int8Array, 'Int8Array' ],
[ Uint8Array, 'Uint8Array' ],
[ Uint8ClampedArray, 'Uint8ClampedArray' ]
];
// EXPORTS //
module.exports = CTORS;
},{"@stdlib/array/float32":2,"@stdlib/array/float64":5,"@stdlib/array/int16":7,"@stdlib/array/int32":10,"@stdlib/array/int8":13,"@stdlib/array/uint16":20,"@stdlib/array/uint32":23,"@stdlib/array/uint8":26,"@stdlib/array/uint8c":29}],17:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Return a JSON representation of a typed array.
*
* @module @stdlib/array/to-json
*
* @example
* var Float64Array = require( '@stdlib/array/float64' );
* var toJSON = require( '@stdlib/array/to-json' );
*
* var arr = new Float64Array( [ 5.0, 3.0 ] );
* var json = toJSON( arr );
* // returns { 'type': 'Float64Array', 'data': [ 5.0, 3.0 ] }
*/
// MODULES //
var toJSON = require( './to_json.js' );
// EXPORTS //
module.exports = toJSON;
},{"./to_json.js":18}],18:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isTypedArray = require( '@stdlib/assert/is-typed-array' );
var typeName = require( './type.js' );
// MAIN //
/**
* Returns a JSON representation of a typed array.
*
* ## Notes
*
* - We build a JSON object representing a typed array similar to how Node.js `Buffer` objects are represented. See [Buffer][1].
*
* [1]: https://nodejs.org/api/buffer.html#buffer_buf_tojson
*
* @param {TypedArray} arr - typed array to serialize
* @throws {TypeError} first argument must be a typed array
* @returns {Object} JSON representation
*
* @example
* var Float64Array = require( '@stdlib/array/float64' );
*
* var arr = new Float64Array( [ 5.0, 3.0 ] );
* var json = toJSON( arr );
* // returns { 'type': 'Float64Array', 'data': [ 5.0, 3.0 ] }
*/
function toJSON( arr ) {
var out;
var i;
if ( !isTypedArray( arr ) ) {
throw new TypeError( 'invalid argument. Must provide a typed array. Value: `' + arr + '`.' );
}
out = {};
out.type = typeName( arr );
out.data = [];
for ( i = 0; i < arr.length; i++ ) {
out.data.push( arr[ i ] );
}
return out;
}
// EXPORTS //
module.exports = toJSON;
},{"./type.js":19,"@stdlib/assert/is-typed-array":165}],19:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var instanceOf = require( '@stdlib/assert/instance-of' );
var ctorName = require( '@stdlib/utils/constructor-name' );
var getPrototypeOf = require( '@stdlib/utils/get-prototype-of' );
var CTORS = require( './ctors.js' );
// MAIN //
/**
* Returns the typed array type.
*
* @private
* @param {TypedArray} arr - typed array
* @returns {(string|void)} typed array type
*
* @example
* var Float64Array = require( '@stdlib/array/float64' );
*
* var arr = new Float64Array( 5 );
* var str = typeName( arr );
* // returns 'Float64Array'
*/
function typeName( arr ) {
var v;
var i;
// Check for typed array objects from the same realm (same Node.js `vm` or same `Window` object)...
for ( i = 0; i < CTORS.length; i++ ) {
if ( instanceOf( arr, CTORS[ i ][ 0 ] ) ) {
return CTORS[ i ][ 1 ];
}
}
// Walk the prototype tree until we find an object having a desired native class...
while ( arr ) {
v = ctorName( arr );
for ( i = 0; i < CTORS.length; i++ ) {
if ( v === CTORS[ i ][ 1 ] ) {
return CTORS[ i ][ 1 ];
}
}
arr = getPrototypeOf( arr );
}
}
// EXPORTS //
module.exports = typeName;
},{"./ctors.js":16,"@stdlib/assert/instance-of":71,"@stdlib/utils/constructor-name":388,"@stdlib/utils/get-prototype-of":411}],20:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Typed array constructor which returns a typed array representing an array of 16-bit unsigned integers in the platform byte order.
*
* @module @stdlib/array/uint16
*
* @example
* var ctor = require( '@stdlib/array/uint16' );
*
* var arr = new ctor( 10 );
* // returns <Uint16Array>
*/
// MODULES //
var hasUint16ArraySupport = require( '@stdlib/assert/has-uint16array-support' );
var builtin = require( './uint16array.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var ctor;
if ( hasUint16ArraySupport() ) {
ctor = builtin;
} else {
ctor = polyfill;
}
// EXPORTS //
module.exports = ctor;
},{"./polyfill.js":21,"./uint16array.js":22,"@stdlib/assert/has-uint16array-support":59}],21:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// TODO: write polyfill
// MAIN //
/**
* Typed array which represents an array of 16-bit unsigned integers in the platform byte order.
*
* @throws {Error} not implemented
*/
function polyfill() {
throw new Error( 'not implemented' );
}
// EXPORTS //
module.exports = polyfill;
},{}],22:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var ctor = ( typeof Uint16Array === 'function' ) ? Uint16Array : void 0; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = ctor;
},{}],23:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Typed array constructor which returns a typed array representing an array of 32-bit unsigned integers in the platform byte order.
*
* @module @stdlib/array/uint32
*
* @example
* var ctor = require( '@stdlib/array/uint32' );
*
* var arr = new ctor( 10 );
* // returns <Uint32Array>
*/
// MODULES //
var hasUint32ArraySupport = require( '@stdlib/assert/has-uint32array-support' );
var builtin = require( './uint32array.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var ctor;
if ( hasUint32ArraySupport() ) {
ctor = builtin;
} else {
ctor = polyfill;
}
// EXPORTS //
module.exports = ctor;
},{"./polyfill.js":24,"./uint32array.js":25,"@stdlib/assert/has-uint32array-support":62}],24:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// TODO: write polyfill
// MAIN //
/**
* Typed array which represents an array of 32-bit unsigned integers in the platform byte order.
*
* @throws {Error} not implemented
*/
function polyfill() {
throw new Error( 'not implemented' );
}
// EXPORTS //
module.exports = polyfill;
},{}],25:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var ctor = ( typeof Uint32Array === 'function' ) ? Uint32Array : void 0; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = ctor;
},{}],26:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Typed array constructor which returns a typed array representing an array of 8-bit unsigned integers in the platform byte order.
*
* @module @stdlib/array/uint8
*
* @example
* var ctor = require( '@stdlib/array/uint8' );
*
* var arr = new ctor( 10 );
* // returns <Uint8Array>
*/
// MODULES //
var hasUint8ArraySupport = require( '@stdlib/assert/has-uint8array-support' );
var builtin = require( './uint8array.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var ctor;
if ( hasUint8ArraySupport() ) {
ctor = builtin;
} else {
ctor = polyfill;
}
// EXPORTS //
module.exports = ctor;
},{"./polyfill.js":27,"./uint8array.js":28,"@stdlib/assert/has-uint8array-support":65}],27:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// TODO: write polyfill
// MAIN //
/**
* Typed array which represents an array of 8-bit unsigned integers in the platform byte order.
*
* @throws {Error} not implemented
*/
function polyfill() {
throw new Error( 'not implemented' );
}
// EXPORTS //
module.exports = polyfill;
},{}],28:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var ctor = ( typeof Uint8Array === 'function' ) ? Uint8Array : void 0; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = ctor;
},{}],29:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Typed array constructor which returns a typed array representing an array of 8-bit unsigned integers in the platform byte order clamped to 0-255.
*
* @module @stdlib/array/uint8c
*
* @example
* var ctor = require( '@stdlib/array/uint8c' );
*
* var arr = new ctor( 10 );
* // returns <Uint8ClampedArray>
*/
// MODULES //
var hasUint8ClampedArraySupport = require( '@stdlib/assert/has-uint8clampedarray-support' ); // eslint-disable-line id-length
var builtin = require( './uint8clampedarray.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var ctor;
if ( hasUint8ClampedArraySupport() ) {
ctor = builtin;
} else {
ctor = polyfill;
}
// EXPORTS //
module.exports = ctor;
},{"./polyfill.js":30,"./uint8clampedarray.js":31,"@stdlib/assert/has-uint8clampedarray-support":68}],30:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// TODO: write polyfill
// MAIN //
/**
* Typed array which represents an array of 8-bit unsigned integers in the platform byte order clamped to 0-255.
*
* @throws {Error} not implemented
*/
function polyfill() {
throw new Error( 'not implemented' );
}
// EXPORTS //
module.exports = polyfill;
},{}],31:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var ctor = ( typeof Uint8ClampedArray === 'function' ) ? Uint8ClampedArray : void 0; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = ctor;
},{}],32:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var main = ( typeof Float32Array === 'function' ) ? Float32Array : null; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = main;
},{}],33:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test for native `Float32Array` support.
*
* @module @stdlib/assert/has-float32array-support
*
* @example
* var hasFloat32ArraySupport = require( '@stdlib/assert/has-float32array-support' );
*
* var bool = hasFloat32ArraySupport();
* // returns <boolean>
*/
// MODULES //
var hasFloat32ArraySupport = require( './main.js' );
// EXPORTS //
module.exports = hasFloat32ArraySupport;
},{"./main.js":34}],34:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isFloat32Array = require( '@stdlib/assert/is-float32array' );
var PINF = require( '@stdlib/constants/float64/pinf' );
var GlobalFloat32Array = require( './float32array.js' );
// MAIN //
/**
* Tests for native `Float32Array` support.
*
* @returns {boolean} boolean indicating if an environment has `Float32Array` support
*
* @example
* var bool = hasFloat32ArraySupport();
* // returns <boolean>
*/
function hasFloat32ArraySupport() {
var bool;
var arr;
if ( typeof GlobalFloat32Array !== 'function' ) {
return false;
}
// Test basic support...
try {
arr = new GlobalFloat32Array( [ 1.0, 3.14, -3.14, 5.0e40 ] );
bool = (
isFloat32Array( arr ) &&
arr[ 0 ] === 1.0 &&
arr[ 1 ] === 3.140000104904175 &&
arr[ 2 ] === -3.140000104904175 &&
arr[ 3 ] === PINF
);
} catch ( err ) { // eslint-disable-line no-unused-vars
bool = false;
}
return bool;
}
// EXPORTS //
module.exports = hasFloat32ArraySupport;
},{"./float32array.js":32,"@stdlib/assert/is-float32array":98,"@stdlib/constants/float64/pinf":246}],35:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var main = ( typeof Float64Array === 'function' ) ? Float64Array : null; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = main;
},{}],36:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test for native `Float64Array` support.
*
* @module @stdlib/assert/has-float64array-support
*
* @example
* var hasFloat64ArraySupport = require( '@stdlib/assert/has-float64array-support' );
*
* var bool = hasFloat64ArraySupport();
* // returns <boolean>
*/
// MODULES //
var hasFloat64ArraySupport = require( './main.js' );
// EXPORTS //
module.exports = hasFloat64ArraySupport;
},{"./main.js":37}],37:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isFloat64Array = require( '@stdlib/assert/is-float64array' );
var GlobalFloat64Array = require( './float64array.js' );
// MAIN //
/**
* Tests for native `Float64Array` support.
*
* @returns {boolean} boolean indicating if an environment has `Float64Array` support
*
* @example
* var bool = hasFloat64ArraySupport();
* // returns <boolean>
*/
function hasFloat64ArraySupport() {
var bool;
var arr;
if ( typeof GlobalFloat64Array !== 'function' ) {
return false;
}
// Test basic support...
try {
arr = new GlobalFloat64Array( [ 1.0, 3.14, -3.14, NaN ] );
bool = (
isFloat64Array( arr ) &&
arr[ 0 ] === 1.0 &&
arr[ 1 ] === 3.14 &&
arr[ 2 ] === -3.14 &&
arr[ 3 ] !== arr[ 3 ]
);
} catch ( err ) { // eslint-disable-line no-unused-vars
bool = false;
}
return bool;
}
// EXPORTS //
module.exports = hasFloat64ArraySupport;
},{"./float64array.js":35,"@stdlib/assert/is-float64array":100}],38:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Dummy function.
*
* @private
*/
function foo() {
// No-op...
}
// EXPORTS //
module.exports = foo;
},{}],39:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test for native function `name` support.
*
* @module @stdlib/assert/has-function-name-support
*
* @example
* var hasFunctionNameSupport = require( '@stdlib/assert/has-function-name-support' );
*
* var bool = hasFunctionNameSupport();
* // returns <boolean>
*/
// MODULES //
var hasFunctionNameSupport = require( './main.js' );
// EXPORTS //
module.exports = hasFunctionNameSupport;
},{"./main.js":40}],40:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var foo = require( './foo.js' );
// MAIN //
/**
* Tests for native function `name` support.
*
* @returns {boolean} boolean indicating if an environment has function `name` support
*
* @example
* var bool = hasFunctionNameSupport();
* // returns <boolean>
*/
function hasFunctionNameSupport() {
return ( foo.name === 'foo' );
}
// EXPORTS //
module.exports = hasFunctionNameSupport;
},{"./foo.js":38}],41:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test for native `Int16Array` support.
*
* @module @stdlib/assert/has-int16array-support
*
* @example
* var hasInt16ArraySupport = require( '@stdlib/assert/has-int16array-support' );
*
* var bool = hasInt16ArraySupport();
* // returns <boolean>
*/
// MODULES //
var hasInt16ArraySupport = require( './main.js' );
// EXPORTS //
module.exports = hasInt16ArraySupport;
},{"./main.js":43}],42:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var main = ( typeof Int16Array === 'function' ) ? Int16Array : null; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = main;
},{}],43:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isInt16Array = require( '@stdlib/assert/is-int16array' );
var INT16_MAX = require( '@stdlib/constants/int16/max' );
var INT16_MIN = require( '@stdlib/constants/int16/min' );
var GlobalInt16Array = require( './int16array.js' );
// MAIN //
/**
* Tests for native `Int16Array` support.
*
* @returns {boolean} boolean indicating if an environment has `Int16Array` support
*
* @example
* var bool = hasInt16ArraySupport();
* // returns <boolean>
*/
function hasInt16ArraySupport() {
var bool;
var arr;
if ( typeof GlobalInt16Array !== 'function' ) {
return false;
}
// Test basic support...
try {
arr = new GlobalInt16Array( [ 1, 3.14, -3.14, INT16_MAX+1 ] );
bool = (
isInt16Array( arr ) &&
arr[ 0 ] === 1 &&
arr[ 1 ] === 3 && // truncation
arr[ 2 ] === -3 && // truncation
arr[ 3 ] === INT16_MIN // wrap around
);
} catch ( err ) { // eslint-disable-line no-unused-vars
bool = false;
}
return bool;
}
// EXPORTS //
module.exports = hasInt16ArraySupport;
},{"./int16array.js":42,"@stdlib/assert/is-int16array":104,"@stdlib/constants/int16/max":248,"@stdlib/constants/int16/min":249}],44:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test for native `Int32Array` support.
*
* @module @stdlib/assert/has-int32array-support
*
* @example
* var hasInt32ArraySupport = require( '@stdlib/assert/has-int32array-support' );
*
* var bool = hasInt32ArraySupport();
* // returns <boolean>
*/
// MODULES //
var hasInt32ArraySupport = require( './main.js' );
// EXPORTS //
module.exports = hasInt32ArraySupport;
},{"./main.js":46}],45:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var main = ( typeof Int32Array === 'function' ) ? Int32Array : null; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = main;
},{}],46:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isInt32Array = require( '@stdlib/assert/is-int32array' );
var INT32_MAX = require( '@stdlib/constants/int32/max' );
var INT32_MIN = require( '@stdlib/constants/int32/min' );
var GlobalInt32Array = require( './int32array.js' );
// MAIN //
/**
* Tests for native `Int32Array` support.
*
* @returns {boolean} boolean indicating if an environment has `Int32Array` support
*
* @example
* var bool = hasInt32ArraySupport();
* // returns <boolean>
*/
function hasInt32ArraySupport() {
var bool;
var arr;
if ( typeof GlobalInt32Array !== 'function' ) {
return false;
}
// Test basic support...
try {
arr = new GlobalInt32Array( [ 1, 3.14, -3.14, INT32_MAX+1 ] );
bool = (
isInt32Array( arr ) &&
arr[ 0 ] === 1 &&
arr[ 1 ] === 3 && // truncation
arr[ 2 ] === -3 && // truncation
arr[ 3 ] === INT32_MIN // wrap around
);
} catch ( err ) { // eslint-disable-line no-unused-vars
bool = false;
}
return bool;
}
// EXPORTS //
module.exports = hasInt32ArraySupport;
},{"./int32array.js":45,"@stdlib/assert/is-int32array":106,"@stdlib/constants/int32/max":250,"@stdlib/constants/int32/min":251}],47:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test for native `Int8Array` support.
*
* @module @stdlib/assert/has-int8array-support
*
* @example
* var hasInt8ArraySupport = require( '@stdlib/assert/has-int8array-support' );
*
* var bool = hasInt8ArraySupport();
* // returns <boolean>
*/
// MODULES //
var hasInt8ArraySupport = require( './main.js' );
// EXPORTS //
module.exports = hasInt8ArraySupport;
},{"./main.js":49}],48:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var main = ( typeof Int8Array === 'function' ) ? Int8Array : null; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = main;
},{}],49:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isInt8Array = require( '@stdlib/assert/is-int8array' );
var INT8_MAX = require( '@stdlib/constants/int8/max' );
var INT8_MIN = require( '@stdlib/constants/int8/min' );
var GlobalInt8Array = require( './int8array.js' );
// MAIN //
/**
* Tests for native `Int8Array` support.
*
* @returns {boolean} boolean indicating if an environment has `Int8Array` support
*
* @example
* var bool = hasInt8ArraySupport();
* // returns <boolean>
*/
function hasInt8ArraySupport() {
var bool;
var arr;
if ( typeof GlobalInt8Array !== 'function' ) {
return false;
}
// Test basic support...
try {
arr = new GlobalInt8Array( [ 1, 3.14, -3.14, INT8_MAX+1 ] );
bool = (
isInt8Array( arr ) &&
arr[ 0 ] === 1 &&
arr[ 1 ] === 3 && // truncation
arr[ 2 ] === -3 && // truncation
arr[ 3 ] === INT8_MIN // wrap around
);
} catch ( err ) { // eslint-disable-line no-unused-vars
bool = false;
}
return bool;
}
// EXPORTS //
module.exports = hasInt8ArraySupport;
},{"./int8array.js":48,"@stdlib/assert/is-int8array":108,"@stdlib/constants/int8/max":252,"@stdlib/constants/int8/min":253}],50:[function(require,module,exports){
(function (Buffer){(function (){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var main = ( typeof Buffer === 'function' ) ? Buffer : null; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = main;
}).call(this)}).call(this,require("buffer").Buffer)
},{"buffer":481}],51:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test for native `Buffer` support.
*
* @module @stdlib/assert/has-node-buffer-support
*
* @example
* var hasNodeBufferSupport = require( '@stdlib/assert/has-node-buffer-support' );
*
* var bool = hasNodeBufferSupport();
* // returns <boolean>
*/
// MODULES //
var hasNodeBufferSupport = require( './main.js' );
// EXPORTS //
module.exports = hasNodeBufferSupport;
},{"./main.js":52}],52:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isBuffer = require( '@stdlib/assert/is-buffer' );
var GlobalBuffer = require( './buffer.js' );
// MAIN //
/**
* Tests for native `Buffer` support.
*
* @returns {boolean} boolean indicating if an environment has `Buffer` support
*
* @example
* var bool = hasNodeBufferSupport();
* // returns <boolean>
*/
function hasNodeBufferSupport() {
var bool;
var b;
if ( typeof GlobalBuffer !== 'function' ) {
return false;
}
// Test basic support...
try {
if ( typeof GlobalBuffer.from === 'function' ) {
b = GlobalBuffer.from( [ 1, 2, 3, 4 ] );
} else {
b = new GlobalBuffer( [ 1, 2, 3, 4 ] ); // Note: this is deprecated behavior starting in Node v6 (see https://nodejs.org/api/buffer.html#buffer_new_buffer_array)
}
bool = (
isBuffer( b ) &&
b[ 0 ] === 1 &&
b[ 1 ] === 2 &&
b[ 2 ] === 3 &&
b[ 3 ] === 4
);
} catch ( err ) { // eslint-disable-line no-unused-vars
bool = false;
}
return bool;
}
// EXPORTS //
module.exports = hasNodeBufferSupport;
},{"./buffer.js":50,"@stdlib/assert/is-buffer":88}],53:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test whether an object has a specified property.
*
* @module @stdlib/assert/has-own-property
*
* @example
* var hasOwnProp = require( '@stdlib/assert/has-own-property' );
*
* var beep = {
* 'boop': true
* };
*
* var bool = hasOwnProp( beep, 'boop' );
* // returns true
*
* bool = hasOwnProp( beep, 'bop' );
* // returns false
*/
// MODULES //
var hasOwnProp = require( './main.js' );
// EXPORTS //
module.exports = hasOwnProp;
},{"./main.js":54}],54:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// FUNCTIONS //
var has = Object.prototype.hasOwnProperty;
// MAIN //
/**
* Tests if an object has a specified property.
*
* @param {*} value - value to test
* @param {*} property - property to test
* @returns {boolean} boolean indicating if an object has a specified property
*
* @example
* var beep = {
* 'boop': true
* };
*
* var bool = hasOwnProp( beep, 'boop' );
* // returns true
*
* @example
* var beep = {
* 'boop': true
* };
*
* var bool = hasOwnProp( beep, 'bap' );
* // returns false
*/
function hasOwnProp( value, property ) {
if (
value === void 0 ||
value === null
) {
return false;
}
return has.call( value, property );
}
// EXPORTS //
module.exports = hasOwnProp;
},{}],55:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test for native `Symbol` support.
*
* @module @stdlib/assert/has-symbol-support
*
* @example
* var hasSymbolSupport = require( '@stdlib/assert/has-symbol-support' );
*
* var bool = hasSymbolSupport();
* // returns <boolean>
*/
// MODULES //
var hasSymbolSupport = require( './main.js' );
// EXPORTS //
module.exports = hasSymbolSupport;
},{"./main.js":56}],56:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Tests for native `Symbol` support.
*
* @returns {boolean} boolean indicating if an environment has `Symbol` support
*
* @example
* var bool = hasSymbolSupport();
* // returns <boolean>
*/
function hasSymbolSupport() {
return (
typeof Symbol === 'function' &&
typeof Symbol( 'foo' ) === 'symbol'
);
}
// EXPORTS //
module.exports = hasSymbolSupport;
},{}],57:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test for native `toStringTag` support.
*
* @module @stdlib/assert/has-tostringtag-support
*
* @example
* var hasToStringTagSupport = require( '@stdlib/assert/has-tostringtag-support' );
*
* var bool = hasToStringTagSupport();
* // returns <boolean>
*/
// MODULES //
var hasToStringTagSupport = require( './main.js' );
// EXPORTS //
module.exports = hasToStringTagSupport;
},{"./main.js":58}],58:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var hasSymbols = require( '@stdlib/assert/has-symbol-support' );
// VARIABLES //
var FLG = hasSymbols();
// MAIN //
/**
* Tests for native `toStringTag` support.
*
* @returns {boolean} boolean indicating if an environment has `toStringTag` support
*
* @example
* var bool = hasToStringTagSupport();
* // returns <boolean>
*/
function hasToStringTagSupport() {
return ( FLG && typeof Symbol.toStringTag === 'symbol' );
}
// EXPORTS //
module.exports = hasToStringTagSupport;
},{"@stdlib/assert/has-symbol-support":55}],59:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test for native `Uint16Array` support.
*
* @module @stdlib/assert/has-uint16array-support
*
* @example
* var hasUint16ArraySupport = require( '@stdlib/assert/has-uint16array-support' );
*
* var bool = hasUint16ArraySupport();
* // returns <boolean>
*/
// MODULES //
var hasUint16ArraySupport = require( './main.js' );
// EXPORTS //
module.exports = hasUint16ArraySupport;
},{"./main.js":60}],60:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isUint16Array = require( '@stdlib/assert/is-uint16array' );
var UINT16_MAX = require( '@stdlib/constants/uint16/max' );
var GlobalUint16Array = require( './uint16array.js' );
// MAIN //
/**
* Tests for native `Uint16Array` support.
*
* @returns {boolean} boolean indicating if an environment has `Uint16Array` support
*
* @example
* var bool = hasUint16ArraySupport();
* // returns <boolean>
*/
function hasUint16ArraySupport() {
var bool;
var arr;
if ( typeof GlobalUint16Array !== 'function' ) {
return false;
}
// Test basic support...
try {
arr = [ 1, 3.14, -3.14, UINT16_MAX+1, UINT16_MAX+2 ];
arr = new GlobalUint16Array( arr );
bool = (
isUint16Array( arr ) &&
arr[ 0 ] === 1 &&
arr[ 1 ] === 3 && // truncation
arr[ 2 ] === UINT16_MAX-2 && // truncation and wrap around
arr[ 3 ] === 0 && // wrap around
arr[ 4 ] === 1 // wrap around
);
} catch ( err ) { // eslint-disable-line no-unused-vars
bool = false;
}
return bool;
}
// EXPORTS //
module.exports = hasUint16ArraySupport;
},{"./uint16array.js":61,"@stdlib/assert/is-uint16array":168,"@stdlib/constants/uint16/max":254}],61:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var main = ( typeof Uint16Array === 'function' ) ? Uint16Array : null; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = main;
},{}],62:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test for native `Uint32Array` support.
*
* @module @stdlib/assert/has-uint32array-support
*
* @example
* var hasUint32ArraySupport = require( '@stdlib/assert/has-uint32array-support' );
*
* var bool = hasUint32ArraySupport();
* // returns <boolean>
*/
// MODULES //
var hasUint32ArraySupport = require( './main.js' );
// EXPORTS //
module.exports = hasUint32ArraySupport;
},{"./main.js":63}],63:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isUint32Array = require( '@stdlib/assert/is-uint32array' );
var UINT32_MAX = require( '@stdlib/constants/uint32/max' );
var GlobalUint32Array = require( './uint32array.js' );
// MAIN //
/**
* Tests for native `Uint32Array` support.
*
* @returns {boolean} boolean indicating if an environment has `Uint32Array` support
*
* @example
* var bool = hasUint32ArraySupport();
* // returns <boolean>
*/
function hasUint32ArraySupport() {
var bool;
var arr;
if ( typeof GlobalUint32Array !== 'function' ) {
return false;
}
// Test basic support...
try {
arr = [ 1, 3.14, -3.14, UINT32_MAX+1, UINT32_MAX+2 ];
arr = new GlobalUint32Array( arr );
bool = (
isUint32Array( arr ) &&
arr[ 0 ] === 1 &&
arr[ 1 ] === 3 && // truncation
arr[ 2 ] === UINT32_MAX-2 && // truncation and wrap around
arr[ 3 ] === 0 && // wrap around
arr[ 4 ] === 1 // wrap around
);
} catch ( err ) { // eslint-disable-line no-unused-vars
bool = false;
}
return bool;
}
// EXPORTS //
module.exports = hasUint32ArraySupport;
},{"./uint32array.js":64,"@stdlib/assert/is-uint32array":170,"@stdlib/constants/uint32/max":255}],64:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var main = ( typeof Uint32Array === 'function' ) ? Uint32Array : null; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = main;
},{}],65:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test for native `Uint8Array` support.
*
* @module @stdlib/assert/has-uint8array-support
*
* @example
* var hasUint8ArraySupport = require( '@stdlib/assert/has-uint8array-support' );
*
* var bool = hasUint8ArraySupport();
* // returns <boolean>
*/
// MODULES //
var hasUint8ArraySupport = require( './main.js' );
// EXPORTS //
module.exports = hasUint8ArraySupport;
},{"./main.js":66}],66:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isUint8Array = require( '@stdlib/assert/is-uint8array' );
var UINT8_MAX = require( '@stdlib/constants/uint8/max' );
var GlobalUint8Array = require( './uint8array.js' );
// MAIN //
/**
* Tests for native `Uint8Array` support.
*
* @returns {boolean} boolean indicating if an environment has `Uint8Array` support
*
* @example
* var bool = hasUint8ArraySupport();
* // returns <boolean>
*/
function hasUint8ArraySupport() {
var bool;
var arr;
if ( typeof GlobalUint8Array !== 'function' ) {
return false;
}
// Test basic support...
try {
arr = [ 1, 3.14, -3.14, UINT8_MAX+1, UINT8_MAX+2 ];
arr = new GlobalUint8Array( arr );
bool = (
isUint8Array( arr ) &&
arr[ 0 ] === 1 &&
arr[ 1 ] === 3 && // truncation
arr[ 2 ] === UINT8_MAX-2 && // truncation and wrap around
arr[ 3 ] === 0 && // wrap around
arr[ 4 ] === 1 // wrap around
);
} catch ( err ) { // eslint-disable-line no-unused-vars
bool = false;
}
return bool;
}
// EXPORTS //
module.exports = hasUint8ArraySupport;
},{"./uint8array.js":67,"@stdlib/assert/is-uint8array":172,"@stdlib/constants/uint8/max":256}],67:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var main = ( typeof Uint8Array === 'function' ) ? Uint8Array : null; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = main;
},{}],68:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test for native `Uint8ClampedArray` support.
*
* @module @stdlib/assert/has-uint8clampedarray-support
*
* @example
* var hasUint8ClampedArraySupport = require( '@stdlib/assert/has-uint8clampedarray-support' );
*
* var bool = hasUint8ClampedArraySupport();
* // returns <boolean>
*/
// MODULES //
var hasUint8ClampedArraySupport = require( './main.js' );
// EXPORTS //
module.exports = hasUint8ClampedArraySupport;
},{"./main.js":69}],69:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isUint8ClampedArray = require( '@stdlib/assert/is-uint8clampedarray' );
var GlobalUint8ClampedArray = require( './uint8clampedarray.js' );
// MAIN //
/**
* Tests for native `Uint8ClampedArray` support.
*
* @returns {boolean} boolean indicating if an environment has `Uint8ClampedArray` support
*
* @example
* var bool = hasUint8ClampedArraySupport();
* // returns <boolean>
*/
function hasUint8ClampedArraySupport() { // eslint-disable-line id-length
var bool;
var arr;
if ( typeof GlobalUint8ClampedArray !== 'function' ) {
return false;
}
// Test basic support...
try {
arr = new GlobalUint8ClampedArray( [ -1, 0, 1, 3.14, 4.99, 255, 256 ] );
bool = (
isUint8ClampedArray( arr ) &&
arr[ 0 ] === 0 && // clamped
arr[ 1 ] === 0 &&
arr[ 2 ] === 1 &&
arr[ 3 ] === 3 && // round to nearest
arr[ 4 ] === 5 && // round to nearest
arr[ 5 ] === 255 &&
arr[ 6 ] === 255 // clamped
);
} catch ( err ) { // eslint-disable-line no-unused-vars
bool = false;
}
return bool;
}
// EXPORTS //
module.exports = hasUint8ClampedArraySupport;
},{"./uint8clampedarray.js":70,"@stdlib/assert/is-uint8clampedarray":174}],70:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var main = ( typeof Uint8ClampedArray === 'function' ) ? Uint8ClampedArray : null; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = main;
},{}],71:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test whether a value has in its prototype chain a specified constructor as a prototype property.
*
* @module @stdlib/assert/instance-of
*
* @example
* var instanceOf = require( '@stdlib/assert/instance-of' );
*
* var bool = instanceOf( [], Array );
* // returns true
*
* bool = instanceOf( {}, Object ); // exception
* // returns true
*
* bool = instanceOf( 'beep', String );
* // returns false
*
* bool = instanceOf( null, Object );
* // returns false
*
* bool = instanceOf( 5, Object );
* // returns false
*/
// MODULES //
var instanceOf = require( './main.js' );
// EXPORTS //
module.exports = instanceOf;
},{"./main.js":72}],72:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Tests whether a value has in its prototype chain a specified constructor as a prototype property.
*
* @param {*} value - value to test
* @param {Function} constructor - constructor to test against
* @throws {TypeError} constructor must be callable
* @returns {boolean} boolean indicating whether a value is an instance of a provided constructor
*
* @example
* var bool = instanceOf( [], Array );
* // returns true
*
* @example
* var bool = instanceOf( {}, Object ); // exception
* // returns true
*
* @example
* var bool = instanceOf( 'beep', String );
* // returns false
*
* @example
* var bool = instanceOf( null, Object );
* // returns false
*
* @example
* var bool = instanceOf( 5, Object );
* // returns false
*/
function instanceOf( value, constructor ) {
// TODO: replace with `isCallable` check
if ( typeof constructor !== 'function' ) {
throw new TypeError( 'invalid argument. `constructor` argument must be callable. Value: `'+constructor+'`.' );
}
return ( value instanceof constructor );
}
// EXPORTS //
module.exports = instanceOf;
},{}],73:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isArguments = require( './main.js' );
// VARIABLES //
var bool;
// FUNCTIONS //
/**
* Detects whether an environment returns the expected internal class of the `arguments` object.
*
* @private
* @returns {boolean} boolean indicating whether an environment behaves as expected
*
* @example
* var bool = detect();
* // returns <boolean>
*/
function detect() {
return isArguments( arguments );
}
// MAIN //
bool = detect();
// EXPORTS //
module.exports = bool;
},{"./main.js":75}],74:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is an `arguments` object.
*
* @module @stdlib/assert/is-arguments
*
* @example
* var isArguments = require( '@stdlib/assert/is-arguments' );
*
* function foo() {
* return arguments;
* }
*
* var bool = isArguments( foo() );
* // returns true
*
* bool = isArguments( [] );
* // returns false
*/
// MODULES //
var hasArgumentsClass = require( './detect.js' );
var main = require( './main.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var isArguments;
if ( hasArgumentsClass ) {
isArguments = main;
} else {
isArguments = polyfill;
}
// EXPORTS //
module.exports = isArguments;
},{"./detect.js":73,"./main.js":75,"./polyfill.js":76}],75:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var nativeClass = require( '@stdlib/utils/native-class' );
// MAIN //
/**
* Tests whether a value is an `arguments` object.
*
* @private
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether a value is an `arguments` object
*
* @example
* function foo() {
* return arguments;
* }
*
* var bool = isArguments( foo() );
* // returns true
*
* @example
* var bool = isArguments( [] );
* // returns false
*/
function isArguments( value ) {
return ( nativeClass( value ) === '[object Arguments]' );
}
// EXPORTS //
module.exports = isArguments;
},{"@stdlib/utils/native-class":445}],76:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var isEnumerableProperty = require( '@stdlib/assert/is-enumerable-property' );
var isArray = require( '@stdlib/assert/is-array' );
var isInteger = require( '@stdlib/math/base/assert/is-integer' );
var MAX_LENGTH = require( '@stdlib/constants/uint32/max' );
// MAIN //
/**
* Tests whether a value is an `arguments` object.
*
* @private
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether a value is an `arguments` object
*
* @example
* function foo() {
* return arguments;
* }
*
* var bool = isArguments( foo() );
* // returns true
*
* @example
* var bool = isArguments( [] );
* // returns false
*/
function isArguments( value ) {
return (
value !== null &&
typeof value === 'object' &&
!isArray( value ) &&
typeof value.length === 'number' &&
isInteger( value.length ) &&
value.length >= 0 &&
value.length <= MAX_LENGTH &&
hasOwnProp( value, 'callee' ) &&
!isEnumerableProperty( value, 'callee' )
);
}
// EXPORTS //
module.exports = isArguments;
},{"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-array":79,"@stdlib/assert/is-enumerable-property":93,"@stdlib/constants/uint32/max":255,"@stdlib/math/base/assert/is-integer":263}],77:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is array-like.
*
* @module @stdlib/assert/is-array-like
*
* @example
* var isArrayLike = require( '@stdlib/assert/is-array-like' );
*
* var bool = isArrayLike( [] );
* // returns true
*
* bool = isArrayLike( { 'length': 10 } );
* // returns true
*
* bool = isArrayLike( 'beep' );
* // returns true
*/
// MODULES //
var isArrayLike = require( './main.js' );
// EXPORTS //
module.exports = isArrayLike;
},{"./main.js":78}],78:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isInteger = require( '@stdlib/math/base/assert/is-integer' );
var MAX_LENGTH = require( '@stdlib/constants/array/max-array-length' );
// MAIN //
/**
* Tests if a value is array-like.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is array-like
*
* @example
* var bool = isArrayLike( [] );
* // returns true
*
* @example
* var bool = isArrayLike( {'length':10} );
* // returns true
*/
function isArrayLike( value ) {
return (
value !== void 0 &&
value !== null &&
typeof value !== 'function' &&
typeof value.length === 'number' &&
isInteger( value.length ) &&
value.length >= 0 &&
value.length <= MAX_LENGTH
);
}
// EXPORTS //
module.exports = isArrayLike;
},{"@stdlib/constants/array/max-array-length":235,"@stdlib/math/base/assert/is-integer":263}],79:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is an array.
*
* @module @stdlib/assert/is-array
*
* @example
* var isArray = require( '@stdlib/assert/is-array' );
*
* var bool = isArray( [] );
* // returns true
*
* bool = isArray( {} );
* // returns false
*/
// MODULES //
var isArray = require( './main.js' );
// EXPORTS //
module.exports = isArray;
},{"./main.js":80}],80:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var nativeClass = require( '@stdlib/utils/native-class' );
// VARIABLES //
var f;
// FUNCTIONS //
/**
* Tests if a value is an array.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is an array
*
* @example
* var bool = isArray( [] );
* // returns true
*
* @example
* var bool = isArray( {} );
* // returns false
*/
function isArray( value ) {
return ( nativeClass( value ) === '[object Array]' );
}
// MAIN //
if ( Array.isArray ) {
f = Array.isArray;
} else {
f = isArray;
}
// EXPORTS //
module.exports = f;
},{"@stdlib/utils/native-class":445}],81:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is a boolean.
*
* @module @stdlib/assert/is-boolean
*
* @example
* var isBoolean = require( '@stdlib/assert/is-boolean' );
*
* var bool = isBoolean( false );
* // returns true
*
* bool = isBoolean( new Boolean( false ) );
* // returns true
*
* @example
* // Use interface to check for boolean primitives...
* var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive;
*
* var bool = isBoolean( false );
* // returns true
*
* bool = isBoolean( new Boolean( true ) );
* // returns false
*
* @example
* // Use interface to check for boolean objects...
* var isBoolean = require( '@stdlib/assert/is-boolean' ).isObject;
*
* var bool = isBoolean( true );
* // returns false
*
* bool = isBoolean( new Boolean( false ) );
* // returns true
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var isBoolean = require( './main.js' );
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );
// MAIN //
setReadOnly( isBoolean, 'isPrimitive', isPrimitive );
setReadOnly( isBoolean, 'isObject', isObject );
// EXPORTS //
module.exports = isBoolean;
},{"./main.js":82,"./object.js":83,"./primitive.js":84,"@stdlib/utils/define-nonenumerable-read-only-property":396}],82:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );
// MAIN //
/**
* Tests if a value is a boolean.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is a boolean
*
* @example
* var bool = isBoolean( false );
* // returns true
*
* @example
* var bool = isBoolean( true );
* // returns true
*
* @example
* var bool = isBoolean( new Boolean( false ) );
* // returns true
*
* @example
* var bool = isBoolean( new Boolean( true ) );
* // returns true
*/
function isBoolean( value ) {
return ( isPrimitive( value ) || isObject( value ) );
}
// EXPORTS //
module.exports = isBoolean;
},{"./object.js":83,"./primitive.js":84}],83:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var hasToStringTag = require( '@stdlib/assert/has-tostringtag-support' );
var nativeClass = require( '@stdlib/utils/native-class' );
var test = require( './try2serialize.js' );
// VARIABLES //
var FLG = hasToStringTag();
// MAIN //
/**
* Tests if a value is a boolean object.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a boolean object
*
* @example
* var bool = isBoolean( true );
* // returns false
*
* @example
* var bool = isBoolean( new Boolean( false ) );
* // returns true
*/
function isBoolean( value ) {
if ( typeof value === 'object' ) {
if ( value instanceof Boolean ) {
return true;
}
if ( FLG ) {
return test( value );
}
return ( nativeClass( value ) === '[object Boolean]' );
}
return false;
}
// EXPORTS //
module.exports = isBoolean;
},{"./try2serialize.js":86,"@stdlib/assert/has-tostringtag-support":57,"@stdlib/utils/native-class":445}],84:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Tests if a value is a boolean primitive.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a boolean primitive
*
* @example
* var bool = isBoolean( true );
* // returns true
*
* @example
* var bool = isBoolean( false );
* // returns true
*
* @example
* var bool = isBoolean( new Boolean( true ) );
* // returns false
*/
function isBoolean( value ) {
return ( typeof value === 'boolean' );
}
// EXPORTS //
module.exports = isBoolean;
},{}],85:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// eslint-disable-next-line stdlib/no-redeclare
var toString = Boolean.prototype.toString; // non-generic
// EXPORTS //
module.exports = toString;
},{}],86:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var toString = require( './tostring.js' ); // eslint-disable-line stdlib/no-redeclare
// MAIN //
/**
* Attempts to serialize a value to a string.
*
* @private
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value can be serialized
*/
function test( value ) {
try {
toString.call( value );
return true;
} catch ( err ) { // eslint-disable-line no-unused-vars
return false;
}
}
// EXPORTS //
module.exports = test;
},{"./tostring.js":85}],87:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// EXPORTS //
module.exports = true;
},{}],88:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is a Buffer instance.
*
* @module @stdlib/assert/is-buffer
*
* @example
* var isBuffer = require( '@stdlib/assert/is-buffer' );
*
* var v = isBuffer( new Buffer( 'beep' ) );
* // returns true
*
* v = isBuffer( {} );
* // returns false
*/
// MODULES //
var isBuffer = require( './main.js' );
// EXPORTS //
module.exports = isBuffer;
},{"./main.js":89}],89:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isObjectLike = require( '@stdlib/assert/is-object-like' );
// MAIN //
/**
* Tests if a value is a Buffer instance.
*
* @param {*} value - value to validate
* @returns {boolean} boolean indicating if a value is a Buffer instance
*
* @example
* var v = isBuffer( new Buffer( 'beep' ) );
* // returns true
*
* @example
* var v = isBuffer( new Buffer( [1,2,3,4] ) );
* // returns true
*
* @example
* var v = isBuffer( {} );
* // returns false
*
* @example
* var v = isBuffer( [] );
* // returns false
*/
function isBuffer( value ) {
return (
isObjectLike( value ) &&
(
// eslint-disable-next-line no-underscore-dangle
value._isBuffer || // for envs missing Object.prototype.constructor (e.g., Safari 5-7)
(
value.constructor &&
// WARNING: `typeof` is not a foolproof check, as certain envs consider RegExp and NodeList instances to be functions
typeof value.constructor.isBuffer === 'function' &&
value.constructor.isBuffer( value )
)
)
);
}
// EXPORTS //
module.exports = isBuffer;
},{"@stdlib/assert/is-object-like":143}],90:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is a collection.
*
* @module @stdlib/assert/is-collection
*
* @example
* var isCollection = require( '@stdlib/assert/is-collection' );
*
* var bool = isCollection( [] );
* // returns true
*
* bool = isCollection( {} );
* // returns false
*/
// MODULES //
var isCollection = require( './main.js' );
// EXPORTS //
module.exports = isCollection;
},{"./main.js":91}],91:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isInteger = require( '@stdlib/math/base/assert/is-integer' );
var MAX_LENGTH = require( '@stdlib/constants/array/max-typed-array-length' );
// MAIN //
/**
* Tests if a value is a collection.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether a value is a collection
*
* @example
* var bool = isCollection( [] );
* // returns true
*
* @example
* var bool = isCollection( {} );
* // returns false
*/
function isCollection( value ) {
return (
typeof value === 'object' &&
value !== null &&
typeof value.length === 'number' &&
isInteger( value.length ) &&
value.length >= 0 &&
value.length <= MAX_LENGTH
);
}
// EXPORTS //
module.exports = isCollection;
},{"@stdlib/constants/array/max-typed-array-length":236,"@stdlib/math/base/assert/is-integer":263}],92:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isEnum = require( './native.js' );
// VARIABLES //
var bool;
// FUNCTIONS //
/**
* Detects whether an environment has a bug where String indices are not detected as "enumerable" properties. Observed in Node v0.10.
*
* @private
* @returns {boolean} boolean indicating whether an environment has the bug
*/
function detect() {
return !isEnum.call( 'beep', '0' );
}
// MAIN //
bool = detect();
// EXPORTS //
module.exports = bool;
},{"./native.js":95}],93:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test whether an object's own property is enumerable.
*
* @module @stdlib/assert/is-enumerable-property
*
* @example
* var isEnumerableProperty = require( '@stdlib/assert/is-enumerable-property' );
*
* var beep = {
* 'boop': true
* };
*
* var bool = isEnumerableProperty( beep, 'boop' );
* // returns true
*
* bool = isEnumerableProperty( beep, 'hasOwnProperty' );
* // returns false
*/
// MODULES //
var isEnumerableProperty = require( './main.js' );
// EXPORTS //
module.exports = isEnumerableProperty;
},{"./main.js":94}],94:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isString = require( '@stdlib/assert/is-string' );
var isnan = require( '@stdlib/assert/is-nan' ).isPrimitive;
var isInteger = require( '@stdlib/assert/is-integer' ).isPrimitive;
var isEnum = require( './native.js' );
var hasStringEnumBug = require( './has_string_enumerability_bug.js' );
// MAIN //
/**
* Tests if an object's own property is enumerable.
*
* @param {*} value - value to test
* @param {*} property - property to test
* @returns {boolean} boolean indicating if an object property is enumerable
*
* @example
* var beep = {
* 'boop': true
* };
*
* var bool = isEnumerableProperty( beep, 'boop' );
* // returns true
*
* @example
* var beep = {
* 'boop': true
* };
*
* var bool = isEnumerableProperty( beep, 'hasOwnProperty' );
* // returns false
*/
function isEnumerableProperty( value, property ) {
var bool;
if (
value === void 0 ||
value === null
) {
return false;
}
bool = isEnum.call( value, property );
if ( !bool && hasStringEnumBug && isString( value ) ) {
// Note: we only check for indices, as properties attached to a `String` object are properly detected as enumerable above.
property = +property;
return (
!isnan( property ) &&
isInteger( property ) &&
property >= 0 &&
property < value.length
);
}
return bool;
}
// EXPORTS //
module.exports = isEnumerableProperty;
},{"./has_string_enumerability_bug.js":92,"./native.js":95,"@stdlib/assert/is-integer":110,"@stdlib/assert/is-nan":118,"@stdlib/assert/is-string":158}],95:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Tests if an object's own property is enumerable.
*
* @private
* @name isEnumerableProperty
* @type {Function}
* @param {*} value - value to test
* @param {*} property - property to test
* @returns {boolean} boolean indicating if an object property is enumerable
*
* @example
* var beep = {
* 'boop': true
* };
*
* var bool = isEnumerableProperty( beep, 'boop' );
* // returns true
*
* @example
* var beep = {
* 'boop': true
* };
*
* var bool = isEnumerableProperty( beep, 'hasOwnProperty' );
* // returns false
*/
var isEnumerableProperty = Object.prototype.propertyIsEnumerable;
// EXPORTS //
module.exports = isEnumerableProperty;
},{}],96:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is an `Error` object.
*
* @module @stdlib/assert/is-error
*
* @example
* var isError = require( '@stdlib/assert/is-error' );
*
* var bool = isError( new Error( 'beep' ) );
* // returns true
*
* bool = isError( {} );
* // returns false
*/
// MODULES //
var isError = require( './main.js' );
// EXPORTS //
module.exports = isError;
},{"./main.js":97}],97:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var getPrototypeOf = require( '@stdlib/utils/get-prototype-of' );
var nativeClass = require( '@stdlib/utils/native-class' );
// MAIN //
/**
* Tests if a value is an `Error` object.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether a value is an `Error` object
*
* @example
* var bool = isError( new Error( 'beep' ) );
* // returns true
*
* @example
* var bool = isError( {} );
* // returns false
*/
function isError( value ) {
if ( typeof value !== 'object' || value === null ) {
return false;
}
// Check for `Error` objects from the same realm (same Node.js `vm` or same `Window` object)...
if ( value instanceof Error ) {
return true;
}
// Walk the prototype tree until we find an object having the desired native class...
while ( value ) {
if ( nativeClass( value ) === '[object Error]' ) {
return true;
}
value = getPrototypeOf( value );
}
return false;
}
// EXPORTS //
module.exports = isError;
},{"@stdlib/utils/get-prototype-of":411,"@stdlib/utils/native-class":445}],98:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is a Float32Array.
*
* @module @stdlib/assert/is-float32array
*
* @example
* var isFloat32Array = require( '@stdlib/assert/is-float32array' );
*
* var bool = isFloat32Array( new Float32Array( 10 ) );
* // returns true
*
* bool = isFloat32Array( [] );
* // returns false
*/
// MODULES //
var isFloat32Array = require( './main.js' );
// EXPORTS //
module.exports = isFloat32Array;
},{"./main.js":99}],99:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var nativeClass = require( '@stdlib/utils/native-class' );
// VARIABLES //
var hasFloat32Array = ( typeof Float32Array === 'function' );// eslint-disable-line stdlib/require-globals
// MAIN //
/**
* Tests if a value is a Float32Array.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is a Float32Array
*
* @example
* var bool = isFloat32Array( new Float32Array( 10 ) );
* // returns true
*
* @example
* var bool = isFloat32Array( [] );
* // returns false
*/
function isFloat32Array( value ) {
return (
( hasFloat32Array && value instanceof Float32Array ) || // eslint-disable-line stdlib/require-globals
nativeClass( value ) === '[object Float32Array]'
);
}
// EXPORTS //
module.exports = isFloat32Array;
},{"@stdlib/utils/native-class":445}],100:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is a Float64Array.
*
* @module @stdlib/assert/is-float64array
*
* @example
* var isFloat64Array = require( '@stdlib/assert/is-float64array' );
*
* var bool = isFloat64Array( new Float64Array( 10 ) );
* // returns true
*
* bool = isFloat64Array( [] );
* // returns false
*/
// MODULES //
var isFloat64Array = require( './main.js' );
// EXPORTS //
module.exports = isFloat64Array;
},{"./main.js":101}],101:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var nativeClass = require( '@stdlib/utils/native-class' );
// VARIABLES //
var hasFloat64Array = ( typeof Float64Array === 'function' ); // eslint-disable-line stdlib/require-globals
// MAIN //
/**
* Tests if a value is a Float64Array.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is a Float64Array
*
* @example
* var bool = isFloat64Array( new Float64Array( 10 ) );
* // returns true
*
* @example
* var bool = isFloat64Array( [] );
* // returns false
*/
function isFloat64Array( value ) {
return (
( hasFloat64Array && value instanceof Float64Array ) || // eslint-disable-line stdlib/require-globals
nativeClass( value ) === '[object Float64Array]'
);
}
// EXPORTS //
module.exports = isFloat64Array;
},{"@stdlib/utils/native-class":445}],102:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is a function.
*
* @module @stdlib/assert/is-function
*
* @example
* var isFunction = require( '@stdlib/assert/is-function' );
*
* function beep() {
* return 'beep';
* }
*
* var bool = isFunction( beep );
* // returns true
*/
// MODULES //
var isFunction = require( './main.js' );
// EXPORTS //
module.exports = isFunction;
},{"./main.js":103}],103:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var typeOf = require( '@stdlib/utils/type-of' );
// MAIN //
/**
* Tests if a value is a function.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is a function
*
* @example
* function beep() {
* return 'beep';
* }
*
* var bool = isFunction( beep );
* // returns true
*/
function isFunction( value ) {
// Note: cannot use `typeof` directly, as various browser engines incorrectly return `'function'` when operating on non-function objects, such as regular expressions and NodeLists.
return ( typeOf( value ) === 'function' );
}
// EXPORTS //
module.exports = isFunction;
},{"@stdlib/utils/type-of":474}],104:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is an Int16Array.
*
* @module @stdlib/assert/is-int16array
*
* @example
* var isInt16Array = require( '@stdlib/assert/is-int16array' );
*
* var bool = isInt16Array( new Int16Array( 10 ) );
* // returns true
*
* bool = isInt16Array( [] );
* // returns false
*/
// MODULES //
var isInt16Array = require( './main.js' );
// EXPORTS //
module.exports = isInt16Array;
},{"./main.js":105}],105:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var nativeClass = require( '@stdlib/utils/native-class' );
// VARIABLES //
var hasInt16Array = ( typeof Int16Array === 'function' ); // eslint-disable-line stdlib/require-globals
// MAIN //
/**
* Tests if a value is an Int16Array.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is an Int16Array
*
* @example
* var bool = isInt16Array( new Int16Array( 10 ) );
* // returns true
*
* @example
* var bool = isInt16Array( [] );
* // returns false
*/
function isInt16Array( value ) {
return (
( hasInt16Array && value instanceof Int16Array ) || // eslint-disable-line stdlib/require-globals
nativeClass( value ) === '[object Int16Array]'
);
}
// EXPORTS //
module.exports = isInt16Array;
},{"@stdlib/utils/native-class":445}],106:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is an Int32Array.
*
* @module @stdlib/assert/is-int32array
*
* @example
* var isInt32Array = require( '@stdlib/assert/is-int32array' );
*
* var bool = isInt32Array( new Int32Array( 10 ) );
* // returns true
*
* bool = isInt32Array( [] );
* // returns false
*/
// MODULES //
var isInt32Array = require( './main.js' );
// EXPORTS //
module.exports = isInt32Array;
},{"./main.js":107}],107:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var nativeClass = require( '@stdlib/utils/native-class' );
// VARIABLES //
var hasInt32Array = ( typeof Int32Array === 'function' ); // eslint-disable-line stdlib/require-globals
// MAIN //
/**
* Tests if a value is an Int32Array.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is an Int32Array
*
* @example
* var bool = isInt32Array( new Int32Array( 10 ) );
* // returns true
*
* @example
* var bool = isInt32Array( [] );
* // returns false
*/
function isInt32Array( value ) {
return (
( hasInt32Array && value instanceof Int32Array ) || // eslint-disable-line stdlib/require-globals
nativeClass( value ) === '[object Int32Array]'
);
}
// EXPORTS //
module.exports = isInt32Array;
},{"@stdlib/utils/native-class":445}],108:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is an Int8Array.
*
* @module @stdlib/assert/is-int8array
*
* @example
* var isInt8Array = require( '@stdlib/assert/is-int8array' );
*
* var bool = isInt8Array( new Int8Array( 10 ) );
* // returns true
*
* bool = isInt8Array( [] );
* // returns false
*/
// MODULES //
var isInt8Array = require( './main.js' );
// EXPORTS //
module.exports = isInt8Array;
},{"./main.js":109}],109:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var nativeClass = require( '@stdlib/utils/native-class' );
// VARIABLES //
var hasInt8Array = ( typeof Int8Array === 'function' ); // eslint-disable-line stdlib/require-globals
// MAIN //
/**
* Tests if a value is an Int8Array.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is an Int8Array
*
* @example
* var bool = isInt8Array( new Int8Array( 10 ) );
* // returns true
*
* @example
* var bool = isInt8Array( [] );
* // returns false
*/
function isInt8Array( value ) {
return (
( hasInt8Array && value instanceof Int8Array ) || // eslint-disable-line stdlib/require-globals
nativeClass( value ) === '[object Int8Array]'
);
}
// EXPORTS //
module.exports = isInt8Array;
},{"@stdlib/utils/native-class":445}],110:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is an integer.
*
* @module @stdlib/assert/is-integer
*
* @example
* var isInteger = require( '@stdlib/assert/is-integer' );
*
* var bool = isInteger( 5.0 );
* // returns true
*
* bool = isInteger( new Number( 5.0 ) );
* // returns true
*
* bool = isInteger( -3.14 );
* // returns false
*
* bool = isInteger( null );
* // returns false
*
* @example
* // Use interface to check for integer primitives...
* var isInteger = require( '@stdlib/assert/is-integer' ).isPrimitive;
*
* var bool = isInteger( -3.0 );
* // returns true
*
* bool = isInteger( new Number( -3.0 ) );
* // returns false
*
* @example
* // Use interface to check for integer objects...
* var isInteger = require( '@stdlib/assert/is-integer' ).isObject;
*
* var bool = isInteger( 3.0 );
* // returns false
*
* bool = isInteger( new Number( 3.0 ) );
* // returns true
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var isInteger = require( './main.js' );
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );
// MAIN //
setReadOnly( isInteger, 'isPrimitive', isPrimitive );
setReadOnly( isInteger, 'isObject', isObject );
// EXPORTS //
module.exports = isInteger;
},{"./main.js":112,"./object.js":113,"./primitive.js":114,"@stdlib/utils/define-nonenumerable-read-only-property":396}],111:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var PINF = require( '@stdlib/constants/float64/pinf' );
var NINF = require( '@stdlib/constants/float64/ninf' );
var isInt = require( '@stdlib/math/base/assert/is-integer' );
// MAIN //
/**
* Tests if a number primitive is an integer value.
*
* @private
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a number primitive is an integer value
*/
function isInteger( value ) {
return (
value < PINF &&
value > NINF &&
isInt( value )
);
}
// EXPORTS //
module.exports = isInteger;
},{"@stdlib/constants/float64/ninf":245,"@stdlib/constants/float64/pinf":246,"@stdlib/math/base/assert/is-integer":263}],112:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );
// MAIN //
/**
* Tests if a value is an integer.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is an integer
*
* @example
* var bool = isInteger( 5.0 );
* // returns true
*
* @example
* var bool = isInteger( new Number( 5.0 ) );
* // returns true
*
* @example
* var bool = isInteger( -3.14 );
* // returns false
*
* @example
* var bool = isInteger( null );
* // returns false
*/
function isInteger( value ) {
return ( isPrimitive( value ) || isObject( value ) );
}
// EXPORTS //
module.exports = isInteger;
},{"./object.js":113,"./primitive.js":114}],113:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isNumber = require( '@stdlib/assert/is-number' ).isObject;
var isInt = require( './integer.js' );
// MAIN //
/**
* Tests if a value is a number object having an integer value.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a number object having an integer value
*
* @example
* var bool = isInteger( 3.0 );
* // returns false
*
* @example
* var bool = isInteger( new Number( 3.0 ) );
* // returns true
*/
function isInteger( value ) {
return (
isNumber( value ) &&
isInt( value.valueOf() )
);
}
// EXPORTS //
module.exports = isInteger;
},{"./integer.js":111,"@stdlib/assert/is-number":137}],114:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isNumber = require( '@stdlib/assert/is-number' ).isPrimitive;
var isInt = require( './integer.js' );
// MAIN //
/**
* Tests if a value is a number primitive having an integer value.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a number primitive having an integer value
*
* @example
* var bool = isInteger( -3.0 );
* // returns true
*
* @example
* var bool = isInteger( new Number( -3.0 ) );
* // returns false
*/
function isInteger( value ) {
return (
isNumber( value ) &&
isInt( value )
);
}
// EXPORTS //
module.exports = isInteger;
},{"./integer.js":111,"@stdlib/assert/is-number":137}],115:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var Uint8Array = require( '@stdlib/array/uint8' );
var Uint16Array = require( '@stdlib/array/uint16' );
// MAIN //
var ctors = {
'uint16': Uint16Array,
'uint8': Uint8Array
};
// EXPORTS //
module.exports = ctors;
},{"@stdlib/array/uint16":20,"@stdlib/array/uint8":26}],116:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Return a boolean indicating if an environment is little endian.
*
* @module @stdlib/assert/is-little-endian
*
* @example
* var IS_LITTLE_ENDIAN = require( '@stdlib/assert/is-little-endian' );
*
* var bool = IS_LITTLE_ENDIAN;
* // returns <boolean>
*/
// MODULES //
var IS_LITTLE_ENDIAN = require( './main.js' );
// EXPORTS //
module.exports = IS_LITTLE_ENDIAN;
},{"./main.js":117}],117:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var ctors = require( './ctors.js' );
// VARIABLES //
var bool;
// FUNCTIONS //
/**
* Returns a boolean indicating if an environment is little endian.
*
* @private
* @returns {boolean} boolean indicating if an environment is little endian
*
* @example
* var bool = isLittleEndian();
* // returns <boolean>
*/
function isLittleEndian() {
var uint16view;
var uint8view;
uint16view = new ctors[ 'uint16' ]( 1 );
/*
* Set the uint16 view to a value having distinguishable lower and higher order words.
*
* 4660 => 0x1234 => 0x12 0x34 => '00010010 00110100' => (0x12,0x34) == (18,52)
*/
uint16view[ 0 ] = 0x1234;
// Create a uint8 view on top of the uint16 buffer:
uint8view = new ctors[ 'uint8' ]( uint16view.buffer );
// If little endian, the least significant byte will be first...
return ( uint8view[ 0 ] === 0x34 );
}
// MAIN //
bool = isLittleEndian();
// EXPORTS //
module.exports = bool;
},{"./ctors.js":115}],118:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is `NaN`.
*
* @module @stdlib/assert/is-nan
*
* @example
* var isnan = require( '@stdlib/assert/is-nan' );
*
* var bool = isnan( NaN );
* // returns true
*
* bool = isnan( new Number( NaN ) );
* // returns true
*
* bool = isnan( 3.14 );
* // returns false
*
* bool = isnan( null );
* // returns false
*
* @example
* var isnan = require( '@stdlib/assert/is-nan' ).isPrimitive;
*
* var bool = isnan( NaN );
* // returns true
*
* bool = isnan( 3.14 );
* // returns false
*
* bool = isnan( new Number( NaN ) );
* // returns false
*
* @example
* var isnan = require( '@stdlib/assert/is-nan' ).isObject;
*
* var bool = isnan( NaN );
* // returns false
*
* bool = isnan( new Number( NaN ) );
* // returns true
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var isnan = require( './main.js' );
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );
// MAIN //
setReadOnly( isnan, 'isPrimitive', isPrimitive );
setReadOnly( isnan, 'isObject', isObject );
// EXPORTS //
module.exports = isnan;
},{"./main.js":119,"./object.js":120,"./primitive.js":121,"@stdlib/utils/define-nonenumerable-read-only-property":396}],119:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );
// MAIN //
/**
* Tests if a value is `NaN`.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is `NaN`
*
* @example
* var bool = isnan( NaN );
* // returns true
*
* @example
* var bool = isnan( new Number( NaN ) );
* // returns true
*
* @example
* var bool = isnan( 3.14 );
* // returns false
*
* @example
* var bool = isnan( null );
* // returns false
*/
function isnan( value ) {
return ( isPrimitive( value ) || isObject( value ) );
}
// EXPORTS //
module.exports = isnan;
},{"./object.js":120,"./primitive.js":121}],120:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isNumber = require( '@stdlib/assert/is-number' ).isObject;
var isNan = require( '@stdlib/math/base/assert/is-nan' );
// MAIN //
/**
* Tests if a value is a number object having a value of `NaN`.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a number object having a value of `NaN`
*
* @example
* var bool = isnan( NaN );
* // returns false
*
* @example
* var bool = isnan( new Number( NaN ) );
* // returns true
*/
function isnan( value ) {
return (
isNumber( value ) &&
isNan( value.valueOf() )
);
}
// EXPORTS //
module.exports = isnan;
},{"@stdlib/assert/is-number":137,"@stdlib/math/base/assert/is-nan":265}],121:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isNumber = require( '@stdlib/assert/is-number' ).isPrimitive;
var isNan = require( '@stdlib/math/base/assert/is-nan' );
// MAIN //
/**
* Tests if a value is a `NaN` number primitive.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a `NaN` number primitive
*
* @example
* var bool = isnan( NaN );
* // returns true
*
* @example
* var bool = isnan( 3.14 );
* // returns false
*
* @example
* var bool = isnan( new Number( NaN ) );
* // returns false
*/
function isnan( value ) {
return (
isNumber( value ) &&
isNan( value )
);
}
// EXPORTS //
module.exports = isnan;
},{"@stdlib/assert/is-number":137,"@stdlib/math/base/assert/is-nan":265}],122:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is Node stream-like.
*
* @module @stdlib/assert/is-node-stream-like
*
* @example
* var transformStream = require( '@stdlib/streams/node/transform' );
* var isNodeStreamLike = require( '@stdlib/assert/is-node-stream-like' );
*
* var stream = transformStream();
*
* var bool = isNodeStreamLike( stream );
* // returns true
*
* bool = isNodeStreamLike( {} );
* // returns false
*/
// MODULES //
var isNodeStreamLike = require( './main.js' );
// EXPORTS //
module.exports = isNodeStreamLike;
},{"./main.js":123}],123:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Tests if a value is Node stream-like.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is Node stream-like
*
* @example
* var transformStream = require( '@stdlib/streams/node/transform' );
*
* var stream = transformStream();
*
* var bool = isNodeStreamLike( stream );
* // returns true
*
* bool = isNodeStreamLike( {} );
* // returns false
*/
function isNodeStreamLike( value ) {
return (
// Must be an object:
value !== null &&
typeof value === 'object' &&
// Should be an event emitter:
typeof value.on === 'function' &&
typeof value.once === 'function' &&
typeof value.emit === 'function' &&
typeof value.addListener === 'function' &&
typeof value.removeListener === 'function' &&
typeof value.removeAllListeners === 'function' &&
// Should have a `pipe` method (Node streams inherit from `Stream`, including writable streams):
typeof value.pipe === 'function'
);
}
// EXPORTS //
module.exports = isNodeStreamLike;
},{}],124:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is Node writable stream-like.
*
* @module @stdlib/assert/is-node-writable-stream-like
*
* @example
* var transformStream = require( '@stdlib/streams/node/transform' );
* var isNodeWritableStreamLike = require( '@stdlib/assert/is-node-writable-stream-like' );
*
* var stream = transformStream();
*
* var bool = isNodeWritableStreamLike( stream );
* // returns true
*
* bool = isNodeWritableStreamLike( {} );
* // returns false
*/
// MODULES //
var isNodeWritableStreamLike = require( './main.js' );
// EXPORTS //
module.exports = isNodeWritableStreamLike;
},{"./main.js":125}],125:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
/* eslint-disable no-underscore-dangle */
'use strict';
// MODULES //
var isNodeStreamLike = require( '@stdlib/assert/is-node-stream-like' );
// MAIN //
/**
* Tests if a value is Node writable stream-like.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is Node writable stream-like
*
* @example
* var transformStream = require( '@stdlib/streams/node/transform' );
*
* var stream = transformStream();
*
* var bool = isNodeWritableStreamLike( stream );
* // returns true
*
* bool = isNodeWritableStreamLike( {} );
* // returns false
*/
function isNodeWritableStreamLike( value ) {
return (
// Must be stream-like:
isNodeStreamLike( value ) &&
// Should have writable stream methods:
typeof value._write === 'function' &&
// Should have writable stream state:
typeof value._writableState === 'object'
);
}
// EXPORTS //
module.exports = isNodeWritableStreamLike;
},{"@stdlib/assert/is-node-stream-like":122}],126:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is an array-like object containing only nonnegative integers.
*
* @module @stdlib/assert/is-nonnegative-integer-array
*
* @example
* var isNonNegativeIntegerArray = require( '@stdlib/assert/is-nonnegative-integer-array' );
*
* var bool = isNonNegativeIntegerArray( [ 3.0, new Number(3.0) ] );
* // returns true
*
* bool = isNonNegativeIntegerArray( [ 3.0, '3.0' ] );
* // returns false
*
* @example
* var isNonNegativeIntegerArray = require( '@stdlib/assert/is-nonnegative-integer-array' ).primitives;
*
* var bool = isNonNegativeIntegerArray( [ 1.0, 0.0, 10.0 ] );
* // returns true
*
* bool = isNonNegativeIntegerArray( [ 3.0, new Number(1.0) ] );
* // returns false
*
* @example
* var isNonNegativeIntegerArray = require( '@stdlib/assert/is-nonnegative-integer-array' ).objects;
*
* var bool = isNonNegativeIntegerArray( [ new Number(3.0), new Number(1.0) ] );
* // returns true
*
* bool = isNonNegativeIntegerArray( [ 1.0, 0.0, 10.0 ] );
* // returns false
*/
// MODULES //
var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' );
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var arrayfun = require( '@stdlib/assert/tools/array-like-function' );
// MAIN //
var isNonNegativeIntegerArray = arrayfun( isNonNegativeInteger );
setReadOnly( isNonNegativeIntegerArray, 'primitives', arrayfun( isNonNegativeInteger.isPrimitive ) );
setReadOnly( isNonNegativeIntegerArray, 'objects', arrayfun( isNonNegativeInteger.isObject ) );
// EXPORTS //
module.exports = isNonNegativeIntegerArray;
},{"@stdlib/assert/is-nonnegative-integer":127,"@stdlib/assert/tools/array-like-function":179,"@stdlib/utils/define-nonenumerable-read-only-property":396}],127:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is a nonnegative integer.
*
* @module @stdlib/assert/is-nonnegative-integer
*
* @example
* var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' );
*
* var bool = isNonNegativeInteger( 5.0 );
* // returns true
*
* bool = isNonNegativeInteger( new Number( 5.0 ) );
* // returns true
*
* bool = isNonNegativeInteger( -5.0 );
* // returns false
*
* bool = isNonNegativeInteger( 3.14 );
* // returns false
*
* bool = isNonNegativeInteger( null );
* // returns false
*
* @example
* var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ).isPrimitive;
*
* var bool = isNonNegativeInteger( 3.0 );
* // returns true
*
* bool = isNonNegativeInteger( new Number( 3.0 ) );
* // returns false
*
* @example
* var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ).isObject;
*
* var bool = isNonNegativeInteger( 3.0 );
* // returns false
*
* bool = isNonNegativeInteger( new Number( 3.0 ) );
* // returns true
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var isNonNegativeInteger = require( './main.js' );
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );
// MAIN //
setReadOnly( isNonNegativeInteger, 'isPrimitive', isPrimitive );
setReadOnly( isNonNegativeInteger, 'isObject', isObject );
// EXPORTS //
module.exports = isNonNegativeInteger;
},{"./main.js":128,"./object.js":129,"./primitive.js":130,"@stdlib/utils/define-nonenumerable-read-only-property":396}],128:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );
// MAIN //
/**
* Tests if a value is a nonnegative integer.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is a nonnegative integer
*
* @example
* var bool = isNonNegativeInteger( 5.0 );
* // returns true
*
* @example
* var bool = isNonNegativeInteger( new Number( 5.0 ) );
* // returns true
*
* @example
* var bool = isNonNegativeInteger( -5.0 );
* // returns false
*
* @example
* var bool = isNonNegativeInteger( 3.14 );
* // returns false
*
* @example
* var bool = isNonNegativeInteger( null );
* // returns false
*/
function isNonNegativeInteger( value ) {
return ( isPrimitive( value ) || isObject( value ) );
}
// EXPORTS //
module.exports = isNonNegativeInteger;
},{"./object.js":129,"./primitive.js":130}],129:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isInteger = require( '@stdlib/assert/is-integer' ).isObject;
// MAIN //
/**
* Tests if a value is a number object having a nonnegative integer value.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a number object having a nonnegative integer value
*
* @example
* var bool = isNonNegativeInteger( 3.0 );
* // returns false
*
* @example
* var bool = isNonNegativeInteger( new Number( 3.0 ) );
* // returns true
*/
function isNonNegativeInteger( value ) {
return (
isInteger( value ) &&
value.valueOf() >= 0
);
}
// EXPORTS //
module.exports = isNonNegativeInteger;
},{"@stdlib/assert/is-integer":110}],130:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isInteger = require( '@stdlib/assert/is-integer' ).isPrimitive;
// MAIN //
/**
* Tests if a value is a number primitive having a nonnegative integer value.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a number primitive having a nonnegative integer value
*
* @example
* var bool = isNonNegativeInteger( 3.0 );
* // returns true
*
* @example
* var bool = isNonNegativeInteger( new Number( 3.0 ) );
* // returns false
*/
function isNonNegativeInteger( value ) {
return (
isInteger( value ) &&
value >= 0
);
}
// EXPORTS //
module.exports = isNonNegativeInteger;
},{"@stdlib/assert/is-integer":110}],131:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is a nonnegative number.
*
* @module @stdlib/assert/is-nonnegative-number
*
* @example
* var isNonNegativeNumber = require( '@stdlib/assert/is-nonnegative-number' );
*
* var bool = isNonNegativeNumber( 5.0 );
* // returns true
*
* bool = isNonNegativeNumber( new Number( 5.0 ) );
* // returns true
*
* bool = isNonNegativeNumber( 3.14 );
* // returns true
*
* bool = isNonNegativeNumber( -5.0 );
* // returns false
*
* bool = isNonNegativeNumber( null );
* // returns false
*
* @example
* var isNonNegativeNumber = require( '@stdlib/assert/is-nonnegative-number' ).isPrimitive;
*
* var bool = isNonNegativeNumber( 3.0 );
* // returns true
*
* bool = isNonNegativeNumber( new Number( 3.0 ) );
* // returns false
*
* @example
* var isNonNegativeNumber = require( '@stdlib/assert/is-nonnegative-number' ).isObject;
*
* var bool = isNonNegativeNumber( 3.0 );
* // returns false
*
* bool = isNonNegativeNumber( new Number( 3.0 ) );
* // returns true
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var isNonNegativeNumber = require( './main.js' );
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );
// MAIN //
setReadOnly( isNonNegativeNumber, 'isPrimitive', isPrimitive );
setReadOnly( isNonNegativeNumber, 'isObject', isObject );
// EXPORTS //
module.exports = isNonNegativeNumber;
},{"./main.js":132,"./object.js":133,"./primitive.js":134,"@stdlib/utils/define-nonenumerable-read-only-property":396}],132:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );
// MAIN //
/**
* Tests if a value is a nonnegative number.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is a nonnegative number
*
* @example
* var bool = isNonNegativeNumber( 5.0 );
* // returns true
*
* @example
* var bool = isNonNegativeNumber( new Number( 5.0 ) );
* // returns true
*
* @example
* var bool = isNonNegativeNumber( 3.14 );
* // returns true
*
* @example
* var bool = isNonNegativeNumber( -5.0 );
* // returns false
*
* @example
* var bool = isNonNegativeNumber( null );
* // returns false
*/
function isNonNegativeNumber( value ) {
return ( isPrimitive( value ) || isObject( value ) );
}
// EXPORTS //
module.exports = isNonNegativeNumber;
},{"./object.js":133,"./primitive.js":134}],133:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isNumber = require( '@stdlib/assert/is-number' ).isObject;
// MAIN //
/**
* Tests if a value is a number object having a nonnegative value.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a number object having a nonnegative number value
*
* @example
* var bool = isNonNegativeNumber( 3.0 );
* // returns false
*
* @example
* var bool = isNonNegativeNumber( new Number( 3.0 ) );
* // returns true
*/
function isNonNegativeNumber( value ) {
return (
isNumber( value ) &&
value.valueOf() >= 0.0
);
}
// EXPORTS //
module.exports = isNonNegativeNumber;
},{"@stdlib/assert/is-number":137}],134:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isNumber = require( '@stdlib/assert/is-number' ).isPrimitive;
// MAIN //
/**
* Tests if a value is a number primitive having a nonnegative value.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a number primitive having a nonnegative number value
*
* @example
* var bool = isNonNegativeNumber( 3.0 );
* // returns true
*
* @example
* var bool = isNonNegativeNumber( new Number( 3.0 ) );
* // returns false
*/
function isNonNegativeNumber( value ) {
return (
isNumber( value ) &&
value >= 0.0
);
}
// EXPORTS //
module.exports = isNonNegativeNumber;
},{"@stdlib/assert/is-number":137}],135:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is `null`.
*
* @module @stdlib/assert/is-null
*
* @example
* var isNull = require( '@stdlib/assert/is-null' );
*
* var value = null;
*
* var bool = isNull( value );
* // returns true
*/
// MODULES //
var isNull = require( './main.js' );
// EXPORTS //
module.exports = isNull;
},{"./main.js":136}],136:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Tests if a value is `null`.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is null
*
* @example
* var bool = isNull( null );
* // returns true
*
* bool = isNull( true );
* // returns false
*/
function isNull( value ) {
return value === null;
}
// EXPORTS //
module.exports = isNull;
},{}],137:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is a number.
*
* @module @stdlib/assert/is-number
*
* @example
* var isNumber = require( '@stdlib/assert/is-number' );
*
* var bool = isNumber( 3.14 );
* // returns true
*
* bool = isNumber( new Number( 3.14 ) );
* // returns true
*
* bool = isNumber( NaN );
* // returns true
*
* bool = isNumber( null );
* // returns false
*
* @example
* var isNumber = require( '@stdlib/assert/is-number' ).isPrimitive;
*
* var bool = isNumber( 3.14 );
* // returns true
*
* bool = isNumber( NaN );
* // returns true
*
* bool = isNumber( new Number( 3.14 ) );
* // returns false
*
* @example
* var isNumber = require( '@stdlib/assert/is-number' ).isObject;
*
* var bool = isNumber( 3.14 );
* // returns false
*
* bool = isNumber( new Number( 3.14 ) );
* // returns true
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var isNumber = require( './main.js' );
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );
// MAIN //
setReadOnly( isNumber, 'isPrimitive', isPrimitive );
setReadOnly( isNumber, 'isObject', isObject );
// EXPORTS //
module.exports = isNumber;
},{"./main.js":138,"./object.js":139,"./primitive.js":140,"@stdlib/utils/define-nonenumerable-read-only-property":396}],138:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );
// MAIN //
/**
* Tests if a value is a number.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is a number
*
* @example
* var bool = isNumber( 3.14 );
* // returns true
*
* @example
* var bool = isNumber( new Number( 3.14 ) );
* // returns true
*
* @example
* var bool = isNumber( NaN );
* // returns true
*
* @example
* var bool = isNumber( null );
* // returns false
*/
function isNumber( value ) {
return ( isPrimitive( value ) || isObject( value ) );
}
// EXPORTS //
module.exports = isNumber;
},{"./object.js":139,"./primitive.js":140}],139:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var hasToStringTag = require( '@stdlib/assert/has-tostringtag-support' );
var nativeClass = require( '@stdlib/utils/native-class' );
var Number = require( '@stdlib/number/ctor' );
var test = require( './try2serialize.js' );
// VARIABLES //
var FLG = hasToStringTag();
// MAIN //
/**
* Tests if a value is a number object.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a number object
*
* @example
* var bool = isNumber( 3.14 );
* // returns false
*
* @example
* var bool = isNumber( new Number( 3.14 ) );
* // returns true
*/
function isNumber( value ) {
if ( typeof value === 'object' ) {
if ( value instanceof Number ) {
return true;
}
if ( FLG ) {
return test( value );
}
return ( nativeClass( value ) === '[object Number]' );
}
return false;
}
// EXPORTS //
module.exports = isNumber;
},{"./try2serialize.js":142,"@stdlib/assert/has-tostringtag-support":57,"@stdlib/number/ctor":303,"@stdlib/utils/native-class":445}],140:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Tests if a value is a number primitive.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a number primitive
*
* @example
* var bool = isNumber( 3.14 );
* // returns true
*
* @example
* var bool = isNumber( NaN );
* // returns true
*
* @example
* var bool = isNumber( new Number( 3.14 ) );
* // returns false
*/
function isNumber( value ) {
return ( typeof value === 'number' );
}
// EXPORTS //
module.exports = isNumber;
},{}],141:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var Number = require( '@stdlib/number/ctor' );
// MAIN //
// eslint-disable-next-line stdlib/no-redeclare
var toString = Number.prototype.toString; // non-generic
// EXPORTS //
module.exports = toString;
},{"@stdlib/number/ctor":303}],142:[function(require,module,exports){
arguments[4][86][0].apply(exports,arguments)
},{"./tostring.js":141,"dup":86}],143:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is object-like.
*
* @module @stdlib/assert/is-object-like
*
* @example
* var isObjectLike = require( '@stdlib/assert/is-object-like' );
*
* var bool = isObjectLike( {} );
* // returns true
*
* bool = isObjectLike( [] );
* // returns true
*
* bool = isObjectLike( null );
* // returns false
*
* @example
* var isObjectLike = require( '@stdlib/assert/is-object-like' ).isObjectLikeArray;
*
* var bool = isObjectLike( [ {}, [] ] );
* // returns true
*
* bool = isObjectLike( [ {}, '3.0' ] );
* // returns false
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var arrayfun = require( '@stdlib/assert/tools/array-function' );
var isObjectLike = require( './main.js' );
// MAIN //
setReadOnly( isObjectLike, 'isObjectLikeArray', arrayfun( isObjectLike ) );
// EXPORTS //
module.exports = isObjectLike;
},{"./main.js":144,"@stdlib/assert/tools/array-function":177,"@stdlib/utils/define-nonenumerable-read-only-property":396}],144:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Tests if a value is object-like.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether a value is object-like
*
* @example
* var bool = isObjectLike( {} );
* // returns true
*
* @example
* var bool = isObjectLike( [] );
* // returns true
*
* @example
* var bool = isObjectLike( null );
* // returns false
*/
function isObjectLike( value ) {
return (
value !== null &&
typeof value === 'object'
);
}
// EXPORTS //
module.exports = isObjectLike;
},{}],145:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is an object.
*
* @module @stdlib/assert/is-object
*
* @example
* var isObject = require( '@stdlib/assert/is-object' );
*
* var bool = isObject( {} );
* // returns true
*
* bool = isObject( true );
* // returns false
*/
// MODULES //
var isObject = require( './main.js' );
// EXPORTS //
module.exports = isObject;
},{"./main.js":146}],146:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isArray = require( '@stdlib/assert/is-array' );
// MAIN //
/**
* Tests if a value is an object; e.g., `{}`.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is an object
*
* @example
* var bool = isObject( {} );
* // returns true
*
* @example
* var bool = isObject( null );
* // returns false
*/
function isObject( value ) {
return (
typeof value === 'object' &&
value !== null &&
!isArray( value )
);
}
// EXPORTS //
module.exports = isObject;
},{"@stdlib/assert/is-array":79}],147:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is a plain object.
*
* @module @stdlib/assert/is-plain-object
*
* @example
* var isPlainObject = require( '@stdlib/assert/is-plain-object' );
*
* var bool = isPlainObject( {} );
* // returns true
*
* bool = isPlainObject( null );
* // returns false
*/
// MODULES //
var isPlainObject = require( './main.js' );
// EXPORTS //
module.exports = isPlainObject;
},{"./main.js":148}],148:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isObject = require( '@stdlib/assert/is-object' );
var isFunction = require( '@stdlib/assert/is-function' );
var getPrototypeOf = require( '@stdlib/utils/get-prototype-of' );
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var nativeClass = require( '@stdlib/utils/native-class' );
// VARIABLES //
var objectPrototype = Object.prototype;
// FUNCTIONS //
/**
* Tests that an object only has own properties.
*
* @private
* @param {Object} obj - value to test
* @returns {boolean} boolean indicating if an object only has own properties
*/
function ownProps( obj ) {
var key;
// NOTE: possibility of perf boost if key enumeration order is known (see http://stackoverflow.com/questions/18531624/isplainobject-thing).
for ( key in obj ) {
if ( !hasOwnProp( obj, key ) ) {
return false;
}
}
return true;
}
// MAIN //
/**
* Tests if a value is a plain object.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is a plain object
*
* @example
* var bool = isPlainObject( {} );
* // returns true
*
* @example
* var bool = isPlainObject( null );
* // returns false
*/
function isPlainObject( value ) {
var proto;
// Screen for obvious non-objects...
if ( !isObject( value ) ) {
return false;
}
// Objects with no prototype (e.g., `Object.create( null )`) are plain...
proto = getPrototypeOf( value );
if ( !proto ) {
return true;
}
// Objects having a prototype are plain if and only if they are constructed with a global `Object` function and the prototype points to the prototype of a plain object...
return (
// Cannot have own `constructor` property:
!hasOwnProp( value, 'constructor' ) &&
// Prototype `constructor` property must be a function (see also https://bugs.jquery.com/ticket/9897 and http://stackoverflow.com/questions/18531624/isplainobject-thing):
hasOwnProp( proto, 'constructor' ) &&
isFunction( proto.constructor ) &&
nativeClass( proto.constructor ) === '[object Function]' &&
// Test for object-specific method:
hasOwnProp( proto, 'isPrototypeOf' ) &&
isFunction( proto.isPrototypeOf ) &&
(
// Test if the prototype matches the global `Object` prototype (same realm):
proto === objectPrototype ||
// Test that all properties are own properties (cross-realm; *most* likely a plain object):
ownProps( value )
)
);
}
// EXPORTS //
module.exports = isPlainObject;
},{"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-function":102,"@stdlib/assert/is-object":145,"@stdlib/utils/get-prototype-of":411,"@stdlib/utils/native-class":445}],149:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is a positive integer.
*
* @module @stdlib/assert/is-positive-integer
*
* @example
* var isPositiveInteger = require( '@stdlib/assert/is-positive-integer' );
*
* var bool = isPositiveInteger( 5.0 );
* // returns true
*
* bool = isPositiveInteger( new Number( 5.0 ) );
* // returns true
*
* bool = isPositiveInteger( -5.0 );
* // returns false
*
* bool = isPositiveInteger( 3.14 );
* // returns false
*
* bool = isPositiveInteger( null );
* // returns false
*
* @example
* var isPositiveInteger = require( '@stdlib/assert/is-positive-integer' ).isPrimitive;
*
* var bool = isPositiveInteger( 3.0 );
* // returns true
*
* bool = isPositiveInteger( new Number( 3.0 ) );
* // returns false
*
* @example
* var isPositiveInteger = require( '@stdlib/assert/is-positive-integer' ).isObject;
*
* var bool = isPositiveInteger( 3.0 );
* // returns false
*
* bool = isPositiveInteger( new Number( 3.0 ) );
* // returns true
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var isPositiveInteger = require( './main.js' );
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );
// MAIN //
setReadOnly( isPositiveInteger, 'isPrimitive', isPrimitive );
setReadOnly( isPositiveInteger, 'isObject', isObject );
// EXPORTS //
module.exports = isPositiveInteger;
},{"./main.js":150,"./object.js":151,"./primitive.js":152,"@stdlib/utils/define-nonenumerable-read-only-property":396}],150:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );
// MAIN //
/**
* Tests if a value is a positive integer.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is a positive integer
*
* @example
* var bool = isPositiveInteger( 5.0 );
* // returns true
*
* @example
* var bool = isPositiveInteger( new Number( 5.0 ) );
* // returns true
*
* @example
* var bool = isPositiveInteger( 0.0 );
* // returns false
*
* @example
* var bool = isPositiveInteger( -5.0 );
* // returns false
*
* @example
* var bool = isPositiveInteger( 3.14 );
* // returns false
*
* @example
* var bool = isPositiveInteger( null );
* // returns false
*/
function isPositiveInteger( value ) {
return ( isPrimitive( value ) || isObject( value ) );
}
// EXPORTS //
module.exports = isPositiveInteger;
},{"./object.js":151,"./primitive.js":152}],151:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isInteger = require( '@stdlib/assert/is-integer' ).isObject;
// MAIN //
/**
* Tests if a value is a number object having a positive integer value.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a number object having a positive integer value
*
* @example
* var bool = isPositiveInteger( 3.0 );
* // returns false
*
* @example
* var bool = isPositiveInteger( new Number( 3.0 ) );
* // returns true
*/
function isPositiveInteger( value ) {
return (
isInteger( value ) &&
value.valueOf() > 0.0
);
}
// EXPORTS //
module.exports = isPositiveInteger;
},{"@stdlib/assert/is-integer":110}],152:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isInteger = require( '@stdlib/assert/is-integer' ).isPrimitive;
// MAIN //
/**
* Tests if a value is a number primitive having a positive integer value.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a number primitive having a positive integer value
*
* @example
* var bool = isPositiveInteger( 3.0 );
* // returns true
*
* @example
* var bool = isPositiveInteger( new Number( 3.0 ) );
* // returns false
*/
function isPositiveInteger( value ) {
return (
isInteger( value ) &&
value > 0.0
);
}
// EXPORTS //
module.exports = isPositiveInteger;
},{"@stdlib/assert/is-integer":110}],153:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
var exec = RegExp.prototype.exec; // non-generic
// EXPORTS //
module.exports = exec;
},{}],154:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is a regular expression.
*
* @module @stdlib/assert/is-regexp
*
* @example
* var isRegExp = require( '@stdlib/assert/is-regexp' );
*
* var bool = isRegExp( /\.+/ );
* // returns true
*
* bool = isRegExp( {} );
* // returns false
*/
// MODULES //
var isRegExp = require( './main.js' );
// EXPORTS //
module.exports = isRegExp;
},{"./main.js":155}],155:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var hasToStringTag = require( '@stdlib/assert/has-tostringtag-support' );
var nativeClass = require( '@stdlib/utils/native-class' );
var test = require( './try2exec.js' );
// VARIABLES //
var FLG = hasToStringTag();
// MAIN //
/**
* Tests if a value is a regular expression.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is a regular expression
*
* @example
* var bool = isRegExp( /\.+/ );
* // returns true
*
* @example
* var bool = isRegExp( {} );
* // returns false
*/
function isRegExp( value ) {
if ( typeof value === 'object' ) {
if ( value instanceof RegExp ) {
return true;
}
if ( FLG ) {
return test( value );
}
return ( nativeClass( value ) === '[object RegExp]' );
}
return false;
}
// EXPORTS //
module.exports = isRegExp;
},{"./try2exec.js":156,"@stdlib/assert/has-tostringtag-support":57,"@stdlib/utils/native-class":445}],156:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var exec = require( './exec.js' );
// MAIN //
/**
* Attempts to call a `RegExp` method.
*
* @private
* @param {*} value - value to test
* @returns {boolean} boolean indicating if able to call a `RegExp` method
*/
function test( value ) {
try {
exec.call( value );
return true;
} catch ( err ) { // eslint-disable-line no-unused-vars
return false;
}
}
// EXPORTS //
module.exports = test;
},{"./exec.js":153}],157:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is an array of strings.
*
* @module @stdlib/assert/is-string-array
*
* @example
* var isStringArray = require( '@stdlib/assert/is-string-array' );
*
* var bool = isStringArray( [ 'abc', 'def' ] );
* // returns true
*
* bool = isStringArray( [ 'abc', 123 ] );
* // returns false
*
* @example
* var isStringArray = require( '@stdlib/assert/is-string-array' ).primitives;
*
* var bool = isStringArray( [ 'abc', 'def' ] );
* // returns true
*
* bool = isStringArray( [ 'abc', new String( 'def' ) ] );
* // returns false
*
* @example
* var isStringArray = require( '@stdlib/assert/is-string-array' ).objects;
*
* var bool = isStringArray( [ new String( 'abc' ), new String( 'def' ) ] );
* // returns true
*
* bool = isStringArray( [ new String( 'abc' ), 'def' ] );
* // returns false
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var arrayfun = require( '@stdlib/assert/tools/array-function' );
var isString = require( '@stdlib/assert/is-string' );
// MAIN //
var isStringArray = arrayfun( isString );
setReadOnly( isStringArray, 'primitives', arrayfun( isString.isPrimitive ) );
setReadOnly( isStringArray, 'objects', arrayfun( isString.isObject ) );
// EXPORTS //
module.exports = isStringArray;
},{"@stdlib/assert/is-string":158,"@stdlib/assert/tools/array-function":177,"@stdlib/utils/define-nonenumerable-read-only-property":396}],158:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is a string.
*
* @module @stdlib/assert/is-string
*
* @example
* var isString = require( '@stdlib/assert/is-string' );
*
* var bool = isString( 'beep' );
* // returns true
*
* bool = isString( new String( 'beep' ) );
* // returns true
*
* bool = isString( 5 );
* // returns false
*
* @example
* var isString = require( '@stdlib/assert/is-string' ).isObject;
*
* var bool = isString( new String( 'beep' ) );
* // returns true
*
* bool = isString( 'beep' );
* // returns false
*
* @example
* var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
*
* var bool = isString( 'beep' );
* // returns true
*
* bool = isString( new String( 'beep' ) );
* // returns false
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var isString = require( './main.js' );
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );
// MAIN //
setReadOnly( isString, 'isPrimitive', isPrimitive );
setReadOnly( isString, 'isObject', isObject );
// EXPORTS //
module.exports = isString;
},{"./main.js":159,"./object.js":160,"./primitive.js":161,"@stdlib/utils/define-nonenumerable-read-only-property":396}],159:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );
// MAIN //
/**
* Tests if a value is a string.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is a string
*
* @example
* var bool = isString( new String( 'beep' ) );
* // returns true
*
* @example
* var bool = isString( 'beep' );
* // returns true
*/
function isString( value ) {
return ( isPrimitive( value ) || isObject( value ) );
}
// EXPORTS //
module.exports = isString;
},{"./object.js":160,"./primitive.js":161}],160:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var hasToStringTag = require( '@stdlib/assert/has-tostringtag-support' );
var nativeClass = require( '@stdlib/utils/native-class' );
var test = require( './try2valueof.js' );
// VARIABLES //
var FLG = hasToStringTag();
// MAIN //
/**
* Tests if a value is a string object.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a string object
*
* @example
* var bool = isString( new String( 'beep' ) );
* // returns true
*
* @example
* var bool = isString( 'beep' );
* // returns false
*/
function isString( value ) {
if ( typeof value === 'object' ) {
if ( value instanceof String ) {
return true;
}
if ( FLG ) {
return test( value );
}
return ( nativeClass( value ) === '[object String]' );
}
return false;
}
// EXPORTS //
module.exports = isString;
},{"./try2valueof.js":162,"@stdlib/assert/has-tostringtag-support":57,"@stdlib/utils/native-class":445}],161:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Tests if a value is a string primitive.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a string primitive
*
* @example
* var bool = isString( 'beep' );
* // returns true
*
* @example
* var bool = isString( new String( 'beep' ) );
* // returns false
*/
function isString( value ) {
return ( typeof value === 'string' );
}
// EXPORTS //
module.exports = isString;
},{}],162:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var valueOf = require( './valueof.js' ); // eslint-disable-line stdlib/no-redeclare
// MAIN //
/**
* Attempts to extract a string value.
*
* @private
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a string can be extracted
*/
function test( value ) {
try {
valueOf.call( value );
return true;
} catch ( err ) { // eslint-disable-line no-unused-vars
return false;
}
}
// EXPORTS //
module.exports = test;
},{"./valueof.js":163}],163:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// eslint-disable-next-line stdlib/no-redeclare
var valueOf = String.prototype.valueOf; // non-generic
// EXPORTS //
module.exports = valueOf;
},{}],164:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var Int8Array = require( '@stdlib/array/int8' );
var Uint8Array = require( '@stdlib/array/uint8' );
var Uint8ClampedArray = require( '@stdlib/array/uint8c' );
var Int16Array = require( '@stdlib/array/int16' );
var Uint16Array = require( '@stdlib/array/uint16' );
var Int32Array = require( '@stdlib/array/int32' );
var Uint32Array = require( '@stdlib/array/uint32' );
var Float32Array = require( '@stdlib/array/float32' );
var Float64Array = require( '@stdlib/array/float64' );
// MAIN //
var CTORS = [
Float64Array,
Float32Array,
Int32Array,
Uint32Array,
Int16Array,
Uint16Array,
Int8Array,
Uint8Array,
Uint8ClampedArray
];
// EXPORTS //
module.exports = CTORS;
},{"@stdlib/array/float32":2,"@stdlib/array/float64":5,"@stdlib/array/int16":7,"@stdlib/array/int32":10,"@stdlib/array/int8":13,"@stdlib/array/uint16":20,"@stdlib/array/uint32":23,"@stdlib/array/uint8":26,"@stdlib/array/uint8c":29}],165:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is a typed array.
*
* @module @stdlib/assert/is-typed-array
*
* @example
* var Int8Array = require( '@stdlib/array/int8' );
* var isTypedArray = require( '@stdlib/assert/is-typed-array' );
*
* var bool = isTypedArray( new Int8Array( 10 ) );
* // returns true
*/
// MODULES //
var isTypedArray = require( './main.js' );
// EXPORTS //
module.exports = isTypedArray;
},{"./main.js":166}],166:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var ctorName = require( '@stdlib/utils/constructor-name' );
var fcnName = require( '@stdlib/utils/function-name' );
var getPrototypeOf = require( '@stdlib/utils/get-prototype-of' );
var hasFloat64ArraySupport = require( '@stdlib/assert/has-float64array-support' );
var Float64Array = require( '@stdlib/array/float64' );
var CTORS = require( './ctors.js' );
var NAMES = require( './names.json' );
// VARIABLES //
// Abstract `TypedArray` class:
var TypedArray = ( hasFloat64ArraySupport() ) ? getPrototypeOf( Float64Array ) : Dummy; // eslint-disable-line max-len
// Ensure abstract typed array class has expected name:
TypedArray = ( fcnName( TypedArray ) === 'TypedArray' ) ? TypedArray : Dummy;
// FUNCTIONS //
/**
* Dummy constructor.
*
* @private
*/
function Dummy() {} // eslint-disable-line no-empty-function
// MAIN //
/**
* Tests if a value is a typed array.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a typed array
*
* @example
* var Int8Array = require( '@stdlib/array/int8' );
*
* var bool = isTypedArray( new Int8Array( 10 ) );
* // returns true
*/
function isTypedArray( value ) {
var v;
var i;
if ( typeof value !== 'object' || value === null ) {
return false;
}
// Check for the abstract class...
if ( value instanceof TypedArray ) {
return true;
}
// Check for typed array objects from the same realm (same Node.js `vm` or same `Window` object)...
for ( i = 0; i < CTORS.length; i++ ) {
if ( value instanceof CTORS[ i ] ) {
return true;
}
}
// Walk the prototype tree until we find an object having a desired class...
while ( value ) {
v = ctorName( value );
for ( i = 0; i < NAMES.length; i++ ) {
if ( NAMES[ i ] === v ) {
return true;
}
}
value = getPrototypeOf( value );
}
return false;
}
// EXPORTS //
module.exports = isTypedArray;
},{"./ctors.js":164,"./names.json":167,"@stdlib/array/float64":5,"@stdlib/assert/has-float64array-support":36,"@stdlib/utils/constructor-name":388,"@stdlib/utils/function-name":408,"@stdlib/utils/get-prototype-of":411}],167:[function(require,module,exports){
module.exports=[
"Int8Array",
"Uint8Array",
"Uint8ClampedArray",
"Int16Array",
"Uint16Array",
"Int32Array",
"Uint32Array",
"Float32Array",
"Float64Array"
]
},{}],168:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is a Uint16Array.
*
* @module @stdlib/assert/is-uint16array
*
* @example
* var isUint16Array = require( '@stdlib/assert/is-uint16array' );
*
* var bool = isUint16Array( new Uint16Array( 10 ) );
* // returns true
*
* bool = isUint16Array( [] );
* // returns false
*/
// MODULES //
var isUint16Array = require( './main.js' );
// EXPORTS //
module.exports = isUint16Array;
},{"./main.js":169}],169:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var nativeClass = require( '@stdlib/utils/native-class' );
// VARIABLES //
var hasUint16Array = ( typeof Uint16Array === 'function' ); // eslint-disable-line stdlib/require-globals
// MAIN //
/**
* Tests if a value is a Uint16Array.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is a Uint16Array
*
* @example
* var bool = isUint16Array( new Uint16Array( 10 ) );
* // returns true
*
* @example
* var bool = isUint16Array( [] );
* // returns false
*/
function isUint16Array( value ) {
return (
( hasUint16Array && value instanceof Uint16Array ) || // eslint-disable-line stdlib/require-globals
nativeClass( value ) === '[object Uint16Array]'
);
}
// EXPORTS //
module.exports = isUint16Array;
},{"@stdlib/utils/native-class":445}],170:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is a Uint32Array.
*
* @module @stdlib/assert/is-uint32array
*
* @example
* var isUint32Array = require( '@stdlib/assert/is-uint32array' );
*
* var bool = isUint32Array( new Uint32Array( 10 ) );
* // returns true
*
* bool = isUint32Array( [] );
* // returns false
*/
// MODULES //
var isUint32Array = require( './main.js' );
// EXPORTS //
module.exports = isUint32Array;
},{"./main.js":171}],171:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var nativeClass = require( '@stdlib/utils/native-class' );
// VARIABLES //
var hasUint32Array = ( typeof Uint32Array === 'function' ); // eslint-disable-line stdlib/require-globals
// MAIN //
/**
* Tests if a value is a Uint32Array.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is a Uint32Array
*
* @example
* var bool = isUint32Array( new Uint32Array( 10 ) );
* // returns true
*
* @example
* var bool = isUint32Array( [] );
* // returns false
*/
function isUint32Array( value ) {
return (
( hasUint32Array && value instanceof Uint32Array ) || // eslint-disable-line stdlib/require-globals
nativeClass( value ) === '[object Uint32Array]'
);
}
// EXPORTS //
module.exports = isUint32Array;
},{"@stdlib/utils/native-class":445}],172:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is a Uint8Array.
*
* @module @stdlib/assert/is-uint8array
*
* @example
* var isUint8Array = require( '@stdlib/assert/is-uint8array' );
*
* var bool = isUint8Array( new Uint8Array( 10 ) );
* // returns true
*
* bool = isUint8Array( [] );
* // returns false
*/
// MODULES //
var isUint8Array = require( './main.js' );
// EXPORTS //
module.exports = isUint8Array;
},{"./main.js":173}],173:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var nativeClass = require( '@stdlib/utils/native-class' );
// VARIABLES //
var hasUint8Array = ( typeof Uint8Array === 'function' ); // eslint-disable-line stdlib/require-globals
// MAIN //
/**
* Tests if a value is a Uint8Array.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is a Uint8Array
*
* @example
* var bool = isUint8Array( new Uint8Array( 10 ) );
* // returns true
*
* @example
* var bool = isUint8Array( [] );
* // returns false
*/
function isUint8Array( value ) {
return (
( hasUint8Array && value instanceof Uint8Array ) || // eslint-disable-line stdlib/require-globals
nativeClass( value ) === '[object Uint8Array]'
);
}
// EXPORTS //
module.exports = isUint8Array;
},{"@stdlib/utils/native-class":445}],174:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is a Uint8ClampedArray.
*
* @module @stdlib/assert/is-uint8clampedarray
*
* @example
* var isUint8ClampedArray = require( '@stdlib/assert/is-uint8clampedarray' );
*
* var bool = isUint8ClampedArray( new Uint8ClampedArray( 10 ) );
* // returns true
*
* bool = isUint8ClampedArray( [] );
* // returns false
*/
// MODULES //
var isUint8ClampedArray = require( './main.js' );
// EXPORTS //
module.exports = isUint8ClampedArray;
},{"./main.js":175}],175:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var nativeClass = require( '@stdlib/utils/native-class' );
// VARIABLES //
var hasUint8ClampedArray = ( typeof Uint8ClampedArray === 'function' ); // eslint-disable-line stdlib/require-globals
// MAIN //
/**
* Tests if a value is a Uint8ClampedArray.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is a Uint8ClampedArray
*
* @example
* var bool = isUint8ClampedArray( new Uint8ClampedArray( 10 ) );
* // returns true
*
* @example
* var bool = isUint8ClampedArray( [] );
* // returns false
*/
function isUint8ClampedArray( value ) {
return (
( hasUint8ClampedArray && value instanceof Uint8ClampedArray ) || // eslint-disable-line stdlib/require-globals
nativeClass( value ) === '[object Uint8ClampedArray]'
);
}
// EXPORTS //
module.exports = isUint8ClampedArray;
},{"@stdlib/utils/native-class":445}],176:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isArray = require( '@stdlib/assert/is-array' );
// MAIN //
/**
* Returns a function which tests if every element in an array passes a test condition.
*
* @param {Function} predicate - function to apply
* @throws {TypeError} must provide a function
* @returns {Function} an array function
*
* @example
* var isOdd = require( '@stdlib/assert/is-odd' );
*
* var arr1 = [ 1, 3, 5, 7 ];
* var arr2 = [ 3, 5, 8 ];
*
* var validate = arrayfcn( isOdd );
*
* var bool = validate( arr1 );
* // returns true
*
* bool = validate( arr2 );
* // returns false
*/
function arrayfcn( predicate ) {
if ( typeof predicate !== 'function' ) {
throw new TypeError( 'invalid argument. Must provide a function. Value: `' + predicate + '`.' );
}
return every;
/**
* Tests if every element in an array passes a test condition.
*
* @private
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether a value is an array for which all elements pass a test condition
*/
function every( value ) {
var len;
var i;
if ( !isArray( value ) ) {
return false;
}
len = value.length;
if ( len === 0 ) {
return false;
}
for ( i = 0; i < len; i++ ) {
if ( predicate( value[ i ] ) === false ) {
return false;
}
}
return true;
}
}
// EXPORTS //
module.exports = arrayfcn;
},{"@stdlib/assert/is-array":79}],177:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Return a function which tests if every element in an array passes a test condition.
*
* @module @stdlib/assert/tools/array-function
*
* @example
* var isOdd = require( '@stdlib/assert/is-odd' );
* var arrayfcn = require( '@stdlib/assert/tools/array-function' );
*
* var arr1 = [ 1, 3, 5, 7 ];
* var arr2 = [ 3, 5, 8 ];
*
* var validate = arrayfcn( isOdd );
*
* var bool = validate( arr1 );
* // returns true
*
* bool = validate( arr2 );
* // returns false
*/
// MODULES //
var arrayfcn = require( './arrayfcn.js' );
// EXPORTS //
module.exports = arrayfcn;
},{"./arrayfcn.js":176}],178:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isArrayLike = require( '@stdlib/assert/is-array-like' );
// MAIN //
/**
* Returns a function which tests if every element in an array-like object passes a test condition.
*
* @param {Function} predicate - function to apply
* @throws {TypeError} must provide a function
* @returns {Function} an array-like object function
*
* @example
* var isOdd = require( '@stdlib/assert/is-odd' );
*
* var arr1 = [ 1, 3, 5, 7 ];
* var arr2 = [ 3, 5, 8 ];
*
* var validate = arraylikefcn( isOdd );
*
* var bool = validate( arr1 );
* // returns true
*
* bool = validate( arr2 );
* // returns false
*/
function arraylikefcn( predicate ) {
if ( typeof predicate !== 'function' ) {
throw new TypeError( 'invalid argument. Must provide a function. Value: `' + predicate + '`.' );
}
return every;
/**
* Tests if every element in an array-like object passes a test condition.
*
* @private
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether a value is an array-like object for which all elements pass a test condition
*/
function every( value ) {
var len;
var i;
if ( !isArrayLike( value ) ) {
return false;
}
len = value.length;
if ( len === 0 ) {
return false;
}
for ( i = 0; i < len; i++ ) {
if ( predicate( value[ i ] ) === false ) {
return false;
}
}
return true;
}
}
// EXPORTS //
module.exports = arraylikefcn;
},{"@stdlib/assert/is-array-like":77}],179:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Return a function which tests if every element in an array-like object passes a test condition.
*
* @module @stdlib/assert/tools/array-like-function
*
* @example
* var isOdd = require( '@stdlib/assert/is-odd' );
* var arraylikefcn = require( '@stdlib/assert/tools/array-like-function' );
*
* var arr1 = [ 1, 3, 5, 7 ];
* var arr2 = [ 3, 5, 8 ];
*
* var validate = arraylikefcn( isOdd );
*
* var bool = validate( arr1 );
* // returns true
*
* bool = validate( arr2 );
* // returns false
*/
// MODULES //
var arraylikefcn = require( './arraylikefcn.js' );
// EXPORTS //
module.exports = arraylikefcn;
},{"./arraylikefcn.js":178}],180:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var TransformStream = require( '@stdlib/streams/node/transform' );
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var isFunction = require( '@stdlib/assert/is-function' );
var createHarness = require( './harness' );
var harness = require( './get_harness.js' );
// VARIABLES //
var listeners = [];
// FUNCTIONS //
/**
* Callback invoked when a harness finishes running all benchmarks.
*
* @private
*/
function done() {
var len;
var f;
var i;
len = listeners.length;
// Inform all the listeners that the harness has finished...
for ( i = 0; i < len; i++ ) {
f = listeners.shift();
f();
}
}
/**
* Creates a results stream.
*
* @private
* @param {Options} [options] - stream options
* @throws {Error} must provide valid stream options
* @returns {TransformStream} results stream
*/
function createStream( options ) {
var stream;
var bench;
var opts;
if ( arguments.length ) {
opts = options;
} else {
opts = {};
}
// If we have already created a harness, calling this function simply creates another results stream...
if ( harness.cached ) {
bench = harness();
return bench.createStream( opts );
}
stream = new TransformStream( opts );
opts.stream = stream;
// Create a harness which uses the created output stream:
harness( opts, done );
return stream;
}
/**
* Adds a listener for when a harness finishes running all benchmarks.
*
* @private
* @param {Callback} clbk - listener
* @throws {TypeError} must provide a function
* @throws {Error} must provide a listener only once
* @returns {void}
*/
function onFinish( clbk ) {
var i;
if ( !isFunction( clbk ) ) {
throw new TypeError( 'invalid argument. Must provide a function. Value: `'+clbk+'`.' );
}
// Allow adding a listener only once...
for ( i = 0; i < listeners.length; i++ ) {
if ( clbk === listeners[ i ] ) {
throw new Error( 'invalid argument. Attempted to add duplicate listener.' );
}
}
listeners.push( clbk );
}
// MAIN //
/**
* Runs a benchmark.
*
* @param {string} name - benchmark name
* @param {Options} [options] - benchmark options
* @param {boolean} [options.skip=false] - boolean indicating whether to skip a benchmark
* @param {(PositiveInteger|null)} [options.iterations=null] - number of iterations
* @param {PositiveInteger} [options.repeats=3] - number of repeats
* @param {PositiveInteger} [options.timeout=300000] - number of milliseconds before a benchmark automatically fails
* @param {Function} [benchmark] - function containing benchmark code
* @throws {TypeError} first argument must be a string
* @throws {TypeError} options argument must be an object
* @throws {TypeError} must provide valid options
* @throws {TypeError} benchmark argument must a function
* @returns {Benchmark} benchmark harness
*
* @example
* bench( 'beep', function benchmark( b ) {
* var x;
* var i;
* b.tic();
* for ( i = 0; i < b.iterations; i++ ) {
* x = Math.sin( Math.random() );
* if ( x !== x ) {
* b.ok( false, 'should not return NaN' );
* }
* }
* b.toc();
* if ( x !== x ) {
* b.ok( false, 'should not return NaN' );
* }
* b.end();
* });
*/
function bench( name, options, benchmark ) {
var h = harness( done );
if ( arguments.length < 2 ) {
h( name );
} else if ( arguments.length === 2 ) {
h( name, options );
} else {
h( name, options, benchmark );
}
return bench;
}
/**
* Creates a benchmark harness.
*
* @name createHarness
* @memberof bench
* @type {Function}
* @param {Options} [options] - harness options
* @param {Callback} [clbk] - callback to invoke when a harness finishes running all benchmarks
* @throws {TypeError} options argument must be an object
* @throws {TypeError} must provide valid options
* @throws {TypeError} callback argument must be a function
* @returns {Function} benchmark harness
*/
setReadOnly( bench, 'createHarness', createHarness );
/**
* Creates a results stream.
*
* @name createStream
* @memberof bench
* @type {Function}
* @param {Options} [options] - stream options
* @throws {Error} must provide valid stream options
* @returns {TransformStream} results stream
*/
setReadOnly( bench, 'createStream', createStream );
/**
* Adds a listener for when a harness finishes running all benchmarks.
*
* @name onFinish
* @memberof bench
* @type {Function}
* @param {Callback} clbk - listener
* @throws {TypeError} must provide a function
* @throws {Error} must provide a listener only once
* @returns {void}
*/
setReadOnly( bench, 'onFinish', onFinish );
// EXPORTS //
module.exports = bench;
},{"./get_harness.js":202,"./harness":203,"@stdlib/assert/is-function":102,"@stdlib/streams/node/transform":372,"@stdlib/utils/define-nonenumerable-read-only-property":396}],181:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
// MAIN //
/**
* Generates an assertion.
*
* @private
* @param {boolean} ok - assertion outcome
* @param {Options} opts - options
*/
function assert( ok, opts ) {
/* eslint-disable no-invalid-this, no-unused-vars */ // TODO: remove no-unused-vars once `err` is used
var result;
var err;
result = {
'id': this._count,
'ok': ok,
'skip': opts.skip,
'todo': opts.todo,
'name': opts.message || '(unnamed assert)',
'operator': opts.operator
};
if ( hasOwnProp( opts, 'actual' ) ) {
result.actual = opts.actual;
}
if ( hasOwnProp( opts, 'expected' ) ) {
result.expected = opts.expected;
}
if ( !ok ) {
result.error = opts.error || new Error( this.name );
err = new Error( 'exception' );
// TODO: generate an exception in order to locate the calling function (https://github.com/substack/tape/blob/master/lib/test.js#L215)
}
this._count += 1;
this.emit( 'result', result );
}
// EXPORTS //
module.exports = assert;
},{"@stdlib/assert/has-own-property":53}],182:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// EXPORTS //
module.exports = clearTimeout;
},{}],183:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var trim = require( '@stdlib/string/trim' );
var replace = require( '@stdlib/string/replace' );
var EOL = require( '@stdlib/regexp/eol' ).REGEXP;
// VARIABLES //
var RE_COMMENT = /^#\s*/;
// MAIN //
/**
* Writes a comment.
*
* @private
* @param {string} msg - comment message
*/
function comment( msg ) {
/* eslint-disable no-invalid-this */
var lines;
var i;
msg = trim( msg );
lines = msg.split( EOL );
for ( i = 0; i < lines.length; i++ ) {
msg = trim( lines[ i ] );
msg = replace( msg, RE_COMMENT, '' );
this.emit( 'result', msg );
}
}
// EXPORTS //
module.exports = comment;
},{"@stdlib/regexp/eol":349,"@stdlib/string/replace":378,"@stdlib/string/trim":380}],184:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Asserts that `actual` is deeply equal to `expected`.
*
* @private
* @param {*} actual - actual value
* @param {*} expected - expected value
* @param {string} [msg] message
*/
function deepEqual( actual, expected, msg ) {
/* eslint-disable no-invalid-this */
this.comment( 'actual: '+actual+'. expected: '+expected+'. msg: '+msg+'.' );
// TODO: implement
}
// EXPORTS //
module.exports = deepEqual;
},{}],185:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var nextTick = require( './../utils/next_tick.js' );
// MAIN //
/**
* Ends a benchmark.
*
* @private
*/
function end() {
/* eslint-disable no-invalid-this */
var self = this;
if ( this._ended ) {
this.fail( '.end() called more than once' );
} else {
// Prevents releasing the zalgo when running synchronous benchmarks.
nextTick( onTick );
}
this._ended = true;
this._running = false;
/**
* Callback invoked upon a subsequent tick of the event loop.
*
* @private
*/
function onTick() {
self.emit( 'end' );
}
}
// EXPORTS //
module.exports = end;
},{"./../utils/next_tick.js":222}],186:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Returns a `boolean` indicating if a benchmark has ended.
*
* @private
* @returns {boolean} boolean indicating if a benchmark has ended
*/
function ended() {
/* eslint-disable no-invalid-this */
return this._ended;
}
// EXPORTS //
module.exports = ended;
},{}],187:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Asserts that `actual` is strictly equal to `expected`.
*
* @private
* @param {*} actual - actual value
* @param {*} expected - expected value
* @param {string} [msg] - message
*/
function equal( actual, expected, msg ) {
/* eslint-disable no-invalid-this */
this._assert( actual === expected, {
'message': msg || 'should be equal',
'operator': 'equal',
'expected': expected,
'actual': actual
});
}
// EXPORTS //
module.exports = equal;
},{}],188:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Forcefully ends a benchmark.
*
* @private
* @returns {void}
*/
function exit() {
/* eslint-disable no-invalid-this */
if ( this._exited ) {
// If we have already "exited", do not create more failing assertions when one should suffice...
return;
}
// Only "exit" when a benchmark has either not yet been run or is currently running. If a benchmark has already ended, no need to generate a failing assertion.
if ( !this._ended ) {
this._exited = true;
this.fail( 'benchmark exited without ending' );
// Allow running benchmarks to call `end` on their own...
if ( !this._running ) {
this.end();
}
}
}
// EXPORTS //
module.exports = exit;
},{}],189:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Generates a failing assertion.
*
* @private
* @param {string} msg - message
*/
function fail( msg ) {
/* eslint-disable no-invalid-this */
this._assert( false, {
'message': msg,
'operator': 'fail'
});
}
// EXPORTS //
module.exports = fail;
},{}],190:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var EventEmitter = require( 'events' ).EventEmitter;
var inherit = require( '@stdlib/utils/inherit' );
var defineProperty = require( '@stdlib/utils/define-property' );
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var tic = require( '@stdlib/time/tic' );
var toc = require( '@stdlib/time/toc' );
var run = require( './run.js' );
var exit = require( './exit.js' );
var ended = require( './ended.js' );
var assert = require( './assert.js' );
var comment = require( './comment.js' );
var skip = require( './skip.js' );
var todo = require( './todo.js' );
var fail = require( './fail.js' );
var pass = require( './pass.js' );
var ok = require( './ok.js' );
var notOk = require( './not_ok.js' );
var equal = require( './equal.js' );
var notEqual = require( './not_equal.js' );
var deepEqual = require( './deep_equal.js' );
var notDeepEqual = require( './not_deep_equal.js' );
var end = require( './end.js' );
// MAIN //
/**
* Benchmark constructor.
*
* @constructor
* @param {string} name - benchmark name
* @param {Options} opts - benchmark options
* @param {boolean} opts.skip - boolean indicating whether to skip a benchmark
* @param {PositiveInteger} opts.iterations - number of iterations
* @param {PositiveInteger} opts.timeout - number of milliseconds before a benchmark automatically fails
* @param {Function} [benchmark] - function containing benchmark code
* @returns {Benchmark} Benchmark instance
*
* @example
* var bench = new Benchmark( 'beep', function benchmark( b ) {
* var x;
* var i;
* b.comment( 'Running benchmarks...' );
* b.tic();
* for ( i = 0; i < b.iterations; i++ ) {
* x = Math.sin( Math.random() );
* if ( x !== x ) {
* b.ok( false, 'should not return NaN' );
* }
* }
* b.toc();
* if ( x !== x ) {
* b.ok( false, 'should not return NaN' );
* }
* b.comment( 'Finished running benchmarks.' );
* b.end();
* });
*/
function Benchmark( name, opts, benchmark ) {
var hasTicked;
var hasTocked;
var self;
var time;
if ( !( this instanceof Benchmark ) ) {
return new Benchmark( name, opts, benchmark );
}
self = this;
hasTicked = false;
hasTocked = false;
EventEmitter.call( this );
// Private properties:
setReadOnly( this, '_benchmark', benchmark );
setReadOnly( this, '_skip', opts.skip );
defineProperty( this, '_ended', {
'configurable': false,
'enumerable': false,
'writable': true,
'value': false
});
defineProperty( this, '_running', {
'configurable': false,
'enumerable': false,
'writable': true,
'value': false
});
defineProperty( this, '_exited', {
'configurable': false,
'enumerable': false,
'writable': true,
'value': false
});
defineProperty( this, '_count', {
'configurable': false,
'enumerable': false,
'writable': true,
'value': 0
});
// Read-only:
setReadOnly( this, 'name', name );
setReadOnly( this, 'tic', start );
setReadOnly( this, 'toc', stop );
setReadOnly( this, 'iterations', opts.iterations );
setReadOnly( this, 'timeout', opts.timeout );
return this;
/**
* Starts a benchmark timer.
*
* ## Notes
*
* - Using a scoped variable prevents nefarious mutation by bad actors hoping to manipulate benchmark results.
* - The one attack vector which remains is manipulation of the `require` cache for `tic` and `toc`.
* - One way to combat cache manipulation is by comparing the checksum of `Function#toString()` against known values.
*
* @private
*/
function start() {
if ( hasTicked ) {
self.fail( '.tic() called more than once' );
} else {
self.emit( 'tic' );
hasTicked = true;
time = tic();
}
}
/**
* Stops a benchmark timer.
*
* @private
* @returns {void}
*/
function stop() {
var elapsed;
var secs;
var rate;
var out;
if ( hasTicked === false ) {
return self.fail( '.toc() called before .tic()' );
}
elapsed = toc( time );
if ( hasTocked ) {
return self.fail( '.toc() called more than once' );
}
hasTocked = true;
self.emit( 'toc' );
secs = elapsed[ 0 ] + ( elapsed[ 1 ]/1e9 );
rate = self.iterations / secs;
out = {
'ok': true,
'operator': 'result',
'iterations': self.iterations,
'elapsed': secs,
'rate': rate
};
self.emit( 'result', out );
}
}
/*
* Inherit from the `EventEmitter` prototype.
*/
inherit( Benchmark, EventEmitter );
/**
* Runs a benchmark.
*
* @private
* @name run
* @memberof Benchmark.prototype
* @type {Function}
*/
setReadOnly( Benchmark.prototype, 'run', run );
/**
* Forcefully ends a benchmark.
*
* @private
* @name exit
* @memberof Benchmark.prototype
* @type {Function}
*/
setReadOnly( Benchmark.prototype, 'exit', exit );
/**
* Returns a `boolean` indicating if a benchmark has ended.
*
* @private
* @name ended
* @memberof Benchmark.prototype
* @type {Function}
* @returns {boolean} boolean indicating if a benchmark has ended
*/
setReadOnly( Benchmark.prototype, 'ended', ended );
/**
* Generates an assertion.
*
* @private
* @name _assert
* @memberof Benchmark.prototype
* @type {Function}
* @param {boolean} ok - assertion outcome
* @param {Options} opts - options
*/
setReadOnly( Benchmark.prototype, '_assert', assert );
/**
* Writes a comment.
*
* @name comment
* @memberof Benchmark.prototype
* @type {Function}
* @param {string} msg - comment message
*/
setReadOnly( Benchmark.prototype, 'comment', comment );
/**
* Generates an assertion which will be skipped.
*
* @name skip
* @memberof Benchmark.prototype
* @type {Function}
* @param {*} value - value
* @param {string} msg - message
*/
setReadOnly( Benchmark.prototype, 'skip', skip );
/**
* Generates an assertion which should be implemented.
*
* @name todo
* @memberof Benchmark.prototype
* @type {Function}
* @param {*} value - value
* @param {string} msg - message
*/
setReadOnly( Benchmark.prototype, 'todo', todo );
/**
* Generates a failing assertion.
*
* @name fail
* @memberof Benchmark.prototype
* @type {Function}
* @param {string} msg - message
*/
setReadOnly( Benchmark.prototype, 'fail', fail );
/**
* Generates a passing assertion.
*
* @name pass
* @memberof Benchmark.prototype
* @type {Function}
* @param {string} msg - message
*/
setReadOnly( Benchmark.prototype, 'pass', pass );
/**
* Asserts that a `value` is truthy.
*
* @name ok
* @memberof Benchmark.prototype
* @type {Function}
* @param {*} value - value
* @param {string} [msg] - message
*/
setReadOnly( Benchmark.prototype, 'ok', ok );
/**
* Asserts that a `value` is falsy.
*
* @name notOk
* @memberof Benchmark.prototype
* @type {Function}
* @param {*} value - value
* @param {string} [msg] - message
*/
setReadOnly( Benchmark.prototype, 'notOk', notOk );
/**
* Asserts that `actual` is strictly equal to `expected`.
*
* @name equal
* @memberof Benchmark.prototype
* @type {Function}
* @param {*} actual - actual value
* @param {*} expected - expected value
* @param {string} [msg] - message
*/
setReadOnly( Benchmark.prototype, 'equal', equal );
/**
* Asserts that `actual` is not strictly equal to `expected`.
*
* @name notEqual
* @memberof Benchmark.prototype
* @type {Function}
* @param {*} actual - actual value
* @param {*} expected - expected value
* @param {string} [msg] - message
*/
setReadOnly( Benchmark.prototype, 'notEqual', notEqual );
/**
* Asserts that `actual` is deeply equal to `expected`.
*
* @name deepEqual
* @memberof Benchmark.prototype
* @type {Function}
* @param {*} actual - actual value
* @param {*} expected - expected value
* @param {string} [msg] message
*/
setReadOnly( Benchmark.prototype, 'deepEqual', deepEqual );
/**
* Asserts that `actual` is not deeply equal to `expected`.
*
* @name notDeepEqual
* @memberof Benchmark.prototype
* @type {Function}
* @param {*} actual - actual value
* @param {*} expected - expected value
* @param {string} [msg] message
*/
setReadOnly( Benchmark.prototype, 'notDeepEqual', notDeepEqual );
/**
* Ends a benchmark.
*
* @name end
* @memberof Benchmark.prototype
* @type {Function}
*/
setReadOnly( Benchmark.prototype, 'end', end );
// EXPORTS //
module.exports = Benchmark;
},{"./assert.js":181,"./comment.js":183,"./deep_equal.js":184,"./end.js":185,"./ended.js":186,"./equal.js":187,"./exit.js":188,"./fail.js":189,"./not_deep_equal.js":191,"./not_equal.js":192,"./not_ok.js":193,"./ok.js":194,"./pass.js":195,"./run.js":196,"./skip.js":198,"./todo.js":199,"@stdlib/time/tic":382,"@stdlib/time/toc":386,"@stdlib/utils/define-nonenumerable-read-only-property":396,"@stdlib/utils/define-property":403,"@stdlib/utils/inherit":424,"events":479}],191:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Asserts that `actual` is not deeply equal to `expected`.
*
* @private
* @param {*} actual - actual value
* @param {*} expected - expected value
* @param {string} [msg] message
*/
function notDeepEqual( actual, expected, msg ) {
/* eslint-disable no-invalid-this */
this.comment( 'actual: '+actual+'. expected: '+expected+'. msg: '+msg+'.' );
// TODO: implement
}
// EXPORTS //
module.exports = notDeepEqual;
},{}],192:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Asserts that `actual` is not strictly equal to `expected`.
*
* @private
* @param {*} actual - actual value
* @param {*} expected - expected value
* @param {string} [msg] - message
*/
function notEqual( actual, expected, msg ) {
/* eslint-disable no-invalid-this */
this._assert( actual !== expected, {
'message': msg || 'should not be equal',
'operator': 'notEqual',
'expected': expected,
'actual': actual
});
}
// EXPORTS //
module.exports = notEqual;
},{}],193:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Asserts that a `value` is falsy.
*
* @private
* @param {*} value - value
* @param {string} [msg] - message
*/
function notOk( value, msg ) {
/* eslint-disable no-invalid-this */
this._assert( !value, {
'message': msg || 'should be falsy',
'operator': 'notOk',
'expected': false,
'actual': value
});
}
// EXPORTS //
module.exports = notOk;
},{}],194:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Asserts that a `value` is truthy.
*
* @private
* @param {*} value - value
* @param {string} [msg] - message
*/
function ok( value, msg ) {
/* eslint-disable no-invalid-this */
this._assert( !!value, {
'message': msg || 'should be truthy',
'operator': 'ok',
'expected': true,
'actual': value
});
}
// EXPORTS //
module.exports = ok;
},{}],195:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Generates a passing assertion.
*
* @private
* @param {string} msg - message
*/
function pass( msg ) {
/* eslint-disable no-invalid-this */
this._assert( true, {
'message': msg,
'operator': 'pass'
});
}
// EXPORTS //
module.exports = pass;
},{}],196:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var timeout = require( './set_timeout.js' );
var clear = require( './clear_timeout.js' );
// MAIN //
/**
* Runs a benchmark.
*
* @private
* @returns {void}
*/
function run() {
/* eslint-disable no-invalid-this */
var self;
var id;
if ( this._skip ) {
this.comment( 'SKIP '+this.name );
return this.end();
}
if ( !this._benchmark ) {
this.comment( 'TODO '+this.name );
return this.end();
}
self = this;
this._running = true;
id = timeout( onTimeout, this.timeout );
this.once( 'end', endTimeout );
this.emit( 'prerun' );
this._benchmark( this );
this.emit( 'run' );
/**
* Callback invoked once a timeout ends.
*
* @private
*/
function onTimeout() {
self.fail( 'benchmark timed out after '+self.timeout+'ms' );
}
/**
* Clears a timeout.
*
* @private
*/
function endTimeout() {
clear( id );
}
}
// EXPORTS //
module.exports = run;
},{"./clear_timeout.js":182,"./set_timeout.js":197}],197:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// EXPORTS //
module.exports = setTimeout;
},{}],198:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Generates an assertion which will be skipped.
*
* @private
* @param {*} value - value
* @param {string} msg - message
*/
function skip( value, msg ) {
/* eslint-disable no-invalid-this */
this._assert( true, {
'message': msg,
'operator': 'skip',
'skip': true
});
}
// EXPORTS //
module.exports = skip;
},{}],199:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Generates an assertion which should be implemented.
*
* @private
* @param {*} value - value
* @param {string} msg - message
*/
function todo( value, msg ) {
/* eslint-disable no-invalid-this */
this._assert( !!value, {
'message': msg,
'operator': 'todo',
'todo': true
});
}
// EXPORTS //
module.exports = todo;
},{}],200:[function(require,module,exports){
module.exports={
"skip": false,
"iterations": null,
"repeats": 3,
"timeout": 300000
}
},{}],201:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isFunction = require( '@stdlib/assert/is-function' );
var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive;
var isObject = require( '@stdlib/assert/is-plain-object' );
var isNodeWritableStreamLike = require( '@stdlib/assert/is-node-writable-stream-like' );
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var pick = require( '@stdlib/utils/pick' );
var omit = require( '@stdlib/utils/omit' );
var noop = require( '@stdlib/utils/noop' );
var createHarness = require( './harness' );
var logStream = require( './log' );
var canEmitExit = require( './utils/can_emit_exit.js' );
var proc = require( './utils/process.js' );
// MAIN //
/**
* Creates a benchmark harness which supports closing when a process exits.
*
* @private
* @param {Options} [options] - function options
* @param {boolean} [options.autoclose] - boolean indicating whether to automatically close a harness after a harness finishes running all benchmarks
* @param {Stream} [options.stream] - output writable stream
* @param {Callback} [clbk] - callback to invoke when a harness finishes running all benchmarks
* @throws {TypeError} options argument must be an object
* @throws {TypeError} must provide valid options
* @throws {TypeError} callback argument must be a function
* @returns {Function} benchmark harness
*
* @example
* var proc = require( 'process' );
* var bench = createExitHarness( onFinish );
*
* function onFinish() {
* bench.close();
* }
*
* bench( 'beep', function benchmark( b ) {
* var x;
* var i;
* b.tic();
* for ( i = 0; i < b.iterations; i++ ) {
* x = Math.sin( Math.random() );
* if ( x !== x ) {
* b.ok( false, 'should not return NaN' );
* }
* }
* b.toc();
* if ( x !== x ) {
* b.ok( false, 'should not return NaN' );
* }
* b.end();
* });
*
* @example
* var stdout = require( '@stdlib/streams/node/stdout' );
*
* var stream = createExitHarness().createStream();
* stream.pipe( stdout );
*/
function createExitHarness() {
var exitCode;
var pipeline;
var harness;
var options;
var stream;
var topts;
var opts;
var clbk;
if ( arguments.length === 0 ) {
options = {};
clbk = noop;
} else if ( arguments.length === 1 ) {
if ( isFunction( arguments[ 0 ] ) ) {
options = {};
clbk = arguments[ 0 ];
} else if ( isObject( arguments[ 0 ] ) ) {
options = arguments[ 0 ];
clbk = noop;
} else {
throw new TypeError( 'invalid argument. Must provide either an options object or a callback function. Value: `'+arguments[ 0 ]+'`.' );
}
} else {
options = arguments[ 0 ];
if ( !isObject( options ) ) {
throw new TypeError( 'invalid argument. First argument must be an object. Value: `'+options+'`.' );
}
clbk = arguments[ 1 ];
if ( !isFunction( clbk ) ) {
throw new TypeError( 'invalid argument. Second argument must be a function. Value: `'+clbk+'`.' );
}
}
opts = {};
if ( hasOwnProp( options, 'autoclose' ) ) {
opts.autoclose = options.autoclose;
if ( !isBoolean( opts.autoclose ) ) {
throw new TypeError( 'invalid option. `autoclose` option must be a boolean primitive. Option: `'+opts.autoclose+'`.' );
}
}
if ( hasOwnProp( options, 'stream' ) ) {
opts.stream = options.stream;
if ( !isNodeWritableStreamLike( opts.stream ) ) {
throw new TypeError( 'invalid option. `stream` option must be a writable stream. Option: `'+opts.stream+'`.' );
}
}
exitCode = 0;
// Create a new harness:
topts = pick( opts, [ 'autoclose' ] );
harness = createHarness( topts, done );
// Create a results stream:
topts = omit( options, [ 'autoclose', 'stream' ] );
stream = harness.createStream( topts );
// Pipe results to an output stream:
pipeline = stream.pipe( opts.stream || logStream() );
// If a process can emit an 'exit' event, capture errors in order to set the exit code...
if ( canEmitExit ) {
pipeline.on( 'error', onError );
proc.on( 'exit', onExit );
}
return harness;
/**
* Callback invoked when a harness finishes.
*
* @private
* @returns {void}
*/
function done() {
return clbk();
}
/**
* Callback invoked upon a stream `error` event.
*
* @private
* @param {Error} error - error object
*/
function onError() {
exitCode = 1;
}
/**
* Callback invoked upon an `exit` event.
*
* @private
* @param {integer} code - exit code
*/
function onExit( code ) {
if ( code !== 0 ) {
// Allow the process to exit...
return;
}
harness.close();
proc.exit( exitCode || harness.exitCode );
}
}
// EXPORTS //
module.exports = createExitHarness;
},{"./harness":203,"./log":209,"./utils/can_emit_exit.js":220,"./utils/process.js":223,"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-boolean":81,"@stdlib/assert/is-function":102,"@stdlib/assert/is-node-writable-stream-like":124,"@stdlib/assert/is-plain-object":147,"@stdlib/utils/noop":452,"@stdlib/utils/omit":454,"@stdlib/utils/pick":456}],202:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var canEmitExit = require( './utils/can_emit_exit.js' );
var createExitHarness = require( './exit_harness.js' );
// VARIABLES //
var harness;
// MAIN //
/**
* Returns a benchmark harness. If a harness has already been created, returns the cached harness.
*
* @private
* @param {Options} [options] - harness options
* @param {Callback} [clbk] - callback to invoke when a harness finishes running all benchmarks
* @returns {Function} benchmark harness
*/
function getHarness( options, clbk ) {
var opts;
var cb;
if ( harness ) {
return harness;
}
if ( arguments.length > 1 ) {
opts = options;
cb = clbk;
} else {
opts = {};
cb = options;
}
opts.autoclose = !canEmitExit;
harness = createExitHarness( opts, cb );
// Update state:
getHarness.cached = true;
return harness;
}
// EXPORTS //
module.exports = getHarness;
},{"./exit_harness.js":201,"./utils/can_emit_exit.js":220}],203:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var setReadOnlyAccessor = require( '@stdlib/utils/define-nonenumerable-read-only-accessor' );
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var isFunction = require( '@stdlib/assert/is-function' );
var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive;
var isObject = require( '@stdlib/assert/is-plain-object' );
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var copy = require( '@stdlib/utils/copy' );
var Benchmark = require( './../benchmark-class' );
var Runner = require( './../runner' );
var nextTick = require( './../utils/next_tick.js' );
var DEFAULTS = require( './../defaults.json' );
var validate = require( './validate.js' );
var init = require( './init.js' );
// MAIN //
/**
* Creates a benchmark harness.
*
* @param {Options} [options] - function options
* @param {boolean} [options.autoclose] - boolean indicating whether to automatically close a harness after a harness finishes running all benchmarks
* @param {Callback} [clbk] - callback to invoke when a harness finishes running all benchmarks
* @throws {TypeError} options argument must be an object
* @throws {TypeError} must provide valid options
* @throws {TypeError} callback argument must be a function
* @returns {Function} benchmark harness
*
* @example
* var bench = createHarness( onFinish );
*
* function onFinish() {
* bench.close();
* console.log( 'Exit code: %d', bench.exitCode );
* }
*
* bench( 'beep', function benchmark( b ) {
* var x;
* var i;
* b.tic();
* for ( i = 0; i < b.iterations; i++ ) {
* x = Math.sin( Math.random() );
* if ( x !== x ) {
* b.ok( false, 'should not return NaN' );
* }
* }
* b.toc();
* if ( x !== x ) {
* b.ok( false, 'should not return NaN' );
* }
* b.end();
* });
*
* @example
* var stdout = require( '@stdlib/streams/node/stdout' );
*
* var stream = createHarness().createStream();
* stream.pipe( stdout );
*/
function createHarness( options, clbk ) {
var exitCode;
var runner;
var queue;
var opts;
var cb;
opts = {};
if ( arguments.length === 1 ) {
if ( isFunction( options ) ) {
cb = options;
} else if ( isObject( options ) ) {
opts = options;
} else {
throw new TypeError( 'invalid argument. Must provide either an options object or a callback function. Value: `'+options+'`.' );
}
} else if ( arguments.length > 1 ) {
if ( !isObject( options ) ) {
throw new TypeError( 'invalid argument. First argument must be an object. Value: `'+options+'`.' );
}
if ( hasOwnProp( options, 'autoclose' ) ) {
opts.autoclose = options.autoclose;
if ( !isBoolean( opts.autoclose ) ) {
throw new TypeError( 'invalid option. `autoclose` option must be a boolean primitive. Option: `'+opts.autoclose+'`.' );
}
}
cb = clbk;
if ( !isFunction( cb ) ) {
throw new TypeError( 'invalid argument. Second argument must be a function. Value: `'+cb+'`.' );
}
}
runner = new Runner();
if ( opts.autoclose ) {
runner.once( 'done', close );
}
if ( cb ) {
runner.once( 'done', cb );
}
exitCode = 0;
queue = [];
/**
* Benchmark harness.
*
* @private
* @param {string} name - benchmark name
* @param {Options} [options] - benchmark options
* @param {boolean} [options.skip=false] - boolean indicating whether to skip a benchmark
* @param {(PositiveInteger|null)} [options.iterations=null] - number of iterations
* @param {PositiveInteger} [options.repeats=3] - number of repeats
* @param {PositiveInteger} [options.timeout=300000] - number of milliseconds before a benchmark automatically fails
* @param {Function} [benchmark] - function containing benchmark code
* @throws {TypeError} first argument must be a string
* @throws {TypeError} options argument must be an object
* @throws {TypeError} must provide valid options
* @throws {TypeError} benchmark argument must a function
* @throws {Error} benchmark error
* @returns {Function} benchmark harness
*/
function harness( name, options, benchmark ) {
var opts;
var err;
var b;
if ( !isString( name ) ) {
throw new TypeError( 'invalid argument. First argument must be a string. Value: `'+name+'`.' );
}
opts = copy( DEFAULTS );
if ( arguments.length === 2 ) {
if ( isFunction( options ) ) {
b = options;
} else {
err = validate( opts, options );
if ( err ) {
throw err;
}
}
} else if ( arguments.length > 2 ) {
err = validate( opts, options );
if ( err ) {
throw err;
}
b = benchmark;
if ( !isFunction( b ) ) {
throw new TypeError( 'invalid argument. Third argument must be a function. Value: `'+b+'`.' );
}
}
// Add the benchmark to the initialization queue:
queue.push( [ name, opts, b ] );
// Perform initialization on the next turn of the event loop (note: this allows all benchmarks to be "registered" within the same turn of the loop; otherwise, we run the risk of registration-execution race conditions (i.e., a benchmark registers and executes before other benchmarks can register, depleting the benchmark queue and leading the harness to close)):
if ( queue.length === 1 ) {
nextTick( initialize );
}
return harness;
}
/**
* Initializes each benchmark.
*
* @private
* @returns {void}
*/
function initialize() {
var idx = -1;
return next();
/**
* Initialize the next benchmark.
*
* @private
* @returns {void}
*/
function next() {
var args;
idx += 1;
// If all benchmarks have been initialized, begin running the benchmarks:
if ( idx === queue.length ) {
queue.length = 0;
return runner.run();
}
// Initialize the next benchmark:
args = queue[ idx ];
init( args[ 0 ], args[ 1 ], args[ 2 ], onInit );
}
/**
* Callback invoked after performing initialization tasks.
*
* @private
* @param {string} name - benchmark name
* @param {Options} opts - benchmark options
* @param {(Function|undefined)} benchmark - function containing benchmark code
* @returns {void}
*/
function onInit( name, opts, benchmark ) {
var b;
var i;
// Create a `Benchmark` instance for each repeat to ensure each benchmark has its own state...
for ( i = 0; i < opts.repeats; i++ ) {
b = new Benchmark( name, opts, benchmark );
b.on( 'result', onResult );
runner.push( b );
}
return next();
}
}
/**
* Callback invoked upon a `result` event.
*
* @private
* @param {(string|Object)} result - result
*/
function onResult( result ) {
if (
!isString( result ) &&
!result.ok &&
!result.todo
) {
exitCode = 1;
}
}
/**
* Returns a results stream.
*
* @private
* @param {Object} [options] - options
* @returns {TransformStream} transform stream
*/
function createStream( options ) {
if ( arguments.length ) {
return runner.createStream( options );
}
return runner.createStream();
}
/**
* Closes a benchmark harness.
*
* @private
*/
function close() {
runner.close();
}
/**
* Forcefully exits a benchmark harness.
*
* @private
*/
function exit() {
runner.exit();
}
/**
* Returns the harness exit code.
*
* @private
* @returns {NonNegativeInteger} exit code
*/
function getExitCode() {
return exitCode;
}
setReadOnly( harness, 'createStream', createStream );
setReadOnly( harness, 'close', close );
setReadOnly( harness, 'exit', exit );
setReadOnlyAccessor( harness, 'exitCode', getExitCode );
return harness;
}
// EXPORTS //
module.exports = createHarness;
},{"./../benchmark-class":190,"./../defaults.json":200,"./../runner":217,"./../utils/next_tick.js":222,"./init.js":204,"./validate.js":207,"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-boolean":81,"@stdlib/assert/is-function":102,"@stdlib/assert/is-plain-object":147,"@stdlib/assert/is-string":158,"@stdlib/utils/copy":392,"@stdlib/utils/define-nonenumerable-read-only-accessor":394,"@stdlib/utils/define-nonenumerable-read-only-property":396}],204:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var pretest = require( './pretest.js' );
var iterations = require( './iterations.js' );
// MAIN //
/**
* Performs benchmark initialization tasks.
*
* @private
* @param {string} name - benchmark name
* @param {Options} opts - benchmark options
* @param {(Function|undefined)} benchmark - function containing benchmark code
* @param {Callback} clbk - callback to invoke after completing initialization tasks
* @returns {void}
*/
function init( name, opts, benchmark, clbk ) {
// If no benchmark function, then the benchmark is considered a "todo", so no need to repeat multiple times...
if ( !benchmark ) {
opts.repeats = 1;
return clbk( name, opts, benchmark );
}
// If the `skip` option to `true`, no need to initialize or repeat multiple times as will not be running the benchmark:
if ( opts.skip ) {
opts.repeats = 1;
return clbk( name, opts, benchmark );
}
// Perform pretests:
pretest( name, opts, benchmark, onPreTest );
/**
* Callback invoked upon completing pretests.
*
* @private
* @param {Error} [error] - error object
* @returns {void}
*/
function onPreTest( error ) {
// If the pretests failed, don't run the benchmark multiple times...
if ( error ) {
opts.repeats = 1;
opts.iterations = 1;
return clbk( name, opts, benchmark );
}
// If a user specified an iteration number, we can begin running benchmarks...
if ( opts.iterations ) {
return clbk( name, opts, benchmark );
}
// Determine iteration number:
iterations( name, opts, benchmark, onIterations );
}
/**
* Callback invoked upon determining an iteration number.
*
* @private
* @param {(Error|null)} error - error object
* @param {PositiveInteger} iter - number of iterations
* @returns {void}
*/
function onIterations( error, iter ) {
// If provided an error, then a benchmark failed, and, similar to pretests, don't run the benchmark multiple times...
if ( error ) {
opts.repeats = 1;
opts.iterations = 1;
return clbk( name, opts, benchmark );
}
opts.iterations = iter;
return clbk( name, opts, benchmark );
}
}
// EXPORTS //
module.exports = init;
},{"./iterations.js":205,"./pretest.js":206}],205:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var copy = require( '@stdlib/utils/copy' );
var Benchmark = require( './../benchmark-class' );
// VARIABLES //
var MIN_TIME = 0.1; // seconds
var ITERATIONS = 10; // 10^1
var MAX_ITERATIONS = 10000000000; // 10^10
// MAIN //
/**
* Determines the number of iterations.
*
* @private
* @param {string} name - benchmark name
* @param {Options} options - benchmark options
* @param {(Function|undefined)} benchmark - function containing benchmark code
* @param {Callback} clbk - callback to invoke after determining number of iterations
* @returns {void}
*/
function iterations( name, options, benchmark, clbk ) {
var opts;
var time;
// Elapsed time (in seconds):
time = 0;
// Create a local copy:
opts = copy( options );
opts.iterations = ITERATIONS;
// Begin running benchmarks:
return next();
/**
* Run a new benchmark.
*
* @private
*/
function next() {
var b = new Benchmark( name, opts, benchmark );
b.on( 'result', onResult );
b.once( 'end', onEnd );
b.run();
}
/**
* Callback invoked upon a `result` event.
*
* @private
* @param {(string|Object)} result - result
*/
function onResult( result ) {
if ( !isString( result ) && result.operator === 'result' ) {
time = result.elapsed;
}
}
/**
* Callback invoked upon an `end` event.
*
* @private
* @returns {void}
*/
function onEnd() {
if (
time < MIN_TIME &&
opts.iterations < MAX_ITERATIONS
) {
opts.iterations *= 10;
return next();
}
clbk( null, opts.iterations );
}
}
// EXPORTS //
module.exports = iterations;
},{"./../benchmark-class":190,"@stdlib/assert/is-string":158,"@stdlib/utils/copy":392}],206:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var copy = require( '@stdlib/utils/copy' );
var Benchmark = require( './../benchmark-class' );
// MAIN //
/**
* Runs pretests to sanity check and/or catch failures.
*
* @private
* @param {string} name - benchmark name
* @param {Options} options - benchmark options
* @param {(Function|undefined)} benchmark - function containing benchmark code
* @param {Callback} clbk - callback to invoke after completing pretests
*/
function pretest( name, options, benchmark, clbk ) {
var fail;
var opts;
var tic;
var toc;
var b;
// Counters to determine the number of `tic` and `toc` events:
tic = 0;
toc = 0;
// Local copy:
opts = copy( options );
opts.iterations = 1;
// Pretest to check for minimum requirements and/or errors...
b = new Benchmark( name, opts, benchmark );
b.on( 'result', onResult );
b.on( 'tic', onTic );
b.on( 'toc', onToc );
b.once( 'end', onEnd );
b.run();
/**
* Callback invoked upon a `result` event.
*
* @private
* @param {(string|Object)} result - result
*/
function onResult( result ) {
if (
!isString( result ) &&
!result.ok &&
!result.todo
) {
fail = true;
}
}
/**
* Callback invoked upon a `tic` event.
*
* @private
*/
function onTic() {
tic += 1;
}
/**
* Callback invoked upon a `toc` event.
*
* @private
*/
function onToc() {
toc += 1;
}
/**
* Callback invoked upon an `end` event.
*
* @private
* @returns {void}
*/
function onEnd() {
var err;
if ( fail ) {
// Possibility that failure is intermittent, but we will assume that the usual case is that the failure would persist across all repeats and no sense failing multiple times when once suffices.
err = new Error( 'benchmark failed' );
} else if ( tic !== 1 || toc !== 1 ) {
// Unable to do anything definitive with timing information (e.g., a tic with no toc or vice versa, or benchmark function calls neither tic nor toc).
err = new Error( 'invalid benchmark' );
}
if ( err ) {
return clbk( err );
}
return clbk();
}
}
// EXPORTS //
module.exports = pretest;
},{"./../benchmark-class":190,"@stdlib/assert/is-string":158,"@stdlib/utils/copy":392}],207:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isObject = require( '@stdlib/assert/is-plain-object' );
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive;
var isNull = require( '@stdlib/assert/is-null' );
var isPositiveInteger = require( '@stdlib/assert/is-positive-integer' ).isPrimitive;
// MAIN //
/**
* Validates function options.
*
* @private
* @param {Object} opts - destination object
* @param {Options} options - function options
* @param {boolean} [options.skip] - boolean indicating whether to skip a benchmark
* @param {(PositiveInteger|null)} [options.iterations] - number of iterations
* @param {PositiveInteger} [options.repeats] - number of repeats
* @param {PositiveInteger} [options.timeout] - number of milliseconds before a benchmark automatically fails
* @returns {(Error|null)} error object or null
*
* @example
* var opts = {};
* var options = {
* 'skip': false,
* 'iterations': 1e6,
* 'repeats': 3,
* 'timeout': 10000
* };
*
* var err = validate( opts, options );
* if ( err ) {
* throw err;
* }
*/
function validate( opts, options ) {
if ( !isObject( options ) ) {
return new TypeError( 'invalid argument. Options argument must be an object. Value: `' + options + '`.' );
}
if ( hasOwnProp( options, 'skip' ) ) {
opts.skip = options.skip;
if ( !isBoolean( opts.skip ) ) {
return new TypeError( 'invalid option. `skip` option must be a boolean primitive. Option: `' + opts.skip + '`.' );
}
}
if ( hasOwnProp( options, 'iterations' ) ) {
opts.iterations = options.iterations;
if (
!isPositiveInteger( opts.iterations ) &&
!isNull( opts.iterations )
) {
return new TypeError( 'invalid option. `iterations` option must be either a positive integer or `null`. Option: `' + opts.iterations + '`.' );
}
}
if ( hasOwnProp( options, 'repeats' ) ) {
opts.repeats = options.repeats;
if ( !isPositiveInteger( opts.repeats ) ) {
return new TypeError( 'invalid option. `repeats` option must be a positive integer. Option: `' + opts.repeats + '`.' );
}
}
if ( hasOwnProp( options, 'timeout' ) ) {
opts.timeout = options.timeout;
if ( !isPositiveInteger( opts.timeout ) ) {
return new TypeError( 'invalid option. `timeout` option must be a positive integer. Option: `' + opts.timeout + '`.' );
}
}
return null;
}
// EXPORTS //
module.exports = validate;
},{"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-boolean":81,"@stdlib/assert/is-null":135,"@stdlib/assert/is-plain-object":147,"@stdlib/assert/is-positive-integer":149}],208:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Benchmark harness.
*
* @module @stdlib/bench/harness
*
* @example
* var bench = require( '@stdlib/bench/harness' );
*
* bench( 'beep', function benchmark( b ) {
* var x;
* var i;
* b.tic();
* for ( i = 0; i < b.iterations; i++ ) {
* x = Math.sin( Math.random() );
* if ( x !== x ) {
* b.ok( false, 'should not return NaN' );
* }
* }
* b.toc();
* if ( x !== x ) {
* b.ok( false, 'should not return NaN' );
* }
* b.end();
* });
*/
// MODULES //
var bench = require( './bench.js' );
// EXPORTS //
module.exports = bench;
},{"./bench.js":180}],209:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var TransformStream = require( '@stdlib/streams/node/transform' );
var fromCodePoint = require( '@stdlib/string/from-code-point' );
var log = require( './log.js' );
// MAIN //
/**
* Returns a Transform stream for logging to the console.
*
* @private
* @returns {TransformStream} transform stream
*/
function createStream() {
var stream;
var line;
stream = new TransformStream({
'transform': transform,
'flush': flush
});
line = '';
return stream;
/**
* Callback invoked upon receiving a new chunk.
*
* @private
* @param {(Buffer|string)} chunk - chunk
* @param {string} enc - Buffer encoding
* @param {Callback} clbk - callback to invoke after transforming the streamed chunk
*/
function transform( chunk, enc, clbk ) {
var c;
var i;
for ( i = 0; i < chunk.length; i++ ) {
c = fromCodePoint( chunk[ i ] );
if ( c === '\n' ) {
flush();
} else {
line += c;
}
}
clbk();
}
/**
* Callback to flush data to `stdout`.
*
* @private
* @param {Callback} [clbk] - callback to invoke after processing data
* @returns {void}
*/
function flush( clbk ) {
try {
log( line );
} catch ( err ) {
stream.emit( 'error', err );
}
line = '';
if ( clbk ) {
return clbk();
}
}
}
// EXPORTS //
module.exports = createStream;
},{"./log.js":210,"@stdlib/streams/node/transform":372,"@stdlib/string/from-code-point":376}],210:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Writes a string to the console.
*
* @private
* @param {string} str - string to write
*/
function log( str ) {
console.log( str ); // eslint-disable-line no-console
}
// EXPORTS //
module.exports = log;
},{}],211:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Removes any pending benchmarks.
*
* @private
*/
function clear() {
/* eslint-disable no-invalid-this */
this._benchmarks.length = 0;
}
// EXPORTS //
module.exports = clear;
},{}],212:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Closes a benchmark runner.
*
* @private
* @returns {void}
*/
function closeRunner() {
/* eslint-disable no-invalid-this */
var self = this;
if ( this._closed ) {
return;
}
this._closed = true;
if ( this._benchmarks.length ) {
this.clear();
this._stream.write( '# WARNING: harness closed before completion.\n' );
} else {
this._stream.write( '#\n' );
this._stream.write( '1..'+this.total+'\n' );
this._stream.write( '# total '+this.total+'\n' );
this._stream.write( '# pass '+this.pass+'\n' );
if ( this.fail ) {
this._stream.write( '# fail '+this.fail+'\n' );
}
if ( this.skip ) {
this._stream.write( '# skip '+this.skip+'\n' );
}
if ( this.todo ) {
this._stream.write( '# todo '+this.todo+'\n' );
}
if ( !this.fail ) {
this._stream.write( '#\n# ok\n' );
}
}
this._stream.once( 'close', onClose );
this._stream.destroy();
/**
* Callback invoked upon a `close` event.
*
* @private
*/
function onClose() {
self.emit( 'close' );
}
}
// EXPORTS //
module.exports = closeRunner;
},{}],213:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
/* eslint-disable no-underscore-dangle */
'use strict';
// MODULES //
var TransformStream = require( '@stdlib/streams/node/transform' );
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var nextTick = require( './../utils/next_tick.js' );
// VARIABLES //
var TAP_HEADER = 'TAP version 13';
// MAIN //
/**
* Creates a results stream.
*
* @private
* @param {Options} [options] - stream options
* @throws {TypeError} options argument must be an object
* @throws {TypeError} must provide valid options
* @returns {TransformStream} transform stream
*/
function createStream( options ) {
/* eslint-disable no-invalid-this */
var stream;
var opts;
var self;
var id;
self = this;
if ( arguments.length ) {
opts = options;
} else {
opts = {};
}
stream = new TransformStream( opts );
if ( opts.objectMode ) {
id = 0;
this.on( '_push', onPush );
this.on( 'done', onDone );
} else {
stream.write( TAP_HEADER+'\n' );
this._stream.pipe( stream );
}
this.on( '_run', onRun );
return stream;
/**
* Runs the next benchmark.
*
* @private
*/
function next() {
nextTick( onTick );
}
/**
* Callback invoked upon the next tick.
*
* @private
* @returns {void}
*/
function onTick() {
var b = self._benchmarks.shift();
if ( b ) {
b.run();
if ( !b.ended() ) {
return b.once( 'end', next );
}
return next();
}
self._running = false;
self.emit( 'done' );
}
/**
* Callback invoked upon a run event.
*
* @private
* @returns {void}
*/
function onRun() {
if ( !self._running ) {
self._running = true;
return next();
}
}
/**
* Callback invoked upon a push event.
*
* @private
* @param {Benchmark} b - benchmark
*/
function onPush( b ) {
var bid = id;
id += 1;
b.once( 'prerun', onPreRun );
b.on( 'result', onResult );
b.on( 'end', onEnd );
/**
* Callback invoked upon a `prerun` event.
*
* @private
*/
function onPreRun() {
var row = {
'type': 'benchmark',
'name': b.name,
'id': bid
};
stream.write( row );
}
/**
* Callback invoked upon a `result` event.
*
* @private
* @param {(Object|string)} res - result
*/
function onResult( res ) {
if ( isString( res ) ) {
res = {
'benchmark': bid,
'type': 'comment',
'name': res
};
} else if ( res.operator === 'result' ) {
res.benchmark = bid;
res.type = 'result';
} else {
res.benchmark = bid;
res.type = 'assert';
}
stream.write( res );
}
/**
* Callback invoked upon an `end` event.
*
* @private
*/
function onEnd() {
stream.write({
'benchmark': bid,
'type': 'end'
});
}
}
/**
* Callback invoked upon a `done` event.
*
* @private
*/
function onDone() {
stream.destroy();
}
}
// EXPORTS //
module.exports = createStream;
},{"./../utils/next_tick.js":222,"@stdlib/assert/is-string":158,"@stdlib/streams/node/transform":372}],214:[function(require,module,exports){
/* eslint-disable stdlib/jsdoc-require-throws-tags */
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var replace = require( '@stdlib/string/replace' );
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var reEOL = require( '@stdlib/regexp/eol' );
// VARIABLES //
var RE_WHITESPACE = /\s+/g;
// MAIN //
/**
* Encodes an assertion.
*
* @private
* @param {Object} result - result
* @param {PositiveInteger} count - result count
* @returns {string} encoded assertion
*/
function encodeAssertion( result, count ) {
var actualStack;
var errorStack;
var expected;
var actual;
var indent;
var stack;
var lines;
var out;
var i;
out = '';
if ( !result.ok ) {
out += 'not ';
}
// Add result count:
out += 'ok ' + count;
// Add description:
if ( result.name ) {
out += ' ' + replace( result.name.toString(), RE_WHITESPACE, ' ' );
}
// Append directives:
if ( result.skip ) {
out += ' # SKIP';
} else if ( result.todo ) {
out += ' # TODO';
}
out += '\n';
if ( result.ok ) {
return out;
}
// Format diagnostics as YAML...
indent = ' ';
out += indent + '---\n';
out += indent + 'operator: ' + result.operator + '\n';
if (
hasOwnProp( result, 'actual' ) ||
hasOwnProp( result, 'expected' )
) {
// TODO: inspect object logic (https://github.com/substack/tape/blob/master/lib/results.js#L145)
expected = result.expected;
actual = result.actual;
if ( actual !== actual && expected !== expected ) {
throw new Error( 'TODO: remove me' );
}
}
if ( result.at ) {
out += indent + 'at: ' + result.at + '\n';
}
if ( result.actual ) {
actualStack = result.actual.stack;
}
if ( result.error ) {
errorStack = result.error.stack;
}
if ( actualStack ) {
stack = actualStack;
} else {
stack = errorStack;
}
if ( stack ) {
lines = stack.toString().split( reEOL.REGEXP );
out += indent + 'stack: |-\n';
for ( i = 0; i < lines.length; i++ ) {
out += indent + ' ' + lines[ i ] + '\n';
}
}
out += indent + '...\n';
return out;
}
// EXPORTS //
module.exports = encodeAssertion;
},{"@stdlib/assert/has-own-property":53,"@stdlib/regexp/eol":349,"@stdlib/string/replace":378}],215:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// VARIABLES //
var YAML_INDENT = ' ';
var YAML_BEGIN = YAML_INDENT + '---\n';
var YAML_END = YAML_INDENT + '...\n';
// MAIN //
/**
* Encodes a result as a YAML block.
*
* @private
* @param {Object} result - result
* @returns {string} encoded result
*/
function encodeResult( result ) {
var out = YAML_BEGIN;
out += YAML_INDENT + 'iterations: '+result.iterations+'\n';
out += YAML_INDENT + 'elapsed: '+result.elapsed+'\n';
out += YAML_INDENT + 'rate: '+result.rate+'\n';
out += YAML_END;
return out;
}
// EXPORTS //
module.exports = encodeResult;
},{}],216:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Forcefully exits a benchmark runner.
*
* @private
*/
function exit() {
/* eslint-disable no-invalid-this */
var self;
var i;
for ( i = 0; i < this._benchmarks.length; i++ ) {
this._benchmarks[ i ].exit();
}
self = this;
this.clear();
this._stream.once( 'close', onClose );
this._stream.destroy();
/**
* Callback invoked upon a `close` event.
*
* @private
*/
function onClose() {
self.emit( 'close' );
}
}
// EXPORTS //
module.exports = exit;
},{}],217:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var EventEmitter = require( 'events' ).EventEmitter;
var inherit = require( '@stdlib/utils/inherit' );
var defineProperty = require( '@stdlib/utils/define-property' );
var TransformStream = require( '@stdlib/streams/node/transform' );
var push = require( './push.js' );
var createStream = require( './create_stream.js' );
var run = require( './run.js' );
var clear = require( './clear.js' );
var close = require( './close.js' ); // eslint-disable-line stdlib/no-redeclare
var exit = require( './exit.js' );
// MAIN //
/**
* Benchmark runner.
*
* @private
* @constructor
* @returns {Runner} Runner instance
*
* @example
* var runner = new Runner();
*/
function Runner() {
if ( !( this instanceof Runner ) ) {
return new Runner();
}
EventEmitter.call( this );
// Private properties:
defineProperty( this, '_benchmarks', {
'value': [],
'configurable': false,
'writable': false,
'enumerable': false
});
defineProperty( this, '_stream', {
'value': new TransformStream(),
'configurable': false,
'writable': false,
'enumerable': false
});
defineProperty( this, '_closed', {
'value': false,
'configurable': false,
'writable': true,
'enumerable': false
});
defineProperty( this, '_running', {
'value': false,
'configurable': false,
'writable': true,
'enumerable': false
});
// Public properties:
defineProperty( this, 'total', {
'value': 0,
'configurable': false,
'writable': true,
'enumerable': true
});
defineProperty( this, 'fail', {
'value': 0,
'configurable': false,
'writable': true,
'enumerable': true
});
defineProperty( this, 'pass', {
'value': 0,
'configurable': false,
'writable': true,
'enumerable': true
});
defineProperty( this, 'skip', {
'value': 0,
'configurable': false,
'writable': true,
'enumerable': true
});
defineProperty( this, 'todo', {
'value': 0,
'configurable': false,
'writable': true,
'enumerable': true
});
return this;
}
/*
* Inherit from the `EventEmitter` prototype.
*/
inherit( Runner, EventEmitter );
/**
* Adds a new benchmark.
*
* @private
* @memberof Runner.prototype
* @function push
* @param {Benchmark} b - benchmark
*/
defineProperty( Runner.prototype, 'push', {
'value': push,
'configurable': false,
'writable': false,
'enumerable': false
});
/**
* Creates a results stream.
*
* @private
* @memberof Runner.prototype
* @function createStream
* @param {Options} [options] - stream options
* @returns {TransformStream} transform stream
*/
defineProperty( Runner.prototype, 'createStream', {
'value': createStream,
'configurable': false,
'writable': false,
'enumerable': false
});
/**
* Runs pending benchmarks.
*
* @private
* @memberof Runner.prototype
* @function run
*/
defineProperty( Runner.prototype, 'run', {
'value': run,
'configurable': false,
'writable': false,
'enumerable': false
});
/**
* Removes any pending benchmarks.
*
* @private
* @memberof Runner.prototype
* @function clear
*/
defineProperty( Runner.prototype, 'clear', {
'value': clear,
'configurable': false,
'writable': false,
'enumerable': false
});
/**
* Closes a benchmark runner.
*
* @private
* @memberof Runner.prototype
* @function close
*/
defineProperty( Runner.prototype, 'close', {
'value': close,
'configurable': false,
'writable': false,
'enumerable': false
});
/**
* Forcefully exits a benchmark runner.
*
* @private
* @memberof Runner.prototype
* @function exit
*/
defineProperty( Runner.prototype, 'exit', {
'value': exit,
'configurable': false,
'writable': false,
'enumerable': false
});
// EXPORTS //
module.exports = Runner;
},{"./clear.js":211,"./close.js":212,"./create_stream.js":213,"./exit.js":216,"./push.js":218,"./run.js":219,"@stdlib/streams/node/transform":372,"@stdlib/utils/define-property":403,"@stdlib/utils/inherit":424,"events":479}],218:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
/* eslint-disable no-underscore-dangle */
'use strict';
// MODULES //
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var encodeAssertion = require( './encode_assertion.js' );
var encodeResult = require( './encode_result.js' );
// MAIN //
/**
* Adds a new benchmark.
*
* @private
* @param {Benchmark} b - benchmark
*/
function push( b ) {
/* eslint-disable no-invalid-this */
var self = this;
this._benchmarks.push( b );
b.once( 'prerun', onPreRun );
b.on( 'result', onResult );
this.emit( '_push', b );
/**
* Callback invoked upon a `prerun` event.
*
* @private
*/
function onPreRun() {
self._stream.write( '# '+b.name+'\n' );
}
/**
* Callback invoked upon a `result` event.
*
* @private
* @param {(Object|string)} res - result
* @returns {void}
*/
function onResult( res ) {
// Check for a comment...
if ( isString( res ) ) {
return self._stream.write( '# '+res+'\n' );
}
if ( res.operator === 'result' ) {
res = encodeResult( res );
return self._stream.write( res );
}
self.total += 1;
if ( res.ok ) {
if ( res.skip ) {
self.skip += 1;
} else if ( res.todo ) {
self.todo += 1;
}
self.pass += 1;
}
// According to the TAP spec, todos pass even if not "ok"...
else if ( res.todo ) {
self.pass += 1;
self.todo += 1;
}
// Everything else is a failure...
else {
self.fail += 1;
}
res = encodeAssertion( res, self.total );
self._stream.write( res );
}
}
// EXPORTS //
module.exports = push;
},{"./encode_assertion.js":214,"./encode_result.js":215,"@stdlib/assert/is-string":158}],219:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Runs pending benchmarks.
*
* @private
*/
function run() {
/* eslint-disable no-invalid-this */
this.emit( '_run' );
}
// EXPORTS //
module.exports = run;
},{}],220:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var IS_BROWSER = require( '@stdlib/assert/is-browser' );
var canExit = require( './can_exit.js' );
// MAIN //
var bool = ( !IS_BROWSER && canExit );
// EXPORTS //
module.exports = bool;
},{"./can_exit.js":221,"@stdlib/assert/is-browser":87}],221:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var proc = require( './process.js' );
// MAIN //
var bool = ( proc && typeof proc.exit === 'function' );
// EXPORTS //
module.exports = bool;
},{"./process.js":223}],222:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Runs a function on a subsequent turn of the event loop.
*
* ## Notes
*
* - `process.nextTick` is only Node.js.
* - `setImmediate` is non-standard.
* - Everything else is browser based (e.g., mutation observer, requestAnimationFrame, etc).
* - Only API which is universal is `setTimeout`.
* - Note that `0` is not actually `0ms`. Browser environments commonly have a minimum delay of `4ms`. This is acceptable. Here, the main intent of this function is to give the runtime a chance to run garbage collection, clear state, and tend to any other pending tasks before returning control to benchmark tasks. The larger aim (attainable or not) is to provide each benchmark run with as much of a fresh state as possible.
*
*
* @private
* @param {Function} fcn - function to run upon a subsequent turn of the event loop
*/
function nextTick( fcn ) {
setTimeout( fcn, 0 );
}
// EXPORTS //
module.exports = nextTick;
},{}],223:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var proc = require( 'process' );
// EXPORTS //
module.exports = proc;
},{"process":491}],224:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Benchmark harness.
*
* @module @stdlib/bench
*
* @example
* var bench = require( '@stdlib/bench' );
*
* bench( 'beep', function benchmark( b ) {
* var x;
* var i;
* b.tic();
* for ( i = 0; i < b.iterations; i++ ) {
* x = Math.sin( Math.random() );
* if ( x !== x ) {
* b.ok( false, 'should not return NaN' );
* }
* }
* b.toc();
* if ( x !== x ) {
* b.ok( false, 'should not return NaN' );
* }
* b.end();
* });
*/
// MODULES //
var bench = require( '@stdlib/bench/harness' );
// EXPORTS //
module.exports = bench;
},{"@stdlib/bench/harness":208}],225:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* BLAS level 1 routine to copy values from `x` into `y`.
*
* @module @stdlib/blas/base/gcopy
*
* @example
* var gcopy = require( '@stdlib/blas/base/gcopy' );
*
* var x = [ 1.0, 2.0, 3.0, 4.0, 5.0 ];
* var y = [ 6.0, 7.0, 8.0, 9.0, 10.0 ];
*
* gcopy( x.length, x, 1, y, 1 );
* // y => [ 1.0, 2.0, 3.0, 4.0, 5.0 ]
*
* @example
* var gcopy = require( '@stdlib/blas/base/gcopy' );
*
* var x = [ 1.0, 2.0, 3.0, 4.0, 5.0 ];
* var y = [ 6.0, 7.0, 8.0, 9.0, 10.0 ];
*
* gcopy.ndarray( x.length, x, 1, 0, y, 1, 0 );
* // y => [ 1.0, 2.0, 3.0, 4.0, 5.0 ]
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var gcopy = require( './main.js' );
var ndarray = require( './ndarray.js' );
// MAIN //
setReadOnly( gcopy, 'ndarray', ndarray );
// EXPORTS //
module.exports = gcopy;
},{"./main.js":226,"./ndarray.js":227,"@stdlib/utils/define-nonenumerable-read-only-property":396}],226:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// VARIABLES //
var M = 8;
// MAIN //
/**
* Copies values from `x` into `y`.
*
* @param {PositiveInteger} N - number of values to copy
* @param {NumericArray} x - input array
* @param {integer} strideX - `x` stride length
* @param {NumericArray} y - destination array
* @param {integer} strideY - `y` stride length
* @returns {NumericArray} `y`
*
* @example
* var x = [ 1.0, 2.0, 3.0, 4.0, 5.0 ];
* var y = [ 6.0, 7.0, 8.0, 9.0, 10.0 ];
*
* gcopy( x.length, x, 1, y, 1 );
* // y => [ 1.0, 2.0, 3.0, 4.0, 5.0 ]
*/
function gcopy( N, x, strideX, y, strideY ) {
var ix;
var iy;
var m;
var i;
if ( N <= 0 ) {
return y;
}
// Use unrolled loops if both strides are equal to `1`...
if ( strideX === 1 && strideY === 1 ) {
m = N % M;
// If we have a remainder, run a clean-up loop...
if ( m > 0 ) {
for ( i = 0; i < m; i++ ) {
y[ i ] = x[ i ];
}
}
if ( N < M ) {
return y;
}
for ( i = m; i < N; i += M ) {
y[ i ] = x[ i ];
y[ i+1 ] = x[ i+1 ];
y[ i+2 ] = x[ i+2 ];
y[ i+3 ] = x[ i+3 ];
y[ i+4 ] = x[ i+4 ];
y[ i+5 ] = x[ i+5 ];
y[ i+6 ] = x[ i+6 ];
y[ i+7 ] = x[ i+7 ];
}
return y;
}
if ( strideX < 0 ) {
ix = (1-N) * strideX;
} else {
ix = 0;
}
if ( strideY < 0 ) {
iy = (1-N) * strideY;
} else {
iy = 0;
}
for ( i = 0; i < N; i++ ) {
y[ iy ] = x[ ix ];
ix += strideX;
iy += strideY;
}
return y;
}
// EXPORTS //
module.exports = gcopy;
},{}],227:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// VARIABLES //
var M = 8;
// MAIN //
/**
* Copies values from `x` into `y`.
*
* @param {PositiveInteger} N - number of values to copy
* @param {NumericArray} x - input array
* @param {integer} strideX - `x` stride length
* @param {NonNegativeInteger} offsetX - starting `x` index
* @param {NumericArray} y - destination array
* @param {integer} strideY - `y` stride length
* @param {NonNegativeInteger} offsetY - starting `y` index
* @returns {NumericArray} `y`
*
* @example
* var x = [ 1.0, 2.0, 3.0, 4.0, 5.0 ];
* var y = [ 6.0, 7.0, 8.0, 9.0, 10.0 ];
*
* gcopy( x.length, x, 1, 0, y, 1, 0 );
* // y => [ 1.0, 2.0, 3.0, 4.0, 5.0 ]
*/
function gcopy( N, x, strideX, offsetX, y, strideY, offsetY ) {
var ix;
var iy;
var m;
var i;
if ( N <= 0 ) {
return y;
}
ix = offsetX;
iy = offsetY;
// Use unrolled loops if both strides are equal to `1`...
if ( strideX === 1 && strideY === 1 ) {
m = N % M;
// If we have a remainder, run a clean-up loop...
if ( m > 0 ) {
for ( i = 0; i < m; i++ ) {
y[ iy ] = x[ ix ];
ix += strideX;
iy += strideY;
}
}
if ( N < M ) {
return y;
}
for ( i = m; i < N; i += M ) {
y[ iy ] = x[ ix ];
y[ iy+1 ] = x[ ix+1 ];
y[ iy+2 ] = x[ ix+2 ];
y[ iy+3 ] = x[ ix+3 ];
y[ iy+4 ] = x[ ix+4 ];
y[ iy+5 ] = x[ ix+5 ];
y[ iy+6 ] = x[ ix+6 ];
y[ iy+7 ] = x[ ix+7 ];
ix += M;
iy += M;
}
return y;
}
for ( i = 0; i < N; i++ ) {
y[ iy ] = x[ ix ];
ix += strideX;
iy += strideY;
}
return y;
}
// EXPORTS //
module.exports = gcopy;
},{}],228:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var ctor = require( 'buffer' ).Buffer; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = ctor;
},{"buffer":481}],229:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Buffer constructor.
*
* @module @stdlib/buffer/ctor
*
* @example
* var ctor = require( '@stdlib/buffer/ctor' );
*
* var b = new ctor( [ 1, 2, 3, 4 ] );
* // returns <Buffer>
*/
// MODULES //
var hasNodeBufferSupport = require( '@stdlib/assert/has-node-buffer-support' );
var main = require( './buffer.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var ctor;
if ( hasNodeBufferSupport() ) {
ctor = main;
} else {
ctor = polyfill;
}
// EXPORTS //
module.exports = ctor;
},{"./buffer.js":228,"./polyfill.js":230,"@stdlib/assert/has-node-buffer-support":51}],230:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// TODO: write (browser) polyfill
// MAIN //
/**
* Buffer constructor.
*
* @throws {Error} not implemented
*/
function polyfill() {
throw new Error( 'not implemented' );
}
// EXPORTS //
module.exports = polyfill;
},{}],231:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isFunction = require( '@stdlib/assert/is-function' );
var Buffer = require( '@stdlib/buffer/ctor' );
// MAIN //
var bool = isFunction( Buffer.from );
// EXPORTS //
module.exports = bool;
},{"@stdlib/assert/is-function":102,"@stdlib/buffer/ctor":229}],232:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Copy buffer data to a new `Buffer` instance.
*
* @module @stdlib/buffer/from-buffer
*
* @example
* var fromArray = require( '@stdlib/buffer/from-array' );
* var copyBuffer = require( '@stdlib/buffer/from-buffer' );
*
* var b1 = fromArray( [ 1, 2, 3, 4 ] );
* // returns <Buffer>
*
* var b2 = copyBuffer( b1 );
* // returns <Buffer>
*/
// MODULES //
var hasFrom = require( './has_from.js' );
var main = require( './main.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var copyBuffer;
if ( hasFrom ) {
copyBuffer = main;
} else {
copyBuffer = polyfill;
}
// EXPORTS //
module.exports = copyBuffer;
},{"./has_from.js":231,"./main.js":233,"./polyfill.js":234}],233:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isBuffer = require( '@stdlib/assert/is-buffer' );
var Buffer = require( '@stdlib/buffer/ctor' );
// MAIN //
/**
* Copies buffer data to a new `Buffer` instance.
*
* @param {Buffer} buffer - buffer from which to copy
* @throws {TypeError} must provide a `Buffer` instance
* @returns {Buffer} new `Buffer` instance
*
* @example
* var fromArray = require( '@stdlib/buffer/from-array' );
*
* var b1 = fromArray( [ 1, 2, 3, 4 ] );
* // returns <Buffer>
*
* var b2 = fromBuffer( b1 );
* // returns <Buffer>
*/
function fromBuffer( buffer ) {
if ( !isBuffer( buffer ) ) {
throw new TypeError( 'invalid argument. Must provide a Buffer. Value: `' + buffer + '`' );
}
return Buffer.from( buffer );
}
// EXPORTS //
module.exports = fromBuffer;
},{"@stdlib/assert/is-buffer":88,"@stdlib/buffer/ctor":229}],234:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isBuffer = require( '@stdlib/assert/is-buffer' );
var Buffer = require( '@stdlib/buffer/ctor' );
// MAIN //
/**
* Copies buffer data to a new `Buffer` instance.
*
* @param {Buffer} buffer - buffer from which to copy
* @throws {TypeError} must provide a `Buffer` instance
* @returns {Buffer} new `Buffer` instance
*
* @example
* var fromArray = require( '@stdlib/buffer/from-array' );
*
* var b1 = fromArray( [ 1, 2, 3, 4 ] );
* // returns <Buffer>
*
* var b2 = fromBuffer( b1 );
* // returns <Buffer>
*/
function fromBuffer( buffer ) {
if ( !isBuffer( buffer ) ) {
throw new TypeError( 'invalid argument. Must provide a Buffer. Value: `' + buffer + '`' );
}
return new Buffer( buffer ); // eslint-disable-line no-buffer-constructor
}
// EXPORTS //
module.exports = fromBuffer;
},{"@stdlib/assert/is-buffer":88,"@stdlib/buffer/ctor":229}],235:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Maximum length of a generic array.
*
* @module @stdlib/constants/array/max-array-length
*
* @example
* var MAX_ARRAY_LENGTH = require( '@stdlib/constants/array/max-array-length' );
* // returns 4294967295
*/
// MAIN //
/**
* Maximum length of a generic array.
*
* ```tex
* 2^{32} - 1
* ```
*
* @constant
* @type {uinteger32}
* @default 4294967295
*/
var MAX_ARRAY_LENGTH = 4294967295>>>0; // asm type annotation
// EXPORTS //
module.exports = MAX_ARRAY_LENGTH;
},{}],236:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Maximum length of a typed array.
*
* @module @stdlib/constants/array/max-typed-array-length
*
* @example
* var MAX_TYPED_ARRAY_LENGTH = require( '@stdlib/constants/array/max-typed-array-length' );
* // returns 9007199254740991
*/
// MAIN //
/**
* Maximum length of a typed array.
*
* ```tex
* 2^{53} - 1
* ```
*
* @constant
* @type {number}
* @default 9007199254740991
*/
var MAX_TYPED_ARRAY_LENGTH = 9007199254740991;
// EXPORTS //
module.exports = MAX_TYPED_ARRAY_LENGTH;
},{}],237:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* The bias of a double-precision floating-point number's exponent.
*
* @module @stdlib/constants/float64/exponent-bias
* @type {integer32}
*
* @example
* var FLOAT64_EXPONENT_BIAS = require( '@stdlib/constants/float64/exponent-bias' );
* // returns 1023
*/
// MAIN //
/**
* Bias of a double-precision floating-point number's exponent.
*
* ## Notes
*
* The bias can be computed via
*
* ```tex
* \mathrm{bias} = 2^{k-1} - 1
* ```
*
* where \\(k\\) is the number of bits in the exponent; here, \\(k = 11\\).
*
* @constant
* @type {integer32}
* @default 1023
* @see [IEEE 754]{@link https://en.wikipedia.org/wiki/IEEE_754-1985}
*/
var FLOAT64_EXPONENT_BIAS = 1023|0; // asm type annotation
// EXPORTS //
module.exports = FLOAT64_EXPONENT_BIAS;
},{}],238:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* High word mask for the exponent of a double-precision floating-point number.
*
* @module @stdlib/constants/float64/high-word-exponent-mask
* @type {uinteger32}
*
* @example
* var FLOAT64_HIGH_WORD_EXPONENT_MASK = require( '@stdlib/constants/float64/high-word-exponent-mask' );
* // returns 2146435072
*/
// MAIN //
/**
* High word mask for the exponent of a double-precision floating-point number.
*
* ## Notes
*
* The high word mask for the exponent of a double-precision floating-point number is an unsigned 32-bit integer with the value \\( 2146435072 \\), which corresponds to the bit sequence
*
* ```binarystring
* 0 11111111111 00000000000000000000
* ```
*
* @constant
* @type {uinteger32}
* @default 0x7ff00000
* @see [IEEE 754]{@link https://en.wikipedia.org/wiki/IEEE_754-1985}
*/
var FLOAT64_HIGH_WORD_EXPONENT_MASK = 0x7ff00000;
// EXPORTS //
module.exports = FLOAT64_HIGH_WORD_EXPONENT_MASK;
},{}],239:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* High word mask for the significand of a double-precision floating-point number.
*
* @module @stdlib/constants/float64/high-word-significand-mask
* @type {uinteger32}
*
* @example
* var FLOAT64_HIGH_WORD_SIGNIFICAND_MASK = require( '@stdlib/constants/float64/high-word-significand-mask' );
* // returns 1048575
*/
// MAIN //
/**
* High word mask for the significand of a double-precision floating-point number.
*
* ## Notes
*
* The high word mask for the significand of a double-precision floating-point number is an unsigned 32-bit integer with the value \\( 1048575 \\), which corresponds to the bit sequence
*
* ```binarystring
* 0 00000000000 11111111111111111111
* ```
*
* @constant
* @type {uinteger32}
* @default 0x000fffff
* @see [IEEE 754]{@link https://en.wikipedia.org/wiki/IEEE_754-1985}
*/
var FLOAT64_HIGH_WORD_SIGNIFICAND_MASK = 0x000fffff;
// EXPORTS //
module.exports = FLOAT64_HIGH_WORD_SIGNIFICAND_MASK;
},{}],240:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Natural logarithm of `2`.
*
* @module @stdlib/constants/float64/ln-two
* @type {number}
*
* @example
* var LN2 = require( '@stdlib/constants/float64/ln-two' );
* // returns 0.6931471805599453
*/
// MAIN //
/**
* Natural logarithm of `2`.
*
* ```tex
* \ln 2
* ```
*
* @constant
* @type {number}
* @default 0.6931471805599453
*/
var LN2 = 6.93147180559945309417232121458176568075500134360255254120680009493393621969694715605863326996418687542001481021e-01; // eslint-disable-line max-len
// EXPORTS //
module.exports = LN2;
},{}],241:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* The maximum biased base 2 exponent for a subnormal double-precision floating-point number.
*
* @module @stdlib/constants/float64/max-base2-exponent-subnormal
* @type {integer32}
*
* @example
* var FLOAT64_MAX_BASE2_EXPONENT_SUBNORMAL = require( '@stdlib/constants/float64/max-base2-exponent-subnormal' );
* // returns -1023
*/
// MAIN //
/**
* The maximum biased base 2 exponent for a subnormal double-precision floating-point number.
*
* ```text
* 00000000000 => 0 - BIAS = -1023
* ```
*
* where `BIAS = 1023`.
*
* @constant
* @type {integer32}
* @default -1023
* @see [IEEE 754]{@link https://en.wikipedia.org/wiki/IEEE_754-1985}
*/
var FLOAT64_MAX_BASE2_EXPONENT_SUBNORMAL = -1023|0; // asm type annotation
// EXPORTS //
module.exports = FLOAT64_MAX_BASE2_EXPONENT_SUBNORMAL;
},{}],242:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* The maximum biased base 2 exponent for a double-precision floating-point number.
*
* @module @stdlib/constants/float64/max-base2-exponent
* @type {integer32}
*
* @example
* var FLOAT64_MAX_BASE2_EXPONENT = require( '@stdlib/constants/float64/max-base2-exponent' );
* // returns 1023
*/
// MAIN //
/**
* The maximum biased base 2 exponent for a double-precision floating-point number.
*
* ```text
* 11111111110 => 2046 - BIAS = 1023
* ```
*
* where `BIAS = 1023`.
*
* @constant
* @type {integer32}
* @default 1023
* @see [IEEE 754]{@link https://en.wikipedia.org/wiki/IEEE_754-1985}
*/
var FLOAT64_MAX_BASE2_EXPONENT = 1023|0; // asm type annotation
// EXPORTS //
module.exports = FLOAT64_MAX_BASE2_EXPONENT;
},{}],243:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Maximum safe double-precision floating-point integer.
*
* @module @stdlib/constants/float64/max-safe-integer
* @type {number}
*
* @example
* var FLOAT64_MAX_SAFE_INTEGER = require( '@stdlib/constants/float64/max-safe-integer' );
* // returns 9007199254740991
*/
// MAIN //
/**
* Maximum safe double-precision floating-point integer.
*
* ## Notes
*
* The integer has the value
*
* ```tex
* 2^{53} - 1
* ```
*
* @constant
* @type {number}
* @default 9007199254740991
* @see [Safe Integers]{@link http://www.2ality.com/2013/10/safe-integers.html}
* @see [IEEE 754]{@link https://en.wikipedia.org/wiki/IEEE_754-1985}
*/
var FLOAT64_MAX_SAFE_INTEGER = 9007199254740991;
// EXPORTS //
module.exports = FLOAT64_MAX_SAFE_INTEGER;
},{}],244:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* The minimum biased base 2 exponent for a subnormal double-precision floating-point number.
*
* @module @stdlib/constants/float64/min-base2-exponent-subnormal
* @type {integer32}
*
* @example
* var FLOAT64_MIN_BASE2_EXPONENT_SUBNORMAL = require( '@stdlib/constants/float64/min-base2-exponent-subnormal' );
* // returns -1074
*/
// MAIN //
/**
* The minimum biased base 2 exponent for a subnormal double-precision floating-point number.
*
* ```text
* -(BIAS+(52-1)) = -(1023+51) = -1074
* ```
*
* where `BIAS = 1023` and `52` is the number of digits in the significand.
*
* @constant
* @type {integer32}
* @default -1074
* @see [IEEE 754]{@link https://en.wikipedia.org/wiki/IEEE_754-1985}
*/
var FLOAT64_MIN_BASE2_EXPONENT_SUBNORMAL = -1074|0; // asm type annotation
// EXPORTS //
module.exports = FLOAT64_MIN_BASE2_EXPONENT_SUBNORMAL;
},{}],245:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Double-precision floating-point negative infinity.
*
* @module @stdlib/constants/float64/ninf
* @type {number}
*
* @example
* var FLOAT64_NINF = require( '@stdlib/constants/float64/ninf' );
* // returns -Infinity
*/
// MODULES //
var Number = require( '@stdlib/number/ctor' );
// MAIN //
/**
* Double-precision floating-point negative infinity.
*
* ## Notes
*
* Double-precision floating-point negative infinity has the bit sequence
*
* ```binarystring
* 1 11111111111 00000000000000000000 00000000000000000000000000000000
* ```
*
* @constant
* @type {number}
* @default Number.NEGATIVE_INFINITY
* @see [IEEE 754]{@link https://en.wikipedia.org/wiki/IEEE_754-1985}
*/
var FLOAT64_NINF = Number.NEGATIVE_INFINITY;
// EXPORTS //
module.exports = FLOAT64_NINF;
},{"@stdlib/number/ctor":303}],246:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Double-precision floating-point positive infinity.
*
* @module @stdlib/constants/float64/pinf
* @type {number}
*
* @example
* var FLOAT64_PINF = require( '@stdlib/constants/float64/pinf' );
* // returns Infinity
*/
// MAIN //
/**
* Double-precision floating-point positive infinity.
*
* ## Notes
*
* Double-precision floating-point positive infinity has the bit sequence
*
* ```binarystring
* 0 11111111111 00000000000000000000 00000000000000000000000000000000
* ```
*
* @constant
* @type {number}
* @default Number.POSITIVE_INFINITY
* @see [IEEE 754]{@link https://en.wikipedia.org/wiki/IEEE_754-1985}
*/
var FLOAT64_PINF = Number.POSITIVE_INFINITY; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = FLOAT64_PINF;
},{}],247:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Smallest positive double-precision floating-point normal number.
*
* @module @stdlib/constants/float64/smallest-normal
* @type {number}
*
* @example
* var FLOAT64_SMALLEST_NORMAL = require( '@stdlib/constants/float64/smallest-normal' );
* // returns 2.2250738585072014e-308
*/
// MAIN //
/**
* The smallest positive double-precision floating-point normal number.
*
* ## Notes
*
* The number has the value
*
* ```tex
* \frac{1}{2^{1023-1}}
* ```
*
* which corresponds to the bit sequence
*
* ```binarystring
* 0 00000000001 00000000000000000000 00000000000000000000000000000000
* ```
*
* @constant
* @type {number}
* @default 2.2250738585072014e-308
* @see [IEEE 754]{@link https://en.wikipedia.org/wiki/IEEE_754-1985}
*/
var FLOAT64_SMALLEST_NORMAL = 2.2250738585072014e-308;
// EXPORTS //
module.exports = FLOAT64_SMALLEST_NORMAL;
},{}],248:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Maximum signed 16-bit integer.
*
* @module @stdlib/constants/int16/max
* @type {integer32}
*
* @example
* var INT16_MAX = require( '@stdlib/constants/int16/max' );
* // returns 32767
*/
// MAIN //
/**
* Maximum signed 16-bit integer.
*
* ## Notes
*
* The number has the value
*
* ```tex
* 2^{15} - 1
* ```
*
* which corresponds to the bit sequence
*
* ```binarystring
* 0111111111111111
* ```
*
* @constant
* @type {integer32}
* @default 32767
*/
var INT16_MAX = 32767|0; // asm type annotation
// EXPORTS //
module.exports = INT16_MAX;
},{}],249:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Minimum signed 16-bit integer.
*
* @module @stdlib/constants/int16/min
* @type {integer32}
*
* @example
* var INT16_MIN = require( '@stdlib/constants/int16/min' );
* // returns -32768
*/
// MAIN //
/**
* Minimum signed 16-bit integer.
*
* ## Notes
*
* The number has the value
*
* ```tex
* -(2^{15})
* ```
*
* which corresponds to the two's complement bit sequence
*
* ```binarystring
* 1000000000000000
* ```
*
* @constant
* @type {integer32}
* @default -32768
*/
var INT16_MIN = -32768|0; // asm type annotation
// EXPORTS //
module.exports = INT16_MIN;
},{}],250:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Maximum signed 32-bit integer.
*
* @module @stdlib/constants/int32/max
* @type {integer32}
*
* @example
* var INT32_MAX = require( '@stdlib/constants/int32/max' );
* // returns 2147483647
*/
// MAIN //
/**
* Maximum signed 32-bit integer.
*
* ## Notes
*
* The number has the value
*
* ```tex
* 2^{31} - 1
* ```
*
* which corresponds to the bit sequence
*
* ```binarystring
* 01111111111111111111111111111111
* ```
*
* @constant
* @type {integer32}
* @default 2147483647
*/
var INT32_MAX = 2147483647|0; // asm type annotation
// EXPORTS //
module.exports = INT32_MAX;
},{}],251:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Minimum signed 32-bit integer.
*
* @module @stdlib/constants/int32/min
* @type {integer32}
*
* @example
* var INT32_MIN = require( '@stdlib/constants/int32/min' );
* // returns -2147483648
*/
// MAIN //
/**
* Minimum signed 32-bit integer.
*
* ## Notes
*
* The number has the value
*
* ```tex
* -(2^{31})
* ```
*
* which corresponds to the two's complement bit sequence
*
* ```binarystring
* 10000000000000000000000000000000
* ```
*
* @constant
* @type {integer32}
* @default -2147483648
*/
var INT32_MIN = -2147483648|0; // asm type annotation
// EXPORTS //
module.exports = INT32_MIN;
},{}],252:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Maximum signed 8-bit integer.
*
* @module @stdlib/constants/int8/max
* @type {integer32}
*
* @example
* var INT8_MAX = require( '@stdlib/constants/int8/max' );
* // returns 127
*/
// MAIN //
/**
* Maximum signed 8-bit integer.
*
* ## Notes
*
* The number is given by
*
* ```tex
* 2^{7} - 1
* ```
*
* which corresponds to the bit sequence
*
* ```binarystring
* 01111111
* ```
*
* @constant
* @type {integer32}
* @default 127
*/
var INT8_MAX = 127|0; // asm type annotation
// EXPORTS //
module.exports = INT8_MAX;
},{}],253:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Minimum signed 8-bit integer.
*
* @module @stdlib/constants/int8/min
* @type {integer32}
*
* @example
* var INT8_MIN = require( '@stdlib/constants/int8/min' );
* // returns -128
*/
// MAIN //
/**
* Minimum signed 8-bit integer.
*
* ## Notes
*
* The number is given by
*
* ```tex
* -(2^{7})
* ```
*
* which corresponds to the two's complement bit sequence
*
* ```binarystring
* 10000000
* ```
*
* @constant
* @type {integer32}
* @default -128
*/
var INT8_MIN = -128|0; // asm type annotation
// EXPORTS //
module.exports = INT8_MIN;
},{}],254:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Maximum unsigned 16-bit integer.
*
* @module @stdlib/constants/uint16/max
* @type {integer32}
*
* @example
* var UINT16_MAX = require( '@stdlib/constants/uint16/max' );
* // returns 65535
*/
// MAIN //
/**
* Maximum unsigned 16-bit integer.
*
* ## Notes
*
* The number has the value
*
* ```tex
* 2^{16} - 1
* ```
*
* which corresponds to the bit sequence
*
* ```binarystring
* 1111111111111111
* ```
*
* @constant
* @type {integer32}
* @default 65535
*/
var UINT16_MAX = 65535|0; // asm type annotation
// EXPORTS //
module.exports = UINT16_MAX;
},{}],255:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Maximum unsigned 32-bit integer.
*
* @module @stdlib/constants/uint32/max
* @type {uinteger32}
*
* @example
* var UINT32_MAX = require( '@stdlib/constants/uint32/max' );
* // returns 4294967295
*/
// MAIN //
/**
* Maximum unsigned 32-bit integer.
*
* ## Notes
*
* The number has the value
*
* ```tex
* 2^{32} - 1
* ```
*
* which corresponds to the bit sequence
*
* ```binarystring
* 11111111111111111111111111111111
* ```
*
* @constant
* @type {uinteger32}
* @default 4294967295
*/
var UINT32_MAX = 4294967295;
// EXPORTS //
module.exports = UINT32_MAX;
},{}],256:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Maximum unsigned 8-bit integer.
*
* @module @stdlib/constants/uint8/max
* @type {integer32}
*
* @example
* var UINT8_MAX = require( '@stdlib/constants/uint8/max' );
* // returns 255
*/
// MAIN //
/**
* Maximum unsigned 8-bit integer.
*
* ## Notes
*
* The number has the value
*
* ```tex
* 2^{8} - 1
* ```
*
* which corresponds to the bit sequence
*
* ```binarystring
* 11111111
* ```
*
* @constant
* @type {integer32}
* @default 255
*/
var UINT8_MAX = 255|0; // asm type annotation
// EXPORTS //
module.exports = UINT8_MAX;
},{}],257:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Maximum Unicode code point in the Basic Multilingual Plane (BMP).
*
* @module @stdlib/constants/unicode/max-bmp
* @type {integer32}
*
* @example
* var UNICODE_MAX_BMP = require( '@stdlib/constants/unicode/max-bmp' );
* // returns 65535
*/
// MAIN //
/**
* Maximum Unicode code point in the Basic Multilingual Plane (BMP).
*
* @constant
* @type {integer32}
* @default 65535
* @see [Unicode]{@link https://en.wikipedia.org/wiki/Unicode}
*/
var UNICODE_MAX_BMP = 0xFFFF|0; // asm type annotation
// EXPORTS //
module.exports = UNICODE_MAX_BMP;
},{}],258:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Maximum Unicode code point.
*
* @module @stdlib/constants/unicode/max
* @type {integer32}
*
* @example
* var UNICODE_MAX = require( '@stdlib/constants/unicode/max' );
* // returns 1114111
*/
// MAIN //
/**
* Maximum Unicode code point.
*
* @constant
* @type {integer32}
* @default 1114111
* @see [Unicode]{@link https://en.wikipedia.org/wiki/Unicode}
*/
var UNICODE_MAX = 0x10FFFF|0; // asm type annotation
// EXPORTS //
module.exports = UNICODE_MAX;
},{}],259:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a finite numeric value is an even number.
*
* @module @stdlib/math/base/assert/is-even
*
* @example
* var isEven = require( '@stdlib/math/base/assert/is-even' );
*
* var bool = isEven( 5.0 );
* // returns false
*
* bool = isEven( -2.0 );
* // returns true
*
* bool = isEven( 0.0 );
* // returns true
*
* bool = isEven( NaN );
* // returns false
*/
// MODULES //
var isEven = require( './is_even.js' );
// EXPORTS //
module.exports = isEven;
},{"./is_even.js":260}],260:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isInteger = require( '@stdlib/math/base/assert/is-integer' );
// MAIN //
/**
* Tests if a finite numeric value is an even number.
*
* @param {number} x - value to test
* @returns {boolean} boolean indicating whether the value is an even number
*
* @example
* var bool = isEven( 5.0 );
* // returns false
*
* @example
* var bool = isEven( -2.0 );
* // returns true
*
* @example
* var bool = isEven( 0.0 );
* // returns true
*
* @example
* var bool = isEven( NaN );
* // returns false
*/
function isEven( x ) {
return isInteger( x/2.0 );
}
// EXPORTS //
module.exports = isEven;
},{"@stdlib/math/base/assert/is-integer":263}],261:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a double-precision floating-point numeric value is infinite.
*
* @module @stdlib/math/base/assert/is-infinite
*
* @example
* var isInfinite = require( '@stdlib/math/base/assert/is-infinite' );
*
* var bool = isInfinite( Infinity );
* // returns true
*
* bool = isInfinite( -Infinity );
* // returns true
*
* bool = isInfinite( 5.0 );
* // returns false
*
* bool = isInfinite( NaN );
* // returns false
*/
// MODULES //
var isInfinite = require( './main.js' );
// EXPORTS //
module.exports = isInfinite;
},{"./main.js":262}],262:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var PINF = require( '@stdlib/constants/float64/pinf' );
var NINF = require( '@stdlib/constants/float64/ninf' );
// MAIN //
/**
* Tests if a double-precision floating-point numeric value is infinite.
*
* @param {number} x - value to test
* @returns {boolean} boolean indicating whether the value is infinite
*
* @example
* var bool = isInfinite( Infinity );
* // returns true
*
* @example
* var bool = isInfinite( -Infinity );
* // returns true
*
* @example
* var bool = isInfinite( 5.0 );
* // returns false
*
* @example
* var bool = isInfinite( NaN );
* // returns false
*/
function isInfinite( x ) {
return (x === PINF || x === NINF);
}
// EXPORTS //
module.exports = isInfinite;
},{"@stdlib/constants/float64/ninf":245,"@stdlib/constants/float64/pinf":246}],263:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a finite double-precision floating-point number is an integer.
*
* @module @stdlib/math/base/assert/is-integer
*
* @example
* var isInteger = require( '@stdlib/math/base/assert/is-integer' );
*
* var bool = isInteger( 1.0 );
* // returns true
*
* bool = isInteger( 3.14 );
* // returns false
*/
// MODULES //
var isInteger = require( './is_integer.js' );
// EXPORTS //
module.exports = isInteger;
},{"./is_integer.js":264}],264:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var floor = require( '@stdlib/math/base/special/floor' );
// MAIN //
/**
* Tests if a finite double-precision floating-point number is an integer.
*
* @param {number} x - value to test
* @returns {boolean} boolean indicating whether the value is an integer
*
* @example
* var bool = isInteger( 1.0 );
* // returns true
*
* @example
* var bool = isInteger( 3.14 );
* // returns false
*/
function isInteger( x ) {
return (floor(x) === x);
}
// EXPORTS //
module.exports = isInteger;
},{"@stdlib/math/base/special/floor":277}],265:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a double-precision floating-point numeric value is `NaN`.
*
* @module @stdlib/math/base/assert/is-nan
*
* @example
* var isnan = require( '@stdlib/math/base/assert/is-nan' );
*
* var bool = isnan( NaN );
* // returns true
*
* bool = isnan( 7.0 );
* // returns false
*/
// MODULES //
var isnan = require( './main.js' );
// EXPORTS //
module.exports = isnan;
},{"./main.js":266}],266:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Tests if a double-precision floating-point numeric value is `NaN`.
*
* @param {number} x - value to test
* @returns {boolean} boolean indicating whether the value is `NaN`
*
* @example
* var bool = isnan( NaN );
* // returns true
*
* @example
* var bool = isnan( 7.0 );
* // returns false
*/
function isnan( x ) {
return ( x !== x );
}
// EXPORTS //
module.exports = isnan;
},{}],267:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2020 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a single-precision floating-point numeric value is `NaN`.
*
* @module @stdlib/math/base/assert/is-nanf
*
* @example
* var isnanf = require( '@stdlib/math/base/assert/is-nanf' );
*
* var bool = isnanf( NaN );
* // returns true
*
* bool = isnanf( 7.0 );
* // returns false
*/
// MODULES //
var isnanf = require( './main.js' );
// EXPORTS //
module.exports = isnanf;
},{"./main.js":268}],268:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2020 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Tests if a single-precision floating-point numeric value is `NaN`.
*
* @param {number} x - value to test
* @returns {boolean} boolean indicating whether the value is `NaN`
*
* @example
* var bool = isnanf( NaN );
* // returns true
*
* @example
* var bool = isnanf( 7.0 );
* // returns false
*/
function isnanf( x ) {
return ( x !== x );
}
// EXPORTS //
module.exports = isnanf;
},{}],269:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a finite numeric value is an odd number.
*
* @module @stdlib/math/base/assert/is-odd
*
* @example
* var isOdd = require( '@stdlib/math/base/assert/is-odd' );
*
* var bool = isOdd( 5.0 );
* // returns true
*
* bool = isOdd( -2.0 );
* // returns false
*
* bool = isOdd( 0.0 );
* // returns false
*
* bool = isOdd( NaN );
* // returns false
*/
// MODULES //
var isOdd = require( './is_odd.js' );
// EXPORTS //
module.exports = isOdd;
},{"./is_odd.js":270}],270:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isEven = require( '@stdlib/math/base/assert/is-even' );
// MAIN //
/**
* Tests if a finite numeric value is an odd number.
*
* @param {number} x - value to test
* @returns {boolean} boolean indicating whether the value is an odd number
*
* @example
* var bool = isOdd( 5.0 );
* // returns true
*
* @example
* var bool = isOdd( -2.0 );
* // returns false
*
* @example
* var bool = isOdd( 0.0 );
* // returns false
*
* @example
* var bool = isOdd( NaN );
* // returns false
*/
function isOdd( x ) {
// Check sign to prevent overflow...
if ( x > 0.0 ) {
return isEven( x-1.0 );
}
return isEven( x+1.0 );
}
// EXPORTS //
module.exports = isOdd;
},{"@stdlib/math/base/assert/is-even":259}],271:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a double-precision floating-point numeric value is positive zero.
*
* @module @stdlib/math/base/assert/is-positive-zero
*
* @example
* var isPositiveZero = require( '@stdlib/math/base/assert/is-positive-zero' );
*
* var bool = isPositiveZero( 0.0 );
* // returns true
*
* bool = isPositiveZero( -0.0 );
* // returns false
*/
// MODULES //
var isPositiveZero = require( './main.js' );
// EXPORTS //
module.exports = isPositiveZero;
},{"./main.js":272}],272:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var PINF = require( '@stdlib/constants/float64/pinf' );
// MAIN //
/**
* Tests if a double-precision floating-point numeric value is positive zero.
*
* @param {number} x - value to test
* @returns {boolean} boolean indicating whether the value is positive zero
*
* @example
* var bool = isPositiveZero( 0.0 );
* // returns true
*
* @example
* var bool = isPositiveZero( -0.0 );
* // returns false
*/
function isPositiveZero( x ) {
return (x === 0.0 && 1.0/x === PINF);
}
// EXPORTS //
module.exports = isPositiveZero;
},{"@stdlib/constants/float64/pinf":246}],273:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Compute an absolute value of a double-precision floating-point number.
*
* @module @stdlib/math/base/special/abs
*
* @example
* var abs = require( '@stdlib/math/base/special/abs' );
*
* var v = abs( -1.0 );
* // returns 1.0
*
* v = abs( 2.0 );
* // returns 2.0
*
* v = abs( 0.0 );
* // returns 0.0
*
* v = abs( -0.0 );
* // returns 0.0
*
* v = abs( NaN );
* // returns NaN
*/
// MODULES //
var abs = require( './main.js' );
// EXPORTS //
module.exports = abs;
},{"./main.js":274}],274:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Computes the absolute value of a double-precision floating-point number `x`.
*
* @param {number} x - input value
* @returns {number} absolute value
*
* @example
* var v = abs( -1.0 );
* // returns 1.0
*
* @example
* var v = abs( 2.0 );
* // returns 2.0
*
* @example
* var v = abs( 0.0 );
* // returns 0.0
*
* @example
* var v = abs( -0.0 );
* // returns 0.0
*
* @example
* var v = abs( NaN );
* // returns NaN
*/
function abs( x ) {
return Math.abs( x ); // eslint-disable-line stdlib/no-builtin-math
}
// EXPORTS //
module.exports = abs;
},{}],275:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var toWords = require( '@stdlib/number/float64/base/to-words' );
var getHighWord = require( '@stdlib/number/float64/base/get-high-word' );
var fromWords = require( '@stdlib/number/float64/base/from-words' );
// VARIABLES //
// 10000000000000000000000000000000 => 2147483648 => 0x80000000
var SIGN_MASK = 0x80000000>>>0; // asm type annotation
// 01111111111111111111111111111111 => 2147483647 => 0x7fffffff
var MAGNITUDE_MASK = 0x7fffffff|0; // asm type annotation
// High/low words workspace:
var WORDS = [ 0, 0 ]; // WARNING: not thread safe
// MAIN //
/**
* Returns a double-precision floating-point number with the magnitude of `x` and the sign of `y`.
*
* @param {number} x - number from which to derive a magnitude
* @param {number} y - number from which to derive a sign
* @returns {number} a double-precision floating-point number
*
* @example
* var z = copysign( -3.14, 10.0 );
* // returns 3.14
*
* @example
* var z = copysign( 3.14, -1.0 );
* // returns -3.14
*
* @example
* var z = copysign( 1.0, -0.0 );
* // returns -1.0
*
* @example
* var z = copysign( -3.14, -0.0 );
* // returns -3.14
*
* @example
* var z = copysign( -0.0, 1.0 );
* // returns 0.0
*/
function copysign( x, y ) {
var hx;
var hy;
// Split `x` into higher and lower order words:
toWords( WORDS, x );
hx = WORDS[ 0 ];
// Turn off the sign bit of `x`:
hx &= MAGNITUDE_MASK;
// Extract the higher order word from `y`:
hy = getHighWord( y );
// Leave only the sign bit of `y` turned on:
hy &= SIGN_MASK;
// Copy the sign bit of `y` to `x`:
hx |= hy;
// Return a new value having the same magnitude as `x`, but with the sign of `y`:
return fromWords( hx, WORDS[ 1 ] );
}
// EXPORTS //
module.exports = copysign;
},{"@stdlib/number/float64/base/from-words":307,"@stdlib/number/float64/base/get-high-word":311,"@stdlib/number/float64/base/to-words":325}],276:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Return a double-precision floating-point number with the magnitude of `x` and the sign of `y`.
*
* @module @stdlib/math/base/special/copysign
*
* @example
* var copysign = require( '@stdlib/math/base/special/copysign' );
*
* var z = copysign( -3.14, 10.0 );
* // returns 3.14
*
* z = copysign( 3.14, -1.0 );
* // returns -3.14
*
* z = copysign( 1.0, -0.0 );
* // returns -1.0
*
* z = copysign( -3.14, -0.0 );
* // returns -3.14
*
* z = copysign( -0.0, 1.0 );
* // returns 0.0
*/
// MODULES //
var copysign = require( './copysign.js' );
// EXPORTS //
module.exports = copysign;
},{"./copysign.js":275}],277:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Round a double-precision floating-point number toward negative infinity.
*
* @module @stdlib/math/base/special/floor
*
* @example
* var floor = require( '@stdlib/math/base/special/floor' );
*
* var v = floor( -4.2 );
* // returns -5.0
*
* v = floor( 9.99999 );
* // returns 9.0
*
* v = floor( 0.0 );
* // returns 0.0
*
* v = floor( NaN );
* // returns NaN
*/
// MODULES //
var floor = require( './main.js' );
// EXPORTS //
module.exports = floor;
},{"./main.js":278}],278:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// TODO: implementation (?)
/**
* Rounds a double-precision floating-point number toward negative infinity.
*
* @param {number} x - input value
* @returns {number} rounded value
*
* @example
* var v = floor( -4.2 );
* // returns -5.0
*
* @example
* var v = floor( 9.99999 );
* // returns 9.0
*
* @example
* var v = floor( 0.0 );
* // returns 0.0
*
* @example
* var v = floor( NaN );
* // returns NaN
*/
var floor = Math.floor; // eslint-disable-line stdlib/no-builtin-math
// EXPORTS //
module.exports = floor;
},{}],279:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Multiply a double-precision floating-point number by an integer power of two.
*
* @module @stdlib/math/base/special/ldexp
*
* @example
* var ldexp = require( '@stdlib/math/base/special/ldexp' );
*
* var x = ldexp( 0.5, 3 ); // => 0.5 * 2^3 = 0.5 * 8
* // returns 4.0
*
* x = ldexp( 4.0, -2 ); // => 4 * 2^(-2) = 4 * (1/4)
* // returns 1.0
*
* x = ldexp( 0.0, 20 );
* // returns 0.0
*
* x = ldexp( -0.0, 39 );
* // returns -0.0
*
* x = ldexp( NaN, -101 );
* // returns NaN
*
* x = ldexp( Infinity, 11 );
* // returns Infinity
*
* x = ldexp( -Infinity, -118 );
* // returns -Infinity
*/
// MODULES //
var ldexp = require( './ldexp.js' );
// EXPORTS //
module.exports = ldexp;
},{"./ldexp.js":280}],280:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// NOTES //
/*
* => ldexp: load exponent (see [The Open Group]{@link http://pubs.opengroup.org/onlinepubs/9699919799/functions/ldexp.html} and [cppreference]{@link http://en.cppreference.com/w/c/numeric/math/ldexp}).
*/
// MODULES //
var PINF = require( '@stdlib/constants/float64/pinf' );
var NINF = require( '@stdlib/constants/float64/ninf' );
var BIAS = require( '@stdlib/constants/float64/exponent-bias' );
var MAX_EXPONENT = require( '@stdlib/constants/float64/max-base2-exponent' );
var MAX_SUBNORMAL_EXPONENT = require( '@stdlib/constants/float64/max-base2-exponent-subnormal' );
var MIN_SUBNORMAL_EXPONENT = require( '@stdlib/constants/float64/min-base2-exponent-subnormal' );
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var isInfinite = require( '@stdlib/math/base/assert/is-infinite' );
var copysign = require( '@stdlib/math/base/special/copysign' );
var normalize = require( '@stdlib/number/float64/base/normalize' );
var floatExp = require( '@stdlib/number/float64/base/exponent' );
var toWords = require( '@stdlib/number/float64/base/to-words' );
var fromWords = require( '@stdlib/number/float64/base/from-words' );
// VARIABLES //
// 1/(1<<52) = 1/(2**52) = 1/4503599627370496
var TWO52_INV = 2.220446049250313e-16;
// Exponent all 0s: 1 00000000000 11111111111111111111 => 2148532223
var CLEAR_EXP_MASK = 0x800fffff>>>0; // asm type annotation
// Normalization workspace:
var FRAC = [ 0.0, 0.0 ]; // WARNING: not thread safe
// High/low words workspace:
var WORDS = [ 0, 0 ]; // WARNING: not thread safe
// MAIN //
/**
* Multiplies a double-precision floating-point number by an integer power of two.
*
* @param {number} frac - fraction
* @param {integer} exp - exponent
* @returns {number} double-precision floating-point number
*
* @example
* var x = ldexp( 0.5, 3 ); // => 0.5 * 2^3 = 0.5 * 8
* // returns 4.0
*
* @example
* var x = ldexp( 4.0, -2 ); // => 4 * 2^(-2) = 4 * (1/4)
* // returns 1.0
*
* @example
* var x = ldexp( 0.0, 20 );
* // returns 0.0
*
* @example
* var x = ldexp( -0.0, 39 );
* // returns -0.0
*
* @example
* var x = ldexp( NaN, -101 );
* // returns NaN
*
* @example
* var x = ldexp( Infinity, 11 );
* // returns Infinity
*
* @example
* var x = ldexp( -Infinity, -118 );
* // returns -Infinity
*/
function ldexp( frac, exp ) {
var high;
var m;
if (
frac === 0.0 || // handles +-0
isnan( frac ) ||
isInfinite( frac )
) {
return frac;
}
// Normalize the input fraction:
normalize( FRAC, frac );
frac = FRAC[ 0 ];
exp += FRAC[ 1 ];
// Extract the exponent from `frac` and add it to `exp`:
exp += floatExp( frac );
// Check for underflow/overflow...
if ( exp < MIN_SUBNORMAL_EXPONENT ) {
return copysign( 0.0, frac );
}
if ( exp > MAX_EXPONENT ) {
if ( frac < 0.0 ) {
return NINF;
}
return PINF;
}
// Check for a subnormal and scale accordingly to retain precision...
if ( exp <= MAX_SUBNORMAL_EXPONENT ) {
exp += 52;
m = TWO52_INV;
} else {
m = 1.0;
}
// Split the fraction into higher and lower order words:
toWords( WORDS, frac );
high = WORDS[ 0 ];
// Clear the exponent bits within the higher order word:
high &= CLEAR_EXP_MASK;
// Set the exponent bits to the new exponent:
high |= ((exp+BIAS) << 20);
// Create a new floating-point number:
return m * fromWords( high, WORDS[ 1 ] );
}
// EXPORTS //
module.exports = ldexp;
},{"@stdlib/constants/float64/exponent-bias":237,"@stdlib/constants/float64/max-base2-exponent":242,"@stdlib/constants/float64/max-base2-exponent-subnormal":241,"@stdlib/constants/float64/min-base2-exponent-subnormal":244,"@stdlib/constants/float64/ninf":245,"@stdlib/constants/float64/pinf":246,"@stdlib/math/base/assert/is-infinite":261,"@stdlib/math/base/assert/is-nan":265,"@stdlib/math/base/special/copysign":276,"@stdlib/number/float64/base/exponent":305,"@stdlib/number/float64/base/from-words":307,"@stdlib/number/float64/base/normalize":313,"@stdlib/number/float64/base/to-words":325}],281:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Return the maximum value.
*
* @module @stdlib/math/base/special/max
*
* @example
* var max = require( '@stdlib/math/base/special/max' );
*
* var v = max( 3.14, 4.2 );
* // returns 4.2
*
* v = max( 5.9, 3.14, 4.2 );
* // returns 5.9
*
* v = max( 3.14, NaN );
* // returns NaN
*
* v = max( +0.0, -0.0 );
* // returns +0.0
*/
// MODULES //
var max = require( './max.js' );
// EXPORTS //
module.exports = max;
},{"./max.js":282}],282:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isPositiveZero = require( '@stdlib/math/base/assert/is-positive-zero' );
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var NINF = require( '@stdlib/constants/float64/ninf' );
var PINF = require( '@stdlib/constants/float64/pinf' );
// MAIN //
/**
* Returns the maximum value.
*
* @param {number} [x] - first number
* @param {number} [y] - second number
* @param {...number} [args] - numbers
* @returns {number} maximum value
*
* @example
* var v = max( 3.14, 4.2 );
* // returns 4.2
*
* @example
* var v = max( 5.9, 3.14, 4.2 );
* // returns 5.9
*
* @example
* var v = max( 3.14, NaN );
* // returns NaN
*
* @example
* var v = max( +0.0, -0.0 );
* // returns +0.0
*/
function max( x, y ) {
var len;
var m;
var v;
var i;
len = arguments.length;
if ( len === 2 ) {
if ( isnan( x ) || isnan( y ) ) {
return NaN;
}
if ( x === PINF || y === PINF ) {
return PINF;
}
if ( x === y && x === 0.0 ) {
if ( isPositiveZero( x ) ) {
return x;
}
return y;
}
if ( x > y ) {
return x;
}
return y;
}
m = NINF;
for ( i = 0; i < len; i++ ) {
v = arguments[ i ];
if ( isnan( v ) || v === PINF ) {
return v;
}
if ( v > m ) {
m = v;
} else if (
v === m &&
v === 0.0 &&
isPositiveZero( v )
) {
m = v;
}
}
return m;
}
// EXPORTS //
module.exports = max;
},{"@stdlib/constants/float64/ninf":245,"@stdlib/constants/float64/pinf":246,"@stdlib/math/base/assert/is-nan":265,"@stdlib/math/base/assert/is-positive-zero":271}],283:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Decompose a double-precision floating-point number into integral and fractional parts.
*
* @module @stdlib/math/base/special/modf
*
* @example
* var modf = require( '@stdlib/math/base/special/modf' );
*
* var parts = modf( 3.14 );
* // returns [ 3.0, 0.14000000000000012 ]
*
* @example
* var Float64Array = require( '@stdlib/array/float64' );
* var modf = require( '@stdlib/math/base/special/modf' );
*
* var out = new Float64Array( 2 );
*
* var parts = modf( out, 3.14 );
* // returns [ 3.0, 0.14000000000000012 ]
*
* var bool = ( parts === out );
* // returns true
*/
// MODULES //
var modf = require( './main.js' );
// EXPORTS //
module.exports = modf;
},{"./main.js":284}],284:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var fcn = require( './modf.js' );
// MAIN //
/**
* Decomposes a double-precision floating-point number into integral and fractional parts, each having the same type and sign as the input value.
*
* @param {(Array|TypedArray|Object)} [out] - output array
* @param {number} x - input value
* @returns {(Array|TypedArray|Object)} output array
*
* @example
* var parts = modf( 3.14 );
* // returns [ 3.0, 0.14000000000000012 ]
*
* @example
* var Float64Array = require( '@stdlib/array/float64' );
*
* var out = new Float64Array( 2 );
*
* var parts = modf( out, 3.14 );
* // returns <Float64Array>[ 3.0, 0.14000000000000012 ]
*
* var bool = ( parts === out );
* // returns true
*/
function modf( out, x ) {
if ( arguments.length === 1 ) {
return fcn( [ 0.0, 0.0 ], out );
}
return fcn( out, x );
}
// EXPORTS //
module.exports = modf;
},{"./modf.js":285}],285:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var toWords = require( '@stdlib/number/float64/base/to-words' );
var fromWords = require( '@stdlib/number/float64/base/from-words' );
var PINF = require( '@stdlib/constants/float64/pinf' );
var FLOAT64_EXPONENT_BIAS = require( '@stdlib/constants/float64/exponent-bias' );
var FLOAT64_HIGH_WORD_EXPONENT_MASK = require( '@stdlib/constants/float64/high-word-exponent-mask' ); // eslint-disable-line id-length
var FLOAT64_HIGH_WORD_SIGNIFICAND_MASK = require( '@stdlib/constants/float64/high-word-significand-mask' ); // eslint-disable-line id-length
// VARIABLES //
// 4294967295 => 0xffffffff => 11111111111111111111111111111111
var ALL_ONES = 4294967295>>>0; // asm type annotation
// High/low words workspace:
var WORDS = [ 0|0, 0|0 ]; // WARNING: not thread safe
// MAIN //
/**
* Decomposes a double-precision floating-point number into integral and fractional parts, each having the same type and sign as the input value.
*
* @private
* @param {(Array|TypedArray|Object)} out - output array
* @param {number} x - input value
* @returns {(Array|TypedArray|Object)} output array
*
* @example
* var parts = modf( [ 0.0, 0.0 ], 3.14 );
* // returns [ 3.0, 0.14000000000000012 ]
*/
function modf( out, x ) {
var high;
var low;
var exp;
var i;
// Special cases...
if ( x < 1.0 ) {
if ( x < 0.0 ) {
modf( out, -x );
out[ 0 ] *= -1.0;
out[ 1 ] *= -1.0;
return out;
}
if ( x === 0.0 ) { // [ +-0, +-0 ]
out[ 0 ] = x;
out[ 1 ] = x;
return out;
}
out[ 0 ] = 0.0;
out[ 1 ] = x;
return out;
}
if ( isnan( x ) ) {
out[ 0 ] = NaN;
out[ 1 ] = NaN;
return out;
}
if ( x === PINF ) {
out[ 0 ] = PINF;
out[ 1 ] = 0.0;
return out;
}
// Decompose |x|...
// Extract the high and low words:
toWords( WORDS, x );
high = WORDS[ 0 ];
low = WORDS[ 1 ];
// Extract the unbiased exponent from the high word:
exp = ((high & FLOAT64_HIGH_WORD_EXPONENT_MASK) >> 20)|0; // asm type annotation
exp -= FLOAT64_EXPONENT_BIAS|0; // asm type annotation
// Handle smaller values (x < 2**20 = 1048576)...
if ( exp < 20 ) {
i = (FLOAT64_HIGH_WORD_SIGNIFICAND_MASK >> exp)|0; // asm type annotation
// Determine if `x` is integral by checking for significand bits which cannot be exponentiated away...
if ( ((high&i)|low) === 0 ) {
out[ 0 ] = x;
out[ 1 ] = 0.0;
return out;
}
// Turn off all the bits which cannot be exponentiated away:
high &= (~i);
// Generate the integral part:
i = fromWords( high, 0 );
// The fractional part is whatever is leftover:
out[ 0 ] = i;
out[ 1 ] = x - i;
return out;
}
// Check if `x` can even have a fractional part...
if ( exp > 51 ) {
// `x` is integral:
out[ 0 ] = x;
out[ 1 ] = 0.0;
return out;
}
i = ALL_ONES >>> (exp-20);
// Determine if `x` is integral by checking for less significant significand bits which cannot be exponentiated away...
if ( (low&i) === 0 ) {
out[ 0 ] = x;
out[ 1 ] = 0.0;
return out;
}
// Turn off all the bits which cannot be exponentiated away:
low &= (~i);
// Generate the integral part:
i = fromWords( high, low );
// The fractional part is whatever is leftover:
out[ 0 ] = i;
out[ 1 ] = x - i;
return out;
}
// EXPORTS //
module.exports = modf;
},{"@stdlib/constants/float64/exponent-bias":237,"@stdlib/constants/float64/high-word-exponent-mask":238,"@stdlib/constants/float64/high-word-significand-mask":239,"@stdlib/constants/float64/pinf":246,"@stdlib/math/base/assert/is-nan":265,"@stdlib/number/float64/base/from-words":307,"@stdlib/number/float64/base/to-words":325}],286:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Evaluate the exponential function.
*
* @module @stdlib/math/base/special/pow
*
* @example
* var pow = require( '@stdlib/math/base/special/pow' );
*
* var v = pow( 2.0, 3.0 );
* // returns 8.0
*
* v = pow( 4.0, 0.5 );
* // returns 2.0
*
* v = pow( 100.0, 0.0 );
* // returns 1.0
*
* v = pow( 3.141592653589793, 5.0 );
* // returns ~306.0197
*
* v = pow( 3.141592653589793, -0.2 );
* // returns ~0.7954
*
* v = pow( NaN, 3.0 );
* // returns NaN
*
* v = pow( 5.0, NaN );
* // returns NaN
*
* v = pow( NaN, NaN );
* // returns NaN
*/
// MODULES //
var pow = require( './pow.js' );
// EXPORTS //
module.exports = pow;
},{"./pow.js":292}],287:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*
*
* ## Notice
*
* The following copyright and license were part of the original implementation available as part of [FreeBSD]{@link https://svnweb.freebsd.org/base/release/9.3.0/lib/msun/src/s_pow.c}. The implementation follows the original, but has been modified for JavaScript.
*
* ```text
* Copyright (C) 2004 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunPro, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ```
*/
'use strict';
// MODULES //
var getHighWord = require( '@stdlib/number/float64/base/get-high-word' );
var setLowWord = require( '@stdlib/number/float64/base/set-low-word' );
var setHighWord = require( '@stdlib/number/float64/base/set-high-word' );
var BIAS = require( '@stdlib/constants/float64/exponent-bias' );
var polyvalL = require( './polyval_l.js' );
// VARIABLES //
// 0x000fffff = 1048575 => 0 00000000000 11111111111111111111
var HIGH_SIGNIFICAND_MASK = 0x000fffff|0; // asm type annotation
// 0x00100000 = 1048576 => 0 00000000001 00000000000000000000 => biased exponent: 1 = -1022+1023 => 2^-1022
var HIGH_MIN_NORMAL_EXP = 0x00100000|0; // asm type annotation
// 0x3ff00000 = 1072693248 => 0 01111111111 00000000000000000000 => biased exponent: 1023 = 0+1023 => 2^0 = 1
var HIGH_BIASED_EXP_0 = 0x3ff00000|0; // asm type annotation
// 0x20000000 = 536870912 => 0 01000000000 00000000000000000000 => biased exponent: 512 = -511+1023
var HIGH_BIASED_EXP_NEG_512 = 0x20000000|0; // asm type annotation
// 0x00080000 = 524288 => 0 00000000000 10000000000000000000
var HIGH_SIGNIFICAND_HALF = 0x00080000|0; // asm type annotation
// TODO: consider making an external constant
var HIGH_NUM_SIGNIFICAND_BITS = 20|0; // asm type annotation
var TWO53 = 9007199254740992.0; // 0x43400000, 0x00000000
// 2/(3*LN2)
var CP = 9.61796693925975554329e-01; // 0x3FEEC709, 0xDC3A03FD
// (float)CP
var CP_HI = 9.61796700954437255859e-01; // 0x3FEEC709, 0xE0000000
// Low: CP_HI
var CP_LO = -7.02846165095275826516e-09; // 0xBE3E2FE0, 0x145B01F5
var BP = [
1.0,
1.5
];
var DP_HI = [
0.0,
5.84962487220764160156e-01 // 0x3FE2B803, 0x40000000
];
var DP_LO = [
0.0,
1.35003920212974897128e-08 // 0x3E4CFDEB, 0x43CFD006
];
// MAIN //
/**
* Computes \\(\operatorname{log2}(ax)\\).
*
* @private
* @param {Array} out - output array
* @param {number} ax - absolute value of `x`
* @param {number} ahx - high word of `ax`
* @returns {Array} output array containing a tuple comprised of high and low parts
*
* @example
* var t = log2ax( [ 0.0, 0.0 ], 9.0, 1075970048 ); // => [ t1, t2 ]
* // returns [ 3.169923782348633, 0.0000012190936795504075 ]
*/
function log2ax( out, ax, ahx ) {
var tmp;
var ss; // `hs + ls`
var s2; // `ss` squared
var hs;
var ls;
var ht;
var lt;
var bp; // `BP` constant
var dp; // `DP` constant
var hp;
var lp;
var hz;
var lz;
var t1;
var t2;
var t;
var r;
var u;
var v;
var n;
var j;
var k;
n = 0|0; // asm type annotation
// Check if `x` is subnormal...
if ( ahx < HIGH_MIN_NORMAL_EXP ) {
ax *= TWO53;
n -= 53|0; // asm type annotation
ahx = getHighWord( ax );
}
// Extract the unbiased exponent of `x`:
n += ((ahx >> HIGH_NUM_SIGNIFICAND_BITS) - BIAS)|0; // asm type annotation
// Isolate the significand bits of `x`:
j = (ahx & HIGH_SIGNIFICAND_MASK)|0; // asm type annotation
// Normalize `ahx` by setting the (biased) exponent to `1023`:
ahx = (j | HIGH_BIASED_EXP_0)|0; // asm type annotation
// Determine the interval of `|x|` by comparing significand bits...
// |x| < sqrt(3/2)
if ( j <= 0x3988E ) { // 0 00000000000 00111001100010001110
k = 0;
}
// |x| < sqrt(3)
else if ( j < 0xBB67A ) { // 0 00000000000 10111011011001111010
k = 1;
}
// |x| >= sqrt(3)
else {
k = 0;
n += 1|0; // asm type annotation
ahx -= HIGH_MIN_NORMAL_EXP;
}
// Load the normalized high word into `|x|`:
ax = setHighWord( ax, ahx );
// Compute `ss = hs + ls = (x-1)/(x+1)` or `(x-1.5)/(x+1.5)`:
bp = BP[ k ]; // BP[0] = 1.0, BP[1] = 1.5
u = ax - bp; // (x-1) || (x-1.5)
v = 1.0 / (ax + bp); // 1/(x+1) || 1/(x+1.5)
ss = u * v;
hs = setLowWord( ss, 0 ); // set all low word (less significant significand) bits to 0s
// Compute `ht = ax + bp` (via manipulation, i.e., bit flipping, of the high word):
tmp = ((ahx>>1) | HIGH_BIASED_EXP_NEG_512) + HIGH_SIGNIFICAND_HALF;
tmp += (k << 18); // `(k<<18)` can be considered the word equivalent of `1.0` or `1.5`
ht = setHighWord( 0.0, tmp );
lt = ax - (ht - bp);
ls = v * ( ( u - (hs*ht) ) - ( hs*lt ) );
// Compute `log(ax)`...
s2 = ss * ss;
r = s2 * s2 * polyvalL( s2 );
r += ls * (hs + ss);
s2 = hs * hs;
ht = 3.0 + s2 + r;
ht = setLowWord( ht, 0 );
lt = r - ((ht-3.0) - s2);
// u+v = ss*(1+...):
u = hs * ht;
v = ( ls*ht ) + ( lt*ss );
// 2/(3LN2) * (ss+...):
hp = u + v;
hp = setLowWord( hp, 0 );
lp = v - (hp - u);
hz = CP_HI * hp; // CP_HI+CP_LO = 2/(3*LN2)
lz = ( CP_LO*hp ) + ( lp*CP ) + DP_LO[ k ];
// log2(ax) = (ss+...)*2/(3*LN2) = n + dp + hz + lz
dp = DP_HI[ k ];
t = n;
t1 = ((hz+lz) + dp) + t; // log2(ax)
t1 = setLowWord( t1, 0 );
t2 = lz - (((t1-t) - dp) - hz);
out[ 0 ] = t1;
out[ 1 ] = t2;
return out;
}
// EXPORTS //
module.exports = log2ax;
},{"./polyval_l.js":289,"@stdlib/constants/float64/exponent-bias":237,"@stdlib/number/float64/base/get-high-word":311,"@stdlib/number/float64/base/set-high-word":317,"@stdlib/number/float64/base/set-low-word":319}],288:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*
*
* ## Notice
*
* The following copyright and license were part of the original implementation available as part of [FreeBSD]{@link https://svnweb.freebsd.org/base/release/9.3.0/lib/msun/src/s_pow.c}. The implementation follows the original, but has been modified for JavaScript.
*
* ```text
* Copyright (C) 2004 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunPro, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ```
*/
'use strict';
// MODULES //
var setLowWord = require( '@stdlib/number/float64/base/set-low-word' );
var polyvalW = require( './polyval_w.js' );
// VARIABLES //
// 1/LN2
var INV_LN2 = 1.44269504088896338700e+00; // 0x3FF71547, 0x652B82FE
// High (24 bits): 1/LN2
var INV_LN2_HI = 1.44269502162933349609e+00; // 0x3FF71547, 0x60000000
// Low: 1/LN2
var INV_LN2_LO = 1.92596299112661746887e-08; // 0x3E54AE0B, 0xF85DDF44
// MAIN //
/**
* Computes \\(\operatorname{log}(x)\\) assuming \\(|1-x|\\) is small and using the approximation \\(x - x^2/2 + x^3/3 - x^4/4\\).
*
* @private
* @param {Array} out - output array
* @param {number} ax - absolute value of `x`
* @returns {Array} output array containing a tuple comprised of high and low parts
*
* @example
* var t = logx( [ 0.0, 0.0 ], 9.0 ); // => [ t1, t2 ]
* // returns [ -1265.7236328125, -0.0008163940840404393 ]
*/
function logx( out, ax ) {
var t2;
var t1;
var t;
var w;
var u;
var v;
t = ax - 1.0; // `t` has `20` trailing zeros
w = t * t * polyvalW( t );
u = INV_LN2_HI * t; // `INV_LN2_HI` has `21` significant bits
v = ( t*INV_LN2_LO ) - ( w*INV_LN2 );
t1 = u + v;
t1 = setLowWord( t1, 0 );
t2 = v - (t1 - u);
out[ 0 ] = t1;
out[ 1 ] = t2;
return out;
}
// EXPORTS //
module.exports = logx;
},{"./polyval_w.js":291,"@stdlib/number/float64/base/set-low-word":319}],289:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
/* This is a generated file. Do not edit directly. */
'use strict';
// MAIN //
/**
* Evaluates a polynomial.
*
* ## Notes
*
* - The implementation uses [Horner's rule][horners-method] for efficient computation.
*
* [horners-method]: https://en.wikipedia.org/wiki/Horner%27s_method
*
*
* @private
* @param {number} x - value at which to evaluate the polynomial
* @returns {number} evaluated polynomial
*/
function evalpoly( x ) {
if ( x === 0.0 ) {
return 0.5999999999999946;
}
return 0.5999999999999946 + (x * (0.4285714285785502 + (x * (0.33333332981837743 + (x * (0.272728123808534 + (x * (0.23066074577556175 + (x * 0.20697501780033842))))))))); // eslint-disable-line max-len
}
// EXPORTS //
module.exports = evalpoly;
},{}],290:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
/* This is a generated file. Do not edit directly. */
'use strict';
// MAIN //
/**
* Evaluates a polynomial.
*
* ## Notes
*
* - The implementation uses [Horner's rule][horners-method] for efficient computation.
*
* [horners-method]: https://en.wikipedia.org/wiki/Horner%27s_method
*
*
* @private
* @param {number} x - value at which to evaluate the polynomial
* @returns {number} evaluated polynomial
*/
function evalpoly( x ) {
if ( x === 0.0 ) {
return 0.16666666666666602;
}
return 0.16666666666666602 + (x * (-0.0027777777777015593 + (x * (0.00006613756321437934 + (x * (-0.0000016533902205465252 + (x * 4.1381367970572385e-8))))))); // eslint-disable-line max-len
}
// EXPORTS //
module.exports = evalpoly;
},{}],291:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
/* This is a generated file. Do not edit directly. */
'use strict';
// MAIN //
/**
* Evaluates a polynomial.
*
* ## Notes
*
* - The implementation uses [Horner's rule][horners-method] for efficient computation.
*
* [horners-method]: https://en.wikipedia.org/wiki/Horner%27s_method
*
*
* @private
* @param {number} x - value at which to evaluate the polynomial
* @returns {number} evaluated polynomial
*/
function evalpoly( x ) {
if ( x === 0.0 ) {
return 0.5;
}
return 0.5 + (x * (-0.3333333333333333 + (x * 0.25)));
}
// EXPORTS //
module.exports = evalpoly;
},{}],292:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*
*
* ## Notice
*
* The following copyright and license were part of the original implementation available as part of [FreeBSD]{@link https://svnweb.freebsd.org/base/release/9.3.0/lib/msun/src/s_pow.c}. The implementation follows the original, but has been modified for JavaScript.
*
* ```text
* Copyright (C) 2004 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunPro, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ```
*/
'use strict';
// MODULES //
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var isOdd = require( '@stdlib/math/base/assert/is-odd' );
var isInfinite = require( '@stdlib/math/base/assert/is-infinite' );
var isInteger = require( '@stdlib/math/base/assert/is-integer' );
var sqrt = require( '@stdlib/math/base/special/sqrt' );
var abs = require( '@stdlib/math/base/special/abs' );
var toWords = require( '@stdlib/number/float64/base/to-words' );
var setLowWord = require( '@stdlib/number/float64/base/set-low-word' );
var uint32ToInt32 = require( '@stdlib/number/uint32/base/to-int32' );
var NINF = require( '@stdlib/constants/float64/ninf' );
var PINF = require( '@stdlib/constants/float64/pinf' );
var xIsZero = require( './x_is_zero.js' );
var yIsHuge = require( './y_is_huge.js' );
var yIsInfinite = require( './y_is_infinite.js' );
var log2ax = require( './log2ax.js' );
var logx = require( './logx.js' );
var pow2 = require( './pow2.js' );
// VARIABLES //
// 0x7fffffff = 2147483647 => 0 11111111111 11111111111111111111
var ABS_MASK = 0x7fffffff|0; // asm type annotation
// 0x3fefffff = 1072693247 => 0 01111111110 11111111111111111111 => biased exponent: 1022 = -1+1023 => 2^-1
var HIGH_MAX_NEAR_UNITY = 0x3fefffff|0; // asm type annotation
// 0x41e00000 = 1105199104 => 0 10000011110 00000000000000000000 => biased exponent: 1054 = 31+1023 => 2^31
var HIGH_BIASED_EXP_31 = 0x41e00000|0; // asm type annotation
// 0x43f00000 = 1139802112 => 0 10000111111 00000000000000000000 => biased exponent: 1087 = 64+1023 => 2^64
var HIGH_BIASED_EXP_64 = 0x43f00000|0; // asm type annotation
// 0x40900000 = 1083179008 => 0 10000001001 00000000000000000000 => biased exponent: 1033 = 10+1023 => 2^10 = 1024
var HIGH_BIASED_EXP_10 = 0x40900000|0; // asm type annotation
// 0x3ff00000 = 1072693248 => 0 01111111111 00000000000000000000 => biased exponent: 1023 = 0+1023 => 2^0 = 1
var HIGH_BIASED_EXP_0 = 0x3ff00000|0; // asm type annotation
// 0x4090cc00 = 1083231232 => 0 10000001001 00001100110000000000
var HIGH_1075 = 0x4090cc00|0; // asm type annotation
// 0xc090cc00 = 3230714880 => 1 10000001001 00001100110000000000
var HIGH_NEG_1075 = 0xc090cc00>>>0; // asm type annotation
var HIGH_NUM_NONSIGN_BITS = 31|0; // asm type annotation
var HUGE = 1.0e300;
var TINY = 1.0e-300;
// -(1024-log2(ovfl+.5ulp))
var OVT = 8.0085662595372944372e-17;
// High/low words workspace:
var WORDS = [ 0|0, 0|0 ]; // WARNING: not thread safe
// Log workspace:
var LOG_WORKSPACE = [ 0.0, 0.0 ]; // WARNING: not thread safe
// MAIN //
/**
* Evaluates the exponential function.
*
* ## Method
*
* 1. Let \\(x = 2^n (1+f)\\).
*
* 2. Compute \\(\operatorname{log2}(x)\\) as
*
* ```tex
* \operatorname{log2}(x) = w_1 + w_2
* ```
*
* where \\(w_1\\) has \\(53 - 24 = 29\\) bit trailing zeros.
*
* 3. Compute
*
* ```tex
* y \cdot \operatorname{log2}(x) = n + y^\prime
* ```
*
* by simulating multi-precision arithmetic, where \\(|y^\prime| \leq 0.5\\).
*
* 4. Return
*
* ```tex
* x^y = 2^n e^{y^\prime \cdot \mathrm{log2}}
* ```
*
* ## Special Cases
*
* ```tex
* \begin{align*}
* x^{\mathrm{NaN}} &= \mathrm{NaN} & \\
* (\mathrm{NaN})^y &= \mathrm{NaN} & \\
* 1^y &= 1 & \\
* x^0 &= 1 & \\
* x^1 &= x & \\
* (\pm 0)^\infty &= +0 & \\
* (\pm 0)^{-\infty} &= +\infty & \\
* (+0)^y &= +0 & \mathrm{if}\ y > 0 \\
* (+0)^y &= +\infty & \mathrm{if}\ y < 0 \\
* (-0)^y &= -\infty & \mathrm{if}\ y\ \mathrm{is\ an\ odd\ integer\ and}\ y < 0 \\
* (-0)^y &= +\infty & \mathrm{if}\ y\ \mathrm{is\ not\ an\ odd\ integer\ and}\ y < 0 \\
* (-0)^y &= -0 & \mathrm{if}\ y\ \mathrm{is\ an\ odd\ integer\ and}\ y > 0 \\
* (-0)^y &= +0 & \mathrm{if}\ y\ \mathrm{is\ not\ an\ odd\ integer\ and}\ y > 0 \\
* (-1)^{\pm\infty} &= \mathrm{NaN} & \\
* x^{\infty} &= +\infty & |x| > 1 \\
* x^{\infty} &= +0 & |x| < 1 \\
* x^{-\infty} &= +0 & |x| > 1 \\
* x^{-\infty} &= +\infty & |x| < 1 \\
* (-\infty)^y &= (-0)^y & \\
* \infty^y &= +0 & y < 0 \\
* \infty^y &= +\infty & y > 0 \\
* x^y &= \mathrm{NaN} & \mathrm{if}\ y\ \mathrm{is\ not\ a\ finite\ integer\ and}\ x < 0
* \end{align*}
* ```
*
* ## Notes
*
* - \\(\operatorname{pow}(x,y)\\) returns \\(x^y\\) nearly rounded. In particular, \\(\operatorname{pow}(<\mathrm{integer}>,<\mathrm{integer}>)\\) **always** returns the correct integer, provided the value is representable.
* - The hexadecimal values shown in the source code are the intended values for used constants. Decimal values may be used, provided the compiler will accurately convert decimal to binary in order to produce the hexadecimal values.
*
*
* @param {number} x - base
* @param {number} y - exponent
* @returns {number} function value
*
* @example
* var v = pow( 2.0, 3.0 );
* // returns 8.0
*
* @example
* var v = pow( 4.0, 0.5 );
* // returns 2.0
*
* @example
* var v = pow( 100.0, 0.0 );
* // returns 1.0
*
* @example
* var v = pow( 3.141592653589793, 5.0 );
* // returns ~306.0197
*
* @example
* var v = pow( 3.141592653589793, -0.2 );
* // returns ~0.7954
*
* @example
* var v = pow( NaN, 3.0 );
* // returns NaN
*
* @example
* var v = pow( 5.0, NaN );
* // returns NaN
*
* @example
* var v = pow( NaN, NaN );
* // returns NaN
*/
function pow( x, y ) {
var ahx; // absolute value high word `x`
var ahy; // absolute value high word `y`
var ax; // absolute value `x`
var hx; // high word `x`
var lx; // low word `x`
var hy; // high word `y`
var ly; // low word `y`
var sx; // sign `x`
var sy; // sign `y`
var y1;
var hp;
var lp;
var t;
var z; // y prime
var j;
var i;
if ( isnan( x ) || isnan( y ) ) {
return NaN;
}
// Split `y` into high and low words:
toWords( WORDS, y );
hy = WORDS[ 0 ];
ly = WORDS[ 1 ];
// Special cases `y`...
if ( ly === 0 ) {
if ( y === 0.0 ) {
return 1.0;
}
if ( y === 1.0 ) {
return x;
}
if ( y === -1.0 ) {
return 1.0 / x;
}
if ( y === 0.5 ) {
return sqrt( x );
}
if ( y === -0.5 ) {
return 1.0 / sqrt( x );
}
if ( y === 2.0 ) {
return x * x;
}
if ( y === 3.0 ) {
return x * x * x;
}
if ( y === 4.0 ) {
x *= x;
return x * x;
}
if ( isInfinite( y ) ) {
return yIsInfinite( x, y );
}
}
// Split `x` into high and low words:
toWords( WORDS, x );
hx = WORDS[ 0 ];
lx = WORDS[ 1 ];
// Special cases `x`...
if ( lx === 0 ) {
if ( hx === 0 ) {
return xIsZero( x, y );
}
if ( x === 1.0 ) {
return 1.0;
}
if (
x === -1.0 &&
isOdd( y )
) {
return -1.0;
}
if ( isInfinite( x ) ) {
if ( x === NINF ) {
// `pow( 1/x, -y )`
return pow( -0.0, -y );
}
if ( y < 0.0 ) {
return 0.0;
}
return PINF;
}
}
if (
x < 0.0 &&
isInteger( y ) === false
) {
// Signal NaN...
return (x-x)/(x-x);
}
ax = abs( x );
// Remove the sign bits (i.e., get absolute values):
ahx = (hx & ABS_MASK)|0; // asm type annotation
ahy = (hy & ABS_MASK)|0; // asm type annotation
// Extract the sign bits:
sx = (hx >>> HIGH_NUM_NONSIGN_BITS)|0; // asm type annotation
sy = (hy >>> HIGH_NUM_NONSIGN_BITS)|0; // asm type annotation
// Determine the sign of the result...
if ( sx && isOdd( y ) ) {
sx = -1.0;
} else {
sx = 1.0;
}
// Case 1: `|y|` is huge...
// |y| > 2^31
if ( ahy > HIGH_BIASED_EXP_31 ) {
// `|y| > 2^64`, then must over- or underflow...
if ( ahy > HIGH_BIASED_EXP_64 ) {
return yIsHuge( x, y );
}
// Over- or underflow if `x` is not close to unity...
if ( ahx < HIGH_MAX_NEAR_UNITY ) {
// y < 0
if ( sy === 1 ) {
// Signal overflow...
return sx * HUGE * HUGE;
}
// Signal underflow...
return sx * TINY * TINY;
}
if ( ahx > HIGH_BIASED_EXP_0 ) {
// y > 0
if ( sy === 0 ) {
// Signal overflow...
return sx * HUGE * HUGE;
}
// Signal underflow...
return sx * TINY * TINY;
}
// At this point, `|1-x|` is tiny (`<= 2^-20`). Suffice to compute `log(x)` by `x - x^2/2 + x^3/3 - x^4/4`.
t = logx( LOG_WORKSPACE, ax );
}
// Case 2: `|y|` is not huge...
else {
t = log2ax( LOG_WORKSPACE, ax, ahx );
}
// Split `y` into `y1 + y2` and compute `(y1+y2) * (t1+t2)`...
y1 = setLowWord( y, 0 );
lp = ( (y-y1)*t[0] ) + ( y*t[1] );
hp = y1 * t[0];
z = lp + hp;
// Note: *can* be more performant to use `getHighWord` and `getLowWord` directly, but using `toWords` looks cleaner.
toWords( WORDS, z );
j = uint32ToInt32( WORDS[0] );
i = uint32ToInt32( WORDS[1] );
// z >= 1024
if ( j >= HIGH_BIASED_EXP_10 ) {
// z > 1024
if ( ((j-HIGH_BIASED_EXP_10)|i) !== 0 ) {
// Signal overflow...
return sx * HUGE * HUGE;
}
if ( (lp+OVT) > (z-hp) ) {
// Signal overflow...
return sx * HUGE * HUGE;
}
}
// z <= -1075
else if ( (j&ABS_MASK) >= HIGH_1075 ) {
// z < -1075
if ( ((j-HIGH_NEG_1075)|i) !== 0 ) {
// signal underflow...
return sx * TINY * TINY;
}
if ( lp <= (z-hp) ) {
// signal underflow...
return sx * TINY * TINY;
}
}
// Compute `2^(hp+lp)`...
z = pow2( j, hp, lp );
return sx * z;
}
// EXPORTS //
module.exports = pow;
},{"./log2ax.js":287,"./logx.js":288,"./pow2.js":293,"./x_is_zero.js":294,"./y_is_huge.js":295,"./y_is_infinite.js":296,"@stdlib/constants/float64/ninf":245,"@stdlib/constants/float64/pinf":246,"@stdlib/math/base/assert/is-infinite":261,"@stdlib/math/base/assert/is-integer":263,"@stdlib/math/base/assert/is-nan":265,"@stdlib/math/base/assert/is-odd":269,"@stdlib/math/base/special/abs":273,"@stdlib/math/base/special/sqrt":299,"@stdlib/number/float64/base/set-low-word":319,"@stdlib/number/float64/base/to-words":325,"@stdlib/number/uint32/base/to-int32":329}],293:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*
*
* ## Notice
*
* The following copyright and license were part of the original implementation available as part of [FreeBSD]{@link https://svnweb.freebsd.org/base/release/9.3.0/lib/msun/src/s_pow.c}. The implementation follows the original, but has been modified for JavaScript.
*
* ```text
* Copyright (C) 2004 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunPro, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ```
*/
'use strict';
// MODULES //
var getHighWord = require( '@stdlib/number/float64/base/get-high-word' );
var setHighWord = require( '@stdlib/number/float64/base/set-high-word' );
var setLowWord = require( '@stdlib/number/float64/base/set-low-word' );
var uint32ToInt32 = require( '@stdlib/number/uint32/base/to-int32' );
var ldexp = require( '@stdlib/math/base/special/ldexp' );
var LN2 = require( '@stdlib/constants/float64/ln-two' );
var BIAS = require( '@stdlib/constants/float64/exponent-bias' );
var polyvalP = require( './polyval_p.js' );
// VARIABLES //
// 0x7fffffff = 2147483647 => 0 11111111111 11111111111111111111
var ABS_MASK = 0x7fffffff|0; // asm type annotation
// 0x000fffff = 1048575 => 0 00000000000 11111111111111111111
var HIGH_SIGNIFICAND_MASK = 0x000fffff|0; // asm type annotation
// 0x00100000 = 1048576 => 0 00000000001 00000000000000000000 => biased exponent: 1 = -1022+1023 => 2^-1022
var HIGH_MIN_NORMAL_EXP = 0x00100000|0; // asm type annotation
// 0x3fe00000 = 1071644672 => 0 01111111110 00000000000000000000 => biased exponent: 1022 = -1+1023 => 2^-1
var HIGH_BIASED_EXP_NEG_1 = 0x3fe00000|0; // asm type annotation
// TODO: consider making into an external constant
var HIGH_NUM_SIGNIFICAND_BITS = 20|0; // asm type annotation
// High: LN2
var LN2_HI = 6.93147182464599609375e-01; // 0x3FE62E43, 0x00000000
// Low: LN2
var LN2_LO = -1.90465429995776804525e-09; // 0xBE205C61, 0x0CA86C39
// MAIN //
/**
* Computes \\(2^{\mathrm{hp} + \mathrm{lp}\\).
*
* @private
* @param {number} j - high word of `hp + lp`
* @param {number} hp - first power summand
* @param {number} lp - second power summand
* @returns {number} function value
*
* @example
* var z = pow2( 1065961648, -0.3398475646972656, -0.000002438187359100815 );
* // returns ~0.79
*/
function pow2( j, hp, lp ) {
var tmp;
var t1;
var t;
var r;
var u;
var v;
var w;
var z;
var n;
var i;
var k;
i = (j & ABS_MASK)|0; // asm type annotation
k = ((i>>HIGH_NUM_SIGNIFICAND_BITS) - BIAS)|0; // asm type annotation
n = 0;
// `|z| > 0.5`, set `n = z+0.5`
if ( i > HIGH_BIASED_EXP_NEG_1 ) {
n = (j + (HIGH_MIN_NORMAL_EXP>>(k+1)))>>>0; // asm type annotation
k = (((n & ABS_MASK)>>HIGH_NUM_SIGNIFICAND_BITS) - BIAS)|0; // new k for n
tmp = ((n & ~(HIGH_SIGNIFICAND_MASK >> k)))>>>0; // asm type annotation
t = setHighWord( 0.0, tmp );
n = (((n & HIGH_SIGNIFICAND_MASK)|HIGH_MIN_NORMAL_EXP) >> (HIGH_NUM_SIGNIFICAND_BITS-k))>>>0; // eslint-disable-line max-len
if ( j < 0 ) {
n = -n;
}
hp -= t;
}
t = lp + hp;
t = setLowWord( t, 0 );
u = t * LN2_HI;
v = ( (lp - (t-hp))*LN2 ) + ( t*LN2_LO );
z = u + v;
w = v - (z - u);
t = z * z;
t1 = z - ( t*polyvalP( t ) );
r = ( (z*t1) / (t1-2.0) ) - ( w + (z*w) );
z = 1.0 - (r - z);
j = getHighWord( z );
j = uint32ToInt32( j );
j += (n << HIGH_NUM_SIGNIFICAND_BITS)>>>0; // asm type annotation
// Check for subnormal output...
if ( (j>>HIGH_NUM_SIGNIFICAND_BITS) <= 0 ) {
z = ldexp( z, n );
} else {
z = setHighWord( z, j );
}
return z;
}
// EXPORTS //
module.exports = pow2;
},{"./polyval_p.js":290,"@stdlib/constants/float64/exponent-bias":237,"@stdlib/constants/float64/ln-two":240,"@stdlib/math/base/special/ldexp":279,"@stdlib/number/float64/base/get-high-word":311,"@stdlib/number/float64/base/set-high-word":317,"@stdlib/number/float64/base/set-low-word":319,"@stdlib/number/uint32/base/to-int32":329}],294:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*
*
* ## Notice
*
* The following copyright and license were part of the original implementation available as part of [FreeBSD]{@link https://svnweb.freebsd.org/base/release/9.3.0/lib/msun/src/s_pow.c}. The implementation follows the original, but has been modified for JavaScript.
*
* ```text
* Copyright (C) 2004 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunPro, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ```
*/
'use strict';
// MODULES //
var isOdd = require( '@stdlib/math/base/assert/is-odd' );
var copysign = require( '@stdlib/math/base/special/copysign' );
var NINF = require( '@stdlib/constants/float64/ninf' );
var PINF = require( '@stdlib/constants/float64/pinf' );
// MAIN //
/**
* Evaluates the exponential function when \\(|x| = 0\\).
*
* @private
* @param {number} x - base
* @param {number} y - exponent
* @returns {number} function value
*
* @example
* var v = pow( 0.0, 2 );
* // returns 0.0
*
* @example
* var v = pow( -0.0, -9 );
* // returns -Infinity
*
* @example
* var v = pow( 0.0, -9 );
* // returns Infinity
*
* @example
* var v = pow( -0.0, 9 );
* // returns 0.0
*
* @example
* var v = pow( 0.0, -Infinity );
* // returns Infinity
*
* @example
* var v = pow( 0.0, Infinity );
* // returns 0.0
*/
function pow( x, y ) {
if ( y === NINF ) {
return PINF;
}
if ( y === PINF ) {
return 0.0;
}
if ( y > 0.0 ) {
if ( isOdd( y ) ) {
return x; // handles +-0
}
return 0.0;
}
// y < 0.0
if ( isOdd( y ) ) {
return copysign( PINF, x ); // handles +-0
}
return PINF;
}
// EXPORTS //
module.exports = pow;
},{"@stdlib/constants/float64/ninf":245,"@stdlib/constants/float64/pinf":246,"@stdlib/math/base/assert/is-odd":269,"@stdlib/math/base/special/copysign":276}],295:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*
*
* ## Notice
*
* The following copyright and license were part of the original implementation available as part of [FreeBSD]{@link https://svnweb.freebsd.org/base/release/9.3.0/lib/msun/src/s_pow.c}. The implementation follows the original, but has been modified for JavaScript.
*
* ```text
* Copyright (C) 2004 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunPro, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ```
*/
'use strict';
// MODULES //
var getHighWord = require( '@stdlib/number/float64/base/get-high-word' );
// VARIABLES //
// 0x7fffffff = 2147483647 => 0 11111111111 11111111111111111111
var ABS_MASK = 0x7fffffff|0; // asm type annotation
// 0x3fefffff = 1072693247 => 0 01111111110 11111111111111111111 => biased exponent: 1022 = -1+1023 => 2^-1
var HIGH_MAX_NEAR_UNITY = 0x3fefffff|0; // asm type annotation
var HUGE = 1.0e300;
var TINY = 1.0e-300;
// MAIN //
/**
* Evaluates the exponential function when \\(|y| > 2^64\\).
*
* @private
* @param {number} x - base
* @param {number} y - exponent
* @returns {number} overflow or underflow result
*
* @example
* var v = pow( 9.0, 3.6893488147419103e19 );
* // returns Infinity
*
* @example
* var v = pow( -3.14, -3.6893488147419103e19 );
* // returns 0.0
*/
function pow( x, y ) {
var ahx;
var hx;
hx = getHighWord( x );
ahx = (hx & ABS_MASK);
if ( ahx <= HIGH_MAX_NEAR_UNITY ) {
if ( y < 0 ) {
// signal overflow...
return HUGE * HUGE;
}
// signal underflow...
return TINY * TINY;
}
// `x` has a biased exponent greater than or equal to `0`...
if ( y > 0 ) {
// signal overflow...
return HUGE * HUGE;
}
// signal underflow...
return TINY * TINY;
}
// EXPORTS //
module.exports = pow;
},{"@stdlib/number/float64/base/get-high-word":311}],296:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var abs = require( '@stdlib/math/base/special/abs' );
var PINF = require( '@stdlib/constants/float64/pinf' );
// MAIN //
/**
* Evaluates the exponential function when \\( y = \pm \infty\\).
*
* @private
* @param {number} x - base
* @param {number} y - exponent
* @returns {number} function value
*
* @example
* var v = pow( -1.0, Infinity );
* // returns NaN
*
* @example
* var v = pow( -1.0, -Infinity );
* // returns NaN
*
* @example
* var v = pow( 1.0, Infinity );
* // returns 1.0
*
* @example
* var v = pow( 1.0, -Infinity );
* // returns 1.0
*
* @example
* var v = pow( 0.5, Infinity );
* // returns 0.0
*
* @example
* var v = pow( 0.5, -Infinity );
* // returns Infinity
*
* @example
* var v = pow( 1.5, -Infinity );
* // returns 0.0
*
* @example
* var v = pow( 1.5, Infinity );
* // returns Infinity
*/
function pow( x, y ) {
if ( x === -1.0 ) {
// Julia (0.4.2) and Python (2.7.9) return `1.0` (WTF???). JavaScript (`Math.pow`), R, and libm return `NaN`. We choose `NaN`, as the value is indeterminate; i.e., we cannot determine whether `y` is odd, even, or somewhere in between.
return (x-x)/(x-x); // signal NaN
}
if ( x === 1.0 ) {
return 1.0;
}
// (|x| > 1 && y === NINF) || (|x| < 1 && y === PINF)
if ( (abs(x) < 1.0) === (y === PINF) ) {
return 0.0;
}
// (|x| > 1 && y === PINF) || (|x| < 1 && y === NINF)
return PINF;
}
// EXPORTS //
module.exports = pow;
},{"@stdlib/constants/float64/pinf":246,"@stdlib/math/base/special/abs":273}],297:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// TODO: implementation
/**
* Round a numeric value to the nearest integer.
*
* @module @stdlib/math/base/special/round
*
* @example
* var round = require( '@stdlib/math/base/special/round' );
*
* var v = round( -4.2 );
* // returns -4.0
*
* v = round( -4.5 );
* // returns -4.0
*
* v = round( -4.6 );
* // returns -5.0
*
* v = round( 9.99999 );
* // returns 10.0
*
* v = round( 9.5 );
* // returns 10.0
*
* v = round( 9.2 );
* // returns 9.0
*
* v = round( 0.0 );
* // returns 0.0
*
* v = round( -0.0 );
* // returns -0.0
*
* v = round( Infinity );
* // returns Infinity
*
* v = round( -Infinity );
* // returns -Infinity
*
* v = round( NaN );
* // returns NaN
*/
// MODULES //
var round = require( './round.js' );
// EXPORTS //
module.exports = round;
},{"./round.js":298}],298:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// TODO: implementation
/**
* Rounds a numeric value to the nearest integer.
*
* @param {number} x - input value
* @returns {number} function value
*
* @example
* var v = round( -4.2 );
* // returns -4.0
*
* @example
* var v = round( -4.5 );
* // returns -4.0
*
* @example
* var v = round( -4.6 );
* // returns -5.0
*
* @example
* var v = round( 9.99999 );
* // returns 10.0
*
* @example
* var v = round( 9.5 );
* // returns 10.0
*
* @example
* var v = round( 9.2 );
* // returns 9.0
*
* @example
* var v = round( 0.0 );
* // returns 0.0
*
* @example
* var v = round( -0.0 );
* // returns -0.0
*
* @example
* var v = round( Infinity );
* // returns Infinity
*
* @example
* var v = round( -Infinity );
* // returns -Infinity
*
* @example
* var v = round( NaN );
* // returns NaN
*/
var round = Math.round; // eslint-disable-line stdlib/no-builtin-math
// EXPORTS //
module.exports = round;
},{}],299:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Compute the principal square root of a double-precision floating-point number.
*
* @module @stdlib/math/base/special/sqrt
*
* @example
* var sqrt = require( '@stdlib/math/base/special/sqrt' );
*
* var v = sqrt( 4.0 );
* // returns 2.0
*
* v = sqrt( 9.0 );
* // returns 3.0
*
* v = sqrt( 0.0 );
* // returns 0.0
*
* v = sqrt( -4.0 );
* // returns NaN
*
* v = sqrt( NaN );
* // returns NaN
*/
// MODULES //
var sqrt = require( './main.js' );
// EXPORTS //
module.exports = sqrt;
},{"./main.js":300}],300:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Compute the principal square root of a double-precision floating-point number.
*
* @type {Function}
* @param {number} x - input value
* @returns {number} principal square root
*
* @example
* var v = sqrt( 4.0 );
* // returns 2.0
*
* v = sqrt( 9.0 );
* // returns 3.0
*
* v = sqrt( 0.0 );
* // returns 0.0
*
* v = sqrt( -4.0 );
* // returns NaN
*
* v = sqrt( NaN );
* // returns NaN
*/
var sqrt = Math.sqrt; // eslint-disable-line stdlib/no-builtin-math
// EXPORTS //
module.exports = sqrt;
},{}],301:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Perform C-like multiplication of two unsigned 32-bit integers.
*
* @module @stdlib/math/base/special/uimul
*
* @example
* var uimul = require( '@stdlib/math/base/special/uimul' );
*
* var v = uimul( 10>>>0, 4>>>0 );
* // returns 40
*/
// MODULES //
var uimul = require( './main.js' );
// EXPORTS //
module.exports = uimul;
},{"./main.js":302}],302:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// VARIABLES //
// Define a mask for the least significant 16 bits (low word): 65535 => 0x0000ffff => 00000000000000001111111111111111
var LOW_WORD_MASK = 0x0000ffff>>>0; // asm type annotation
// MAIN //
/**
* Performs C-like multiplication of two unsigned 32-bit integers.
*
* ## Method
*
* - To emulate C-like multiplication without the aid of 64-bit integers, we recognize that a 32-bit integer can be split into two 16-bit words
*
* ```tex
* a = w_h*2^{16} + w_l
* ```
*
* where \\( w_h \\) is the most significant 16 bits and \\( w_l \\) is the least significant 16 bits. For example, consider the maximum unsigned 32-bit integer \\( 2^{32}-1 \\)
*
* ```binarystring
* 11111111111111111111111111111111
* ```
*
* The 16-bit high word is then
*
* ```binarystring
* 1111111111111111
* ```
*
* and the 16-bit low word
*
* ```binarystring
* 1111111111111111
* ```
*
* If we cast the high word to 32-bit precision and multiply by \\( 2^{16} \\) (equivalent to a 16-bit left shift), then the bit sequence is
*
* ```binarystring
* 11111111111111110000000000000000
* ```
*
* Similarly, upon casting the low word to 32-bit precision, the bit sequence is
*
* ```binarystring
* 00000000000000001111111111111111
* ```
*
* From the rules of binary addition, we recognize that adding the two 32-bit values for the high and low words will return our original value \\( 2^{32}-1 \\).
*
* - Accordingly, the multiplication of two 32-bit integers can be expressed
*
* ```tex
* \begin{align*}
* a \cdot b &= ( a_h \cdot 2^{16} + a_l) \cdot ( b_h \cdot 2^{16} + b_l) \\
* &= a_l \cdot b_l + a_h \cdot b_l \cdot 2^{16} + a_l \cdot b_h \cdot 2^{16} + (a_h \cdot b_h) \cdot 2^{32} \\
* &= a_l \cdot b_l + (a_h \cdot b_l + a_l \cdot b_h) \cdot 2^{16} + (a_h \cdot b_h) \cdot 2^{32}
* \end{align*}
* ```
*
* - We note that multiplying (dividing) an integer by \\( 2^n \\) is equivalent to performing a left (right) shift of \\( n \\) bits.
*
* - Further, as we want to return an integer of the same precision, for a 32-bit integer, the return value will be modulo \\( 2^{32} \\). Stated another way, we only care about the low word of a 64-bit result.
*
* - Accordingly, the last term, being evenly divisible by \\( 2^{32} \\), drops from the equation leaving the remaining two terms as the remainder.
*
* ```tex
* a \cdot b = a_l \cdot b_l + (a_h \cdot b_l + a_l \cdot b_h) << 16
* ```
*
* - Lastly, the second term in the above equation contributes to the middle bits and may cause the product to "overflow". However, we can disregard (`>>>0`) overflow bits due modulo arithmetic, as discussed earlier with regard to the term involving the partial product of high words.
*
*
* @param {uinteger32} a - integer
* @param {uinteger32} b - integer
* @returns {uinteger32} product
*
* @example
* var v = uimul( 10>>>0, 4>>>0 );
* // returns 40
*/
function uimul( a, b ) {
var lbits;
var mbits;
var ha;
var hb;
var la;
var lb;
a >>>= 0; // asm type annotation
b >>>= 0; // asm type annotation
// Isolate the most significant 16-bits:
ha = ( a>>>16 )>>>0; // asm type annotation
hb = ( b>>>16 )>>>0; // asm type annotation
// Isolate the least significant 16-bits:
la = ( a&LOW_WORD_MASK )>>>0; // asm type annotation
lb = ( b&LOW_WORD_MASK )>>>0; // asm type annotation
// Compute partial sums:
lbits = ( la*lb )>>>0; // asm type annotation; no integer overflow possible
mbits = ( ((ha*lb) + (la*hb))<<16 )>>>0; // asm type annotation; possible integer overflow
// The final `>>>0` converts the intermediate sum to an unsigned integer (possible integer overflow during sum):
return ( lbits + mbits )>>>0; // asm type annotation
}
// EXPORTS //
module.exports = uimul;
},{}],303:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Constructor which returns a `Number` object.
*
* @module @stdlib/number/ctor
*
* @example
* var Number = require( '@stdlib/number/ctor' );
*
* var v = new Number( 10.0 );
* // returns <Number>
*/
// MODULES //
var Number = require( './number.js' );
// EXPORTS //
module.exports = Number;
},{"./number.js":304}],304:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// EXPORTS //
module.exports = Number; // eslint-disable-line stdlib/require-globals
},{}],305:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Return an integer corresponding to the unbiased exponent of a double-precision floating-point number.
*
* @module @stdlib/number/float64/base/exponent
*
* @example
* var exponent = require( '@stdlib/number/float64/base/exponent' );
*
* var exp = exponent( 3.14e-307 ); // => 2**-1019 ~ 1e-307
* // returns -1019
*
* exp = exponent( -3.14 );
* // returns 1
*
* exp = exponent( 0.0 );
* // returns -1023
*
* exp = exponent( NaN );
* // returns 1024
*/
// MODULES //
var exponent = require( './main.js' );
// EXPORTS //
module.exports = exponent;
},{"./main.js":306}],306:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var getHighWord = require( '@stdlib/number/float64/base/get-high-word' );
var EXP_MASK = require( '@stdlib/constants/float64/high-word-exponent-mask' );
var BIAS = require( '@stdlib/constants/float64/exponent-bias' );
// MAIN //
/**
* Returns an integer corresponding to the unbiased exponent of a double-precision floating-point number.
*
* @param {number} x - input value
* @returns {integer32} unbiased exponent
*
* @example
* var exp = exponent( 3.14e-307 ); // => 2**-1019 ~ 1e-307
* // returns -1019
*
* @example
* var exp = exponent( -3.14 );
* // returns 1
*
* @example
* var exp = exponent( 0.0 );
* // returns -1023
*
* @example
* var exp = exponent( NaN );
* // returns 1024
*/
function exponent( x ) {
// Extract from the input value a higher order word (unsigned 32-bit integer) which contains the exponent:
var high = getHighWord( x );
// Apply a mask to isolate only the exponent bits and then shift off all bits which are part of the fraction:
high = ( high & EXP_MASK ) >>> 20;
// Remove the bias and return:
return (high - BIAS)|0; // asm type annotation
}
// EXPORTS //
module.exports = exponent;
},{"@stdlib/constants/float64/exponent-bias":237,"@stdlib/constants/float64/high-word-exponent-mask":238,"@stdlib/number/float64/base/get-high-word":311}],307:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Create a double-precision floating-point number from a higher order word (unsigned 32-bit integer) and a lower order word (unsigned 32-bit integer).
*
* @module @stdlib/number/float64/base/from-words
*
* @example
* var fromWords = require( '@stdlib/number/float64/base/from-words' );
*
* var v = fromWords( 1774486211, 2479577218 );
* // returns 3.14e201
*
* v = fromWords( 3221823995, 1413754136 );
* // returns -3.141592653589793
*
* v = fromWords( 0, 0 );
* // returns 0.0
*
* v = fromWords( 2147483648, 0 );
* // returns -0.0
*
* v = fromWords( 2146959360, 0 );
* // returns NaN
*
* v = fromWords( 2146435072, 0 );
* // returns Infinity
*
* v = fromWords( 4293918720, 0 );
* // returns -Infinity
*/
// MODULES //
var fromWords = require( './main.js' );
// EXPORTS //
module.exports = fromWords;
},{"./main.js":309}],308:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isLittleEndian = require( '@stdlib/assert/is-little-endian' );
// MAIN //
var indices;
var HIGH;
var LOW;
if ( isLittleEndian === true ) {
HIGH = 1; // second index
LOW = 0; // first index
} else {
HIGH = 0; // first index
LOW = 1; // second index
}
indices = {
'HIGH': HIGH,
'LOW': LOW
};
// EXPORTS //
module.exports = indices;
},{"@stdlib/assert/is-little-endian":116}],309:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var Uint32Array = require( '@stdlib/array/uint32' );
var Float64Array = require( '@stdlib/array/float64' );
var indices = require( './indices.js' );
// VARIABLES //
var FLOAT64_VIEW = new Float64Array( 1 );
var UINT32_VIEW = new Uint32Array( FLOAT64_VIEW.buffer );
var HIGH = indices.HIGH;
var LOW = indices.LOW;
// MAIN //
/**
* Creates a double-precision floating-point number from a higher order word (unsigned 32-bit integer) and a lower order word (unsigned 32-bit integer).
*
* ## Notes
*
* ```text
* float64 (64 bits)
* f := fraction (significand/mantissa) (52 bits)
* e := exponent (11 bits)
* s := sign bit (1 bit)
*
* |-------- -------- -------- -------- -------- -------- -------- --------|
* | Float64 |
* |-------- -------- -------- -------- -------- -------- -------- --------|
* | Uint32 | Uint32 |
* |-------- -------- -------- -------- -------- -------- -------- --------|
* ```
*
* If little endian (more significant bits last):
*
* ```text
* <-- lower higher -->
* | f7 f6 f5 f4 f3 f2 e2 | f1 |s| e1 |
* ```
*
* If big endian (more significant bits first):
*
* ```text
* <-- higher lower -->
* |s| e1 e2 | f1 f2 f3 f4 f5 f6 f7 |
* ```
*
*
* In which Uint32 should we place the higher order bits? If little endian, the second; if big endian, the first.
*
*
* ## References
*
* - [Open Group][1]
*
* [1]: http://pubs.opengroup.org/onlinepubs/9629399/chap14.htm
*
* @param {uinteger32} high - higher order word (unsigned 32-bit integer)
* @param {uinteger32} low - lower order word (unsigned 32-bit integer)
* @returns {number} floating-point number
*
* @example
* var v = fromWords( 1774486211, 2479577218 );
* // returns 3.14e201
*
* @example
* var v = fromWords( 3221823995, 1413754136 );
* // returns -3.141592653589793
*
* @example
* var v = fromWords( 0, 0 );
* // returns 0.0
*
* @example
* var v = fromWords( 2147483648, 0 );
* // returns -0.0
*
* @example
* var v = fromWords( 2146959360, 0 );
* // returns NaN
*
* @example
* var v = fromWords( 2146435072, 0 );
* // returns Infinity
*
* @example
* var v = fromWords( 4293918720, 0 );
* // returns -Infinity
*/
function fromWords( high, low ) {
UINT32_VIEW[ HIGH ] = high;
UINT32_VIEW[ LOW ] = low;
return FLOAT64_VIEW[ 0 ];
}
// EXPORTS //
module.exports = fromWords;
},{"./indices.js":308,"@stdlib/array/float64":5,"@stdlib/array/uint32":23}],310:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isLittleEndian = require( '@stdlib/assert/is-little-endian' );
// MAIN //
var HIGH;
if ( isLittleEndian === true ) {
HIGH = 1; // second index
} else {
HIGH = 0; // first index
}
// EXPORTS //
module.exports = HIGH;
},{"@stdlib/assert/is-little-endian":116}],311:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Return an unsigned 32-bit integer corresponding to the more significant 32 bits of a double-precision floating-point number.
*
* @module @stdlib/number/float64/base/get-high-word
*
* @example
* var getHighWord = require( '@stdlib/number/float64/base/get-high-word' );
*
* var w = getHighWord( 3.14e201 ); // => 01101001110001001000001011000011
* // returns 1774486211
*/
// MODULES //
var getHighWord = require( './main.js' );
// EXPORTS //
module.exports = getHighWord;
},{"./main.js":312}],312:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var Uint32Array = require( '@stdlib/array/uint32' );
var Float64Array = require( '@stdlib/array/float64' );
var HIGH = require( './high.js' );
// VARIABLES //
var FLOAT64_VIEW = new Float64Array( 1 );
var UINT32_VIEW = new Uint32Array( FLOAT64_VIEW.buffer );
// MAIN //
/**
* Returns an unsigned 32-bit integer corresponding to the more significant 32 bits of a double-precision floating-point number.
*
* ## Notes
*
* ```text
* float64 (64 bits)
* f := fraction (significand/mantissa) (52 bits)
* e := exponent (11 bits)
* s := sign bit (1 bit)
*
* |-------- -------- -------- -------- -------- -------- -------- --------|
* | Float64 |
* |-------- -------- -------- -------- -------- -------- -------- --------|
* | Uint32 | Uint32 |
* |-------- -------- -------- -------- -------- -------- -------- --------|
* ```
*
* If little endian (more significant bits last):
*
* ```text
* <-- lower higher -->
* | f7 f6 f5 f4 f3 f2 e2 | f1 |s| e1 |
* ```
*
* If big endian (more significant bits first):
*
* ```text
* <-- higher lower -->
* |s| e1 e2 | f1 f2 f3 f4 f5 f6 f7 |
* ```
*
* In which Uint32 can we find the higher order bits? If little endian, the second; if big endian, the first.
*
*
* ## References
*
* - [Open Group][1]
*
* [1]: http://pubs.opengroup.org/onlinepubs/9629399/chap14.htm
*
* @param {number} x - input value
* @returns {uinteger32} higher order word
*
* @example
* var w = getHighWord( 3.14e201 ); // => 01101001110001001000001011000011
* // returns 1774486211
*/
function getHighWord( x ) {
FLOAT64_VIEW[ 0 ] = x;
return UINT32_VIEW[ HIGH ];
}
// EXPORTS //
module.exports = getHighWord;
},{"./high.js":310,"@stdlib/array/float64":5,"@stdlib/array/uint32":23}],313:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Return a normal number `y` and exponent `exp` satisfying \\(x = y \cdot 2^\mathrm{exp}\\).
*
* @module @stdlib/number/float64/base/normalize
*
* @example
* var normalize = require( '@stdlib/number/float64/base/normalize' );
* var pow = require( '@stdlib/math/base/special/pow' );
*
* var out = normalize( 3.14e-319 );
* // returns [ 1.4141234400356668e-303, -52 ]
*
* var y = out[ 0 ];
* var exp = out[ 1 ];
*
* var bool = ( y*pow(2.0,exp) === 3.14e-319 );
* // returns true
*
* @example
* var Float64Array = require( '@stdlib/array/float64' );
* var normalize = require( '@stdlib/number/float64/base/normalize' );
*
* var out = new Float64Array( 2 );
*
* var v = normalize( out, 3.14e-319 );
* // returns <Float64Array>[ 1.4141234400356668e-303, -52 ]
*
* var bool = ( v === out );
* // returns true
*/
// MODULES //
var normalize = require( './main.js' );
// EXPORTS //
module.exports = normalize;
},{"./main.js":314}],314:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var fcn = require( './normalize.js' );
// MAIN //
/**
* Returns a normal number `y` and exponent `exp` satisfying \\(x = y \cdot 2^\mathrm{exp}\\).
*
* @param {(Array|TypedArray|Object)} [out] - output array
* @param {number} x - input value
* @returns {(Array|TypedArray|Object)} output array
*
* @example
* var pow = require( '@stdlib/math/base/special/pow' );
*
* var out = normalize( [ 0.0, 0 ], 3.14e-319 );
* // returns [ 1.4141234400356668e-303, -52 ]
*
* var y = out[ 0 ];
* var exp = out[ 1 ];
*
* var bool = ( y*pow(2.0,exp) === 3.14e-319 );
* // returns true
*
* @example
* var Float64Array = require( '@stdlib/array/float64' );
* var pow = require( '@stdlib/math/base/special/pow' );
*
* var out = new Float64Array( 2 );
*
* var v = normalize( out, 3.14e-319 );
* // returns <Float64Array>[ 1.4141234400356668e-303, -52 ]
*
* var bool = ( v === out );
* // returns true
*
* @example
* var out = normalize( [ 0.0, 0 ], 0.0 );
* // returns [ 0.0, 0 ]
*
* @example
* var out = normalize( [ 0.0, 0 ], Infinity );
* // returns [ Infinity, 0 ]
*
* @example
* var out = normalize( [ 0.0, 0 ], -Infinity );
* // returns [ -Infinity, 0 ]
*
* @example
* var out = normalize( [ 0.0, 0 ], NaN );
* // returns [ NaN, 0 ]
*/
function normalize( out, x ) {
if ( arguments.length === 1 ) {
return fcn( [ 0.0, 0 ], out );
}
return fcn( out, x );
}
// EXPORTS //
module.exports = normalize;
},{"./normalize.js":315}],315:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var FLOAT64_SMALLEST_NORMAL = require( '@stdlib/constants/float64/smallest-normal' );
var isInfinite = require( '@stdlib/math/base/assert/is-infinite' );
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var abs = require( '@stdlib/math/base/special/abs' );
// VARIABLES //
// (1<<52)
var SCALAR = 4503599627370496;
// MAIN //
/**
* Returns a normal number `y` and exponent `exp` satisfying \\(x = y \cdot 2^\mathrm{exp}\\).
*
* @private
* @param {(Array|TypedArray|Object)} out - output array
* @param {number} x - input value
* @returns {(Array|TypedArray|Object)} output array
*
* @example
* var pow = require( '@stdlib/math/base/special/pow' );
*
* var out = normalize( [ 0.0, 0 ], 3.14e-319 );
* // returns [ 1.4141234400356668e-303, -52 ]
*
* var y = out[ 0 ];
* var exp = out[ 1 ];
*
* var bool = ( y*pow(2.0,exp) === 3.14e-319 );
* // returns true
*
* @example
* var out = normalize( [ 0.0, 0 ], 0.0 );
* // returns [ 0.0, 0 ];
*
* @example
* var out = normalize( [ 0.0, 0 ], Infinity );
* // returns [ Infinity, 0 ]
*
* @example
* var out = normalize( [ 0.0, 0 ], -Infinity );
* // returns [ -Infinity, 0 ]
*
* @example
* var out = normalize( [ 0.0, 0 ], NaN );
* // returns [ NaN, 0 ]
*/
function normalize( out, x ) {
if ( isnan( x ) || isInfinite( x ) ) {
out[ 0 ] = x;
out[ 1 ] = 0;
return out;
}
if ( x !== 0.0 && abs( x ) < FLOAT64_SMALLEST_NORMAL ) {
out[ 0 ] = x * SCALAR;
out[ 1 ] = -52;
return out;
}
out[ 0 ] = x;
out[ 1 ] = 0;
return out;
}
// EXPORTS //
module.exports = normalize;
},{"@stdlib/constants/float64/smallest-normal":247,"@stdlib/math/base/assert/is-infinite":261,"@stdlib/math/base/assert/is-nan":265,"@stdlib/math/base/special/abs":273}],316:[function(require,module,exports){
arguments[4][310][0].apply(exports,arguments)
},{"@stdlib/assert/is-little-endian":116,"dup":310}],317:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Set the more significant 32 bits of a double-precision floating-point number.
*
* @module @stdlib/number/float64/base/set-high-word
*
* @example
* var setHighWord = require( '@stdlib/number/float64/base/set-high-word' );
*
* var high = 5 >>> 0; // => 0 00000000000 00000000000000000101
*
* var y = setHighWord( 3.14e201, high ); // => 0 00000000000 0000000000000000010110010011110010110101100010000010
* // returns 1.18350528745e-313
*
* @example
* var setHighWord = require( '@stdlib/number/float64/base/set-high-word' );
* var PINF = require( '@stdlib/constants/float64/pinf' ); // => 0 11111111111 00000000000000000000 00000000000000000000000000000000
*
* var high = 1072693248 >>> 0; // => 0 01111111111 00000000000000000000
*
* // Set the higher order bits of `+infinity` to return `1`:
* var y = setHighWord( PINF, high ); => 0 01111111111 0000000000000000000000000000000000000000000000000000
* // returns 1.0
*/
// MODULES //
var setHighWord = require( './main.js' );
// EXPORTS //
module.exports = setHighWord;
},{"./main.js":318}],318:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var Uint32Array = require( '@stdlib/array/uint32' );
var Float64Array = require( '@stdlib/array/float64' );
var HIGH = require( './high.js' );
// VARIABLES //
var FLOAT64_VIEW = new Float64Array( 1 );
var UINT32_VIEW = new Uint32Array( FLOAT64_VIEW.buffer );
// MAIN //
/**
* Sets the more significant 32 bits of a double-precision floating-point number.
*
* ## Notes
*
* ```text
* float64 (64 bits)
* f := fraction (significand/mantissa) (52 bits)
* e := exponent (11 bits)
* s := sign bit (1 bit)
*
* |-------- -------- -------- -------- -------- -------- -------- --------|
* | Float64 |
* |-------- -------- -------- -------- -------- -------- -------- --------|
* | Uint32 | Uint32 |
* |-------- -------- -------- -------- -------- -------- -------- --------|
* ```
*
* If little endian (more significant bits last):
*
* ```text
* <-- lower higher -->
* | f7 f6 f5 f4 f3 f2 e2 | f1 |s| e1 |
* ```
*
* If big endian (more significant bits first):
*
* ```text
* <-- higher lower -->
* |s| e1 e2 | f1 f2 f3 f4 f5 f6 f7 |
* ```
*
* In which Uint32 can we find the higher order bits? If little endian, the second; if big endian, the first.
*
*
* ## References
*
* - [Open Group][1]
*
* [1]: http://pubs.opengroup.org/onlinepubs/9629399/chap14.htm
*
* @param {number} x - double
* @param {uinteger32} high - unsigned 32-bit integer to replace the higher order word of `x`
* @returns {number} double having the same lower order word as `x`
*
* @example
* var high = 5 >>> 0; // => 0 00000000000 00000000000000000101
*
* var y = setHighWord( 3.14e201, high ); // => 0 00000000000 0000000000000000010110010011110010110101100010000010
* // returns 1.18350528745e-313
*
* @example
* var PINF = require( '@stdlib/constants/float64/pinf' ); // => 0 11111111111 00000000000000000000 00000000000000000000000000000000
*
* var high = 1072693248 >>> 0; // => 0 01111111111 00000000000000000000
*
* // Set the higher order bits of `+infinity` to return `1`:
* var y = setHighWord( PINF, high ); // => 0 01111111111 0000000000000000000000000000000000000000000000000000
* // returns 1.0
*/
function setHighWord( x, high ) {
FLOAT64_VIEW[ 0 ] = x;
UINT32_VIEW[ HIGH ] = ( high >>> 0 ); // identity bit shift to ensure integer
return FLOAT64_VIEW[ 0 ];
}
// EXPORTS //
module.exports = setHighWord;
},{"./high.js":316,"@stdlib/array/float64":5,"@stdlib/array/uint32":23}],319:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Set the less significant 32 bits of a double-precision floating-point number.
*
* @module @stdlib/number/float64/base/set-low-word
*
* @example
* var setLowWord = require( '@stdlib/number/float64/base/set-low-word' );
*
* var low = 5 >>> 0; // => 00000000000000000000000000000101
*
* var x = 3.14e201; // => 0 11010011100 01001000001011000011 10010011110010110101100010000010
*
* var y = setLowWord( x, low ); // => 0 11010011100 01001000001011000011 00000000000000000000000000000101
* // returns 3.139998651394392e+201
*
* @example
* var setLowWord = require( '@stdlib/number/float64/base/set-low-word' );
* var PINF = require( '@stdlib/constants/float64/pinf' );
* var NINF = require( '@stdlib/constants/float64/ninf' );
*
* var low = 12345678;
*
* var y = setLowWord( PINF, low );
* // returns NaN
*
* y = setLowWord( NINF, low );
* // returns NaN
*
* y = setLowWord( NaN, low );
* // returns NaN
*/
// MODULES //
var setLowWord = require( './main.js' );
// EXPORTS //
module.exports = setLowWord;
},{"./main.js":321}],320:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isLittleEndian = require( '@stdlib/assert/is-little-endian' );
// MAIN //
var LOW;
if ( isLittleEndian === true ) {
LOW = 0; // first index
} else {
LOW = 1; // second index
}
// EXPORTS //
module.exports = LOW;
},{"@stdlib/assert/is-little-endian":116}],321:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var Uint32Array = require( '@stdlib/array/uint32' );
var Float64Array = require( '@stdlib/array/float64' );
var LOW = require( './low.js' );
// VARIABLES //
var FLOAT64_VIEW = new Float64Array( 1 );
var UINT32_VIEW = new Uint32Array( FLOAT64_VIEW.buffer );
// MAIN //
/**
* Sets the less significant 32 bits of a double-precision floating-point number.
*
* ## Notes
*
* ```text
* float64 (64 bits)
* f := fraction (significand/mantissa) (52 bits)
* e := exponent (11 bits)
* s := sign bit (1 bit)
*
* |-------- -------- -------- -------- -------- -------- -------- --------|
* | Float64 |
* |-------- -------- -------- -------- -------- -------- -------- --------|
* | Uint32 | Uint32 |
* |-------- -------- -------- -------- -------- -------- -------- --------|
* ```
*
* If little endian (more significant bits last):
*
* ```text
* <-- lower higher -->
* | f7 f6 f5 f4 f3 f2 e2 | f1 |s| e1 |
* ```
*
* If big endian (more significant bits first):
*
* ```text
* <-- higher lower -->
* |s| e1 e2 | f1 f2 f3 f4 f5 f6 f7 |
* ```
*
* In which Uint32 can we find the lower order bits? If little endian, the first; if big endian, the second.
*
*
* ## References
*
* - [Open Group][1]
*
* [1]: http://pubs.opengroup.org/onlinepubs/9629399/chap14.htm
*
* @param {number} x - double
* @param {uinteger32} low - unsigned 32-bit integer to replace the lower order word of `x`
* @returns {number} double having the same higher order word as `x`
*
* @example
* var low = 5 >>> 0; // => 00000000000000000000000000000101
*
* var x = 3.14e201; // => 0 11010011100 01001000001011000011 10010011110010110101100010000010
*
* var y = setLowWord( x, low ); // => 0 11010011100 01001000001011000011 00000000000000000000000000000101
* // returns 3.139998651394392e+201
*
* @example
* var PINF = require( '@stdlib/constants/float64/pinf' );
* var NINF = require( '@stdlib/constants/float64/ninf' );
*
* var low = 12345678;
*
* var y = setLowWord( PINF, low );
* // returns NaN
*
* y = setLowWord( NINF, low );
* // returns NaN
*
* y = setLowWord( NaN, low );
* // returns NaN
*/
function setLowWord( x, low ) {
FLOAT64_VIEW[ 0 ] = x;
UINT32_VIEW[ LOW ] = ( low >>> 0 ); // identity bit shift to ensure integer
return FLOAT64_VIEW[ 0 ];
}
// EXPORTS //
module.exports = setLowWord;
},{"./low.js":320,"@stdlib/array/float64":5,"@stdlib/array/uint32":23}],322:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Convert a double-precision floating-point number to the nearest single-precision floating-point number.
*
* @module @stdlib/number/float64/base/to-float32
*
* @example
* var float64ToFloat32 = require( '@stdlib/number/float64/base/to-float32' );
*
* var y = float64ToFloat32( 1.337 );
* // returns 1.3370000123977661
*/
// MODULES //
var float64ToFloat32 = require( './main.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
if ( typeof float64ToFloat32 !== 'function' ) {
float64ToFloat32 = polyfill;
}
// EXPORTS //
module.exports = float64ToFloat32;
},{"./main.js":323,"./polyfill.js":324}],323:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var fround = ( typeof Math.fround === 'function' ) ? Math.fround : null; // eslint-disable-line stdlib/no-builtin-math
// EXPORTS //
module.exports = fround;
},{}],324:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var Float32Array = require( '@stdlib/array/float32' );
// VARIABLES //
var FLOAT32_VIEW = new Float32Array( 1 );
// MAIN //
/**
* Converts a double-precision floating-point number to the nearest single-precision floating-point number.
*
* @param {number} x - double-precision floating-point number
* @returns {number} nearest single-precision floating-point number
*
* @example
* var y = float64ToFloat32( 1.337 );
* // returns 1.3370000123977661
*/
function float64ToFloat32( x ) {
FLOAT32_VIEW[ 0 ] = x;
return FLOAT32_VIEW[ 0 ];
}
// EXPORTS //
module.exports = float64ToFloat32;
},{"@stdlib/array/float32":2}],325:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Split a double-precision floating-point number into a higher order word (unsigned 32-bit integer) and a lower order word (unsigned 32-bit integer).
*
* @module @stdlib/number/float64/base/to-words
*
* @example
* var toWords = require( '@stdlib/number/float64/base/to-words' );
*
* var w = toWords( 3.14e201 );
* // returns [ 1774486211, 2479577218 ]
*
* @example
* var Uint32Array = require( '@stdlib/array/uint32' );
* var toWords = require( '@stdlib/number/float64/base/to-words' );
*
* var out = new Uint32Array( 2 );
*
* var w = toWords( out, 3.14e201 );
* // returns <Uint32Array>[ 1774486211, 2479577218 ]
*
* var bool = ( w === out );
* // returns true
*/
// MODULES //
var toWords = require( './main.js' );
// EXPORTS //
module.exports = toWords;
},{"./main.js":327}],326:[function(require,module,exports){
arguments[4][308][0].apply(exports,arguments)
},{"@stdlib/assert/is-little-endian":116,"dup":308}],327:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var fcn = require( './to_words.js' );
// MAIN //
/**
* Splits a double-precision floating-point number into a higher order word (unsigned 32-bit integer) and a lower order word (unsigned 32-bit integer).
*
* @param {(Array|TypedArray|Object)} [out] - output array
* @param {number} x - input value
* @returns {(Array|TypedArray|Object)} output array
*
* @example
* var w = toWords( 3.14e201 );
* // returns [ 1774486211, 2479577218 ]
*
* @example
* var Uint32Array = require( '@stdlib/array/uint32' );
*
* var out = new Uint32Array( 2 );
*
* var w = toWords( out, 3.14e201 );
* // returns <Uint32Array>[ 1774486211, 2479577218 ]
*
* var bool = ( w === out );
* // returns true
*/
function toWords( out, x ) {
if ( arguments.length === 1 ) {
return fcn( [ 0, 0 ], out );
}
return fcn( out, x );
}
// EXPORTS //
module.exports = toWords;
},{"./to_words.js":328}],328:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var Uint32Array = require( '@stdlib/array/uint32' );
var Float64Array = require( '@stdlib/array/float64' );
var indices = require( './indices.js' );
// VARIABLES //
var FLOAT64_VIEW = new Float64Array( 1 );
var UINT32_VIEW = new Uint32Array( FLOAT64_VIEW.buffer );
var HIGH = indices.HIGH;
var LOW = indices.LOW;
// MAIN //
/**
* Splits a double-precision floating-point number into a higher order word (unsigned 32-bit integer) and a lower order word (unsigned 32-bit integer).
*
* ## Notes
*
* ```text
* float64 (64 bits)
* f := fraction (significand/mantissa) (52 bits)
* e := exponent (11 bits)
* s := sign bit (1 bit)
*
* |-------- -------- -------- -------- -------- -------- -------- --------|
* | Float64 |
* |-------- -------- -------- -------- -------- -------- -------- --------|
* | Uint32 | Uint32 |
* |-------- -------- -------- -------- -------- -------- -------- --------|
* ```
*
* If little endian (more significant bits last):
*
* ```text
* <-- lower higher -->
* | f7 f6 f5 f4 f3 f2 e2 | f1 |s| e1 |
* ```
*
* If big endian (more significant bits first):
*
* ```text
* <-- higher lower -->
* |s| e1 e2 | f1 f2 f3 f4 f5 f6 f7 |
* ```
*
* In which Uint32 can we find the higher order bits? If little endian, the second; if big endian, the first.
*
*
* ## References
*
* - [Open Group][1]
*
* [1]: http://pubs.opengroup.org/onlinepubs/9629399/chap14.htm
*
*
* @private
* @param {(Array|TypedArray|Object)} out - output array
* @param {number} x - input value
* @returns {(Array|TypedArray|Object)} output array
*
* @example
* var Uint32Array = require( '@stdlib/array/uint32' );
*
* var out = new Uint32Array( 2 );
*
* var w = toWords( out, 3.14e201 );
* // returns <Uint32Array>[ 1774486211, 2479577218 ]
*
* var bool = ( w === out );
* // returns true
*/
function toWords( out, x ) {
FLOAT64_VIEW[ 0 ] = x;
out[ 0 ] = UINT32_VIEW[ HIGH ];
out[ 1 ] = UINT32_VIEW[ LOW ];
return out;
}
// EXPORTS //
module.exports = toWords;
},{"./indices.js":326,"@stdlib/array/float64":5,"@stdlib/array/uint32":23}],329:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Convert an unsigned 32-bit integer to a signed 32-bit integer.
*
* @module @stdlib/number/uint32/base/to-int32
*
* @example
* var float64ToUint32 = require( '@stdlib/number/float64/base/to-uint32' );
* var uint32ToInt32 = require( '@stdlib/number/uint32/base/to-int32' );
*
* var y = uint32ToInt32( float64ToUint32( 4294967295 ) );
* // returns -1
*
* y = uint32ToInt32( float64ToUint32( 3 ) );
* // returns 3
*/
// MODULES //
var uint32ToInt32 = require( './main.js' );
// EXPORTS //
module.exports = uint32ToInt32;
},{"./main.js":330}],330:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Converts an unsigned 32-bit integer to a signed 32-bit integer.
*
* @param {uinteger32} x - unsigned 32-bit integer
* @returns {integer32} signed 32-bit integer
*
* @example
* var float64ToUint32 = require( '@stdlib/number/float64/base/to-uint32' );
* var y = uint32ToInt32( float64ToUint32( 4294967295 ) );
* // returns -1
*
* @example
* var float64ToUint32 = require( '@stdlib/number/float64/base/to-uint32' );
* var y = uint32ToInt32( float64ToUint32( 3 ) );
* // returns 3
*/
function uint32ToInt32( x ) {
// NOTE: we could also use typed-arrays to achieve the same end.
return x|0; // asm type annotation
}
// EXPORTS //
module.exports = uint32ToInt32;
},{}],331:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isnan = require( '@stdlib/math/base/assert/is-nan' );
// VARIABLES //
var NUM_WARMUPS = 8;
// MAIN //
/**
* Initializes a shuffle table.
*
* @private
* @param {PRNG} rand - pseudorandom number generator
* @param {Int32Array} table - table
* @param {PositiveInteger} N - table size
* @throws {Error} PRNG returned `NaN`
* @returns {NumberArray} shuffle table
*/
function createTable( rand, table, N ) {
var v;
var i;
// "warm-up" the PRNG...
for ( i = 0; i < NUM_WARMUPS; i++ ) {
v = rand();
// Prevent the above loop from being discarded by the compiler...
if ( isnan( v ) ) {
throw new Error( 'unexpected error. PRNG returned `NaN`.' );
}
}
// Initialize the shuffle table...
for ( i = N-1; i >= 0; i-- ) {
table[ i ] = rand();
}
return table;
}
// EXPORTS //
module.exports = createTable;
},{"@stdlib/math/base/assert/is-nan":265}],332:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
/* eslint-disable max-len */
'use strict';
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var setReadOnlyAccessor = require( '@stdlib/utils/define-nonenumerable-read-only-accessor' );
var setReadWriteAccessor = require( '@stdlib/utils/define-nonenumerable-read-write-accessor' );
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var isObject = require( '@stdlib/assert/is-plain-object' );
var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive;
var isCollection = require( '@stdlib/assert/is-collection' );
var isPositiveInteger = require( '@stdlib/assert/is-positive-integer' ).isPrimitive;
var isInt32Array = require( '@stdlib/assert/is-int32array' );
var gcopy = require( '@stdlib/blas/base/gcopy' );
var floor = require( '@stdlib/math/base/special/floor' );
var Int32Array = require( '@stdlib/array/int32' );
var INT32_MAX = require( '@stdlib/constants/int32/max' );
var typedarray2json = require( '@stdlib/array/to-json' );
var createTable = require( './create_table.js' );
var randint32 = require( './rand_int32.js' );
// VARIABLES //
var NORMALIZATION_CONSTANT = (INT32_MAX - 1)|0; // asm type annotation
var MAX_SEED = (INT32_MAX - 1)|0; // asm type annotation
var A = 16807|0; // asm type annotation
// Define the number of elements in the shuffle table:
var TABLE_LENGTH = 32;
// Define the state array schema version:
var STATE_ARRAY_VERSION = 1; // NOTE: anytime the state array schema changes, this value should be incremented!!!
// Define the number of sections in the state array:
var NUM_STATE_SECTIONS = 3; // table, other, seed
// Define the index offset of the "table" section in the state array:
var TABLE_SECTION_OFFSET = 2; // | version | num_sections | table_length | ...table | other_length | shuffle_state | prng_state | seed_length | ...seed |
// Define the index offset of the "state" section in the state array:
var STATE_SECTION_OFFSET = TABLE_LENGTH + 3; // | version | num_sections | table_length | ...table | state_length | shuffle_state | prng_state | seed_length | ...seed |
// Define the index offset of the seed section in the state array:
var SEED_SECTION_OFFSET = TABLE_LENGTH + 6; // | version | num_sections | table_length | ...table | state_length | shuffle_state | prng_state | seed_length | ...seed |
// Define the length of the "fixed" length portion of the state array:
var STATE_FIXED_LENGTH = TABLE_LENGTH + 7; // 1 (version) + 1 (num_sections) + 1 (table_length) + TABLE_LENGTH (table) + 1 (state_length) + 1 (shuffle_state) + 1 (prng_state) + 1 (seed_length)
// Define the indices for the shuffle table and PRNG states:
var SHUFFLE_STATE = STATE_SECTION_OFFSET + 1;
var PRNG_STATE = STATE_SECTION_OFFSET + 2;
// FUNCTIONS //
/**
* Verifies state array integrity.
*
* @private
* @param {Int32Array} state - state array
* @param {boolean} FLG - flag indicating whether the state array was provided as an option (true) or an argument (false)
* @returns {(Error|null)} an error or `null`
*/
function verifyState( state, FLG ) {
var s1;
if ( FLG ) {
s1 = 'option';
} else {
s1 = 'argument';
}
// The state array must have a minimum length...
if ( state.length < STATE_FIXED_LENGTH+1 ) {
return new RangeError( 'invalid '+s1+'. `state` array has insufficient length.' );
}
// The first element of the state array must equal the supported state array schema version...
if ( state[ 0 ] !== STATE_ARRAY_VERSION ) {
return new RangeError( 'invalid '+s1+'. `state` array has an incompatible schema version. Expected: '+STATE_ARRAY_VERSION+'. Actual: '+state[ 0 ]+'.' );
}
// The second element of the state array must contain the number of sections...
if ( state[ 1 ] !== NUM_STATE_SECTIONS ) {
return new RangeError( 'invalid '+s1+'. `state` array has an incompatible number of sections. Expected: '+NUM_STATE_SECTIONS+'. Actual: '+state[ 1 ]+'.' );
}
// The length of the "table" section must equal `TABLE_LENGTH`...
if ( state[ TABLE_SECTION_OFFSET ] !== TABLE_LENGTH ) {
return new RangeError( 'invalid '+s1+'. `state` array has an incompatible table length. Expected: '+TABLE_LENGTH+'. Actual: '+state[ TABLE_SECTION_OFFSET ]+'.' );
}
// The length of the "state" section must equal `2`...
if ( state[ STATE_SECTION_OFFSET ] !== 2 ) {
return new RangeError( 'invalid '+s1+'. `state` array has an incompatible state length. Expected: '+(2).toString()+'. Actual: '+state[ STATE_SECTION_OFFSET ]+'.' );
}
// The length of the "seed" section much match the empirical length...
if ( state[ SEED_SECTION_OFFSET ] !== state.length-STATE_FIXED_LENGTH ) {
return new RangeError( 'invalid '+s1+'. `state` array length is incompatible with seed section length. Expected: '+(state.length-STATE_FIXED_LENGTH)+'. Actual: '+state[ SEED_SECTION_OFFSET ]+'.' );
}
return null;
}
// MAIN //
/**
* Returns a linear congruential pseudorandom number generator (LCG) whose output is shuffled.
*
* @param {Options} [options] - options
* @param {PRNGSeedMINSTD} [options.seed] - pseudorandom number generator seed
* @param {PRNGStateMINSTD} [options.state] - pseudorandom number generator state
* @param {boolean} [options.copy=true] - boolean indicating whether to copy a provided pseudorandom number generator state
* @throws {TypeError} options argument must be an object
* @throws {TypeError} a seed must be either a positive integer less than the maximum signed 32-bit integer or an array-like object containing integers less than the maximum signed 32-bit integer
* @throws {RangeError} a numeric seed must be a positive integer less than the maximum signed 32-bit integer
* @throws {TypeError} state must be an `Int32Array`
* @throws {Error} must provide a valid state
* @throws {TypeError} `copy` option must be a boolean
* @returns {PRNG} shuffled LCG PRNG
*
* @example
* var minstd = factory();
*
* var v = minstd();
* // returns <number>
*
* @example
* // Return a seeded LCG:
* var minstd = factory({
* 'seed': 1234
* });
*
* var v = minstd();
* // returns 1421600654
*/
function factory( options ) {
var STATE;
var state;
var opts;
var seed;
var slen;
var err;
opts = {};
if ( arguments.length ) {
if ( !isObject( options ) ) {
throw new TypeError( 'invalid argument. Options argument must be an object. Value: `' + options + '`.' );
}
if ( hasOwnProp( options, 'copy' ) ) {
opts.copy = options.copy;
if ( !isBoolean( options.copy ) ) {
throw new TypeError( 'invalid option. `copy` option must be a boolean. Option: `' + options.copy + '`.' );
}
}
if ( hasOwnProp( options, 'state' ) ) {
state = options.state;
opts.state = true;
if ( !isInt32Array( state ) ) {
throw new TypeError( 'invalid option. `state` option must be an Int32Array. Option: `' + state + '`.' );
}
err = verifyState( state, true );
if ( err ) {
throw err;
}
if ( opts.copy === false ) {
STATE = state;
} else {
STATE = new Int32Array( state.length );
gcopy( state.length, state, 1, STATE, 1 );
}
// Create a state (table) "view":
state = new Int32Array( STATE.buffer, STATE.byteOffset+((TABLE_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), TABLE_LENGTH );
// Create a seed "view":
seed = new Int32Array( STATE.buffer, STATE.byteOffset+((SEED_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), state[ SEED_SECTION_OFFSET ] );
}
// If provided a PRNG state, we ignore the `seed` option...
if ( seed === void 0 ) {
if ( hasOwnProp( options, 'seed' ) ) {
seed = options.seed;
opts.seed = true;
if ( isPositiveInteger( seed ) ) {
if ( seed > MAX_SEED ) {
throw new RangeError( 'invalid option. `seed` option must be a positive integer less than the maximum signed 32-bit integer. Option: `' + seed + '`.' );
}
seed |= 0; // asm type annotation
} else if ( isCollection( seed ) && seed.length > 0 ) {
slen = seed.length;
STATE = new Int32Array( STATE_FIXED_LENGTH+slen );
// Initialize sections:
STATE[ 0 ] = STATE_ARRAY_VERSION;
STATE[ 1 ] = NUM_STATE_SECTIONS;
STATE[ TABLE_SECTION_OFFSET ] = TABLE_LENGTH;
STATE[ STATE_SECTION_OFFSET ] = 2;
STATE[ PRNG_STATE ] = seed[ 0 ];
STATE[ SEED_SECTION_OFFSET ] = slen;
// Copy the provided seed array to prevent external mutation, as mutation would lead to an inability to reproduce PRNG values according to the PRNG's stated seed:
gcopy.ndarray( slen, seed, 1, 0, STATE, 1, SEED_SECTION_OFFSET+1 );
// Create a state (table) "view":
state = new Int32Array( STATE.buffer, STATE.byteOffset+((TABLE_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), TABLE_LENGTH );
// Create a seed "view":
seed = new Int32Array( STATE.buffer, STATE.byteOffset+((SEED_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), slen );
// Initialize the internal PRNG state:
state = createTable( minstd, state, TABLE_LENGTH );
STATE[ SHUFFLE_STATE ] = state[ 0 ];
} else {
throw new TypeError( 'invalid option. `seed` option must be either a positive integer less than the maximum signed 32-bit integer or an array-like object containing integer values less than the maximum signed 32-bit integer. Option: `' + seed + '`.' );
}
} else {
seed = randint32()|0; // asm type annotation
}
}
} else {
seed = randint32()|0; // asm type annotation
}
if ( state === void 0 ) {
STATE = new Int32Array( STATE_FIXED_LENGTH+1 );
// Initialize sections:
STATE[ 0 ] = STATE_ARRAY_VERSION;
STATE[ 1 ] = NUM_STATE_SECTIONS;
STATE[ TABLE_SECTION_OFFSET ] = TABLE_LENGTH;
STATE[ STATE_SECTION_OFFSET ] = 2;
STATE[ PRNG_STATE ] = seed;
STATE[ SEED_SECTION_OFFSET ] = 1;
STATE[ SEED_SECTION_OFFSET+1 ] = seed;
// Create a state (table) "view":
state = new Int32Array( STATE.buffer, STATE.byteOffset+((TABLE_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), TABLE_LENGTH );
// Create a seed "view":
seed = new Int32Array( STATE.buffer, STATE.byteOffset+((SEED_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), 1 );
// Initialize the internal PRNG state:
state = createTable( minstd, state, TABLE_LENGTH );
STATE[ SHUFFLE_STATE ] = state[ 0 ];
}
setReadOnly( minstdShuffle, 'NAME', 'minstd-shuffle' );
setReadOnlyAccessor( minstdShuffle, 'seed', getSeed );
setReadOnlyAccessor( minstdShuffle, 'seedLength', getSeedLength );
setReadWriteAccessor( minstdShuffle, 'state', getState, setState );
setReadOnlyAccessor( minstdShuffle, 'stateLength', getStateLength );
setReadOnlyAccessor( minstdShuffle, 'byteLength', getStateSize );
setReadOnly( minstdShuffle, 'toJSON', toJSON );
setReadOnly( minstdShuffle, 'MIN', 1 );
setReadOnly( minstdShuffle, 'MAX', INT32_MAX-1 );
setReadOnly( minstdShuffle, 'normalized', normalized );
setReadOnly( normalized, 'NAME', minstdShuffle.NAME );
setReadOnlyAccessor( normalized, 'seed', getSeed );
setReadOnlyAccessor( normalized, 'seedLength', getSeedLength );
setReadWriteAccessor( normalized, 'state', getState, setState );
setReadOnlyAccessor( normalized, 'stateLength', getStateLength );
setReadOnlyAccessor( normalized, 'byteLength', getStateSize );
setReadOnly( normalized, 'toJSON', toJSON );
setReadOnly( normalized, 'MIN', (minstdShuffle.MIN-1.0) / NORMALIZATION_CONSTANT );
setReadOnly( normalized, 'MAX', (minstdShuffle.MAX-1.0) / NORMALIZATION_CONSTANT );
return minstdShuffle;
/**
* Returns the PRNG seed.
*
* @private
* @returns {PRNGSeedMINSTD} seed
*/
function getSeed() {
var len = STATE[ SEED_SECTION_OFFSET ];
return gcopy( len, seed, 1, new Int32Array( len ), 1 );
}
/**
* Returns the PRNG seed length.
*
* @private
* @returns {PositiveInteger} seed length
*/
function getSeedLength() {
return STATE[ SEED_SECTION_OFFSET ];
}
/**
* Returns the PRNG state length.
*
* @private
* @returns {PositiveInteger} state length
*/
function getStateLength() {
return STATE.length;
}
/**
* Returns the PRNG state size (in bytes).
*
* @private
* @returns {PositiveInteger} state size (in bytes)
*/
function getStateSize() {
return STATE.byteLength;
}
/**
* Returns the current PRNG state.
*
* ## Notes
*
* - The PRNG state array is comprised of a preamble followed by `3` sections:
*
* 0. preamble (version + number of sections)
* 1. shuffle table
* 2. internal PRNG state
* 3. PRNG seed
*
* - The first element of the PRNG state array preamble is the state array schema version.
*
* - The second element of the PRNG state array preamble is the number of state array sections (i.e., `3`).
*
* - The first element of each section following the preamble specifies the section length. The remaining section elements comprise the section contents.
*
* @private
* @returns {PRNGStateMINSTD} current state
*/
function getState() {
var len = STATE.length;
return gcopy( len, STATE, 1, new Int32Array( len ), 1 );
}
/**
* Sets the PRNG state.
*
* ## Notes
*
* - If PRNG state is "shared" (meaning a state array was provided during PRNG creation and **not** copied) and one sets the generator state to a state array having a different length, the PRNG does **not** update the existing shared state and, instead, points to the newly provided state array. In order to synchronize PRNG output according to the new shared state array, the state array for **each** relevant PRNG must be **explicitly** set.
* - If PRNG state is "shared" and one sets the generator state to a state array of the same length, the PRNG state is updated (along with the state of all other PRNGs sharing the PRNG's state array).
*
* @private
* @param {PRNGStateMINSTD} s - generator state
* @throws {TypeError} must provide an `Int32Array`
* @throws {Error} must provide a valid state
*/
function setState( s ) {
var err;
if ( !isInt32Array( s ) ) {
throw new TypeError( 'invalid argument. Must provide an Int32Array. Value: `' + s + '`.' );
}
err = verifyState( s, false );
if ( err ) {
throw err;
}
if ( opts.copy === false ) {
if ( opts.state && s.length === STATE.length ) {
gcopy( s.length, s, 1, STATE, 1 ); // update current shared state
} else {
STATE = s; // point to new shared state
opts.state = true; // setting this flag allows updating a shared state even if a state array was not provided at PRNG creation
}
} else {
// Check if we can reuse allocated memory...
if ( s.length !== STATE.length ) {
STATE = new Int32Array( s.length ); // reallocate
}
gcopy( s.length, s, 1, STATE, 1 );
}
// Create a new state (table) "view":
state = new Int32Array( STATE.buffer, STATE.byteOffset+((TABLE_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), TABLE_LENGTH );
// Create a new seed "view":
seed = new Int32Array( STATE.buffer, STATE.byteOffset+((SEED_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), STATE[ SEED_SECTION_OFFSET ] );
}
/**
* Serializes the pseudorandom number generator as a JSON object.
*
* ## Notes
*
* - `JSON.stringify()` implicitly calls this method when stringifying a PRNG.
*
* @private
* @returns {Object} JSON representation
*/
function toJSON() {
var out = {};
out.type = 'PRNG';
out.name = minstdShuffle.NAME;
out.state = typedarray2json( STATE );
out.params = [];
return out;
}
/**
* Generates a pseudorandom integer on the interval \\( [1,2^{31}-1) \\).
*
* @private
* @returns {integer32} pseudorandom integer
*/
function minstd() {
var s = STATE[ PRNG_STATE ]|0; // asm type annotation
s = ( (A*s)%INT32_MAX )|0; // asm type annotation
STATE[ PRNG_STATE ] = s;
return s|0; // asm type annotation
}
/**
* Generates a pseudorandom integer on the interval \\( [1,2^{31}-1) \\).
*
* @private
* @returns {integer32} pseudorandom integer
*
* @example
* var v = minstd();
* // returns <number>
*/
function minstdShuffle() {
var s;
var i;
s = STATE[ SHUFFLE_STATE ];
i = floor( TABLE_LENGTH * (s/INT32_MAX) );
// Pull a state from the table:
s = state[ i ];
// Update the PRNG state:
STATE[ SHUFFLE_STATE ] = s;
// Replace the pulled state:
state[ i ] = minstd();
return s;
}
/**
* Generates a pseudorandom number on the interval \\( [0,1) \\).
*
* @private
* @returns {number} pseudorandom number
*
* @example
* var v = normalized();
* // returns <number>
*/
function normalized() {
return (minstdShuffle()-1) / NORMALIZATION_CONSTANT;
}
}
// EXPORTS //
module.exports = factory;
},{"./create_table.js":331,"./rand_int32.js":335,"@stdlib/array/int32":10,"@stdlib/array/to-json":17,"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-boolean":81,"@stdlib/assert/is-collection":90,"@stdlib/assert/is-int32array":106,"@stdlib/assert/is-plain-object":147,"@stdlib/assert/is-positive-integer":149,"@stdlib/blas/base/gcopy":225,"@stdlib/constants/int32/max":250,"@stdlib/math/base/special/floor":277,"@stdlib/utils/define-nonenumerable-read-only-accessor":394,"@stdlib/utils/define-nonenumerable-read-only-property":396,"@stdlib/utils/define-nonenumerable-read-write-accessor":398}],333:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* A linear congruential pseudorandom number generator (LCG) whose output is shuffled.
*
* @module @stdlib/random/base/minstd-shuffle
*
* @example
* var minstd = require( '@stdlib/random/base/minstd-shuffle' );
*
* var v = minstd();
* // returns <number>
*
* @example
* var factory = require( '@stdlib/random/base/minstd-shuffle' ).factory;
*
* var minstd = factory({
* 'seed': 1234
* });
*
* var v = minstd();
* // returns 1421600654
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var minstd = require( './main.js' );
var factory = require( './factory.js' );
// MAIN //
setReadOnly( minstd, 'factory', factory );
// EXPORTS //
module.exports = minstd;
},{"./factory.js":332,"./main.js":334,"@stdlib/utils/define-nonenumerable-read-only-property":396}],334:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var factory = require( './factory.js' );
var randint32 = require( './rand_int32.js' );
// MAIN //
/**
* Generates a pseudorandom integer on the interval \\( [1,2^{31}-1) \\).
*
* ## Method
*
* Linear congruential generators (LCGs) use the recurrence relation
*
* ```tex
* X_{n+1} = ( a \cdot X_n + c ) \operatorname{mod}(m)
* ```
*
* where the modulus \\( m \\) is a prime number or power of a prime number and \\( a \\) is a primitive root modulo \\( m \\).
*
* <!-- <note> -->
*
* For an LCG to be a Lehmer RNG, the seed \\( X_0 \\) must be coprime to \\( m \\).
*
* <!-- </note> -->
*
* In this implementation, the constants \\( a \\), \\( c \\), and \\( m \\) have the values
*
* ```tex
* \begin{align*}
* a &= 7^5 = 16807 \\
* c &= 0 \\
* m &= 2^{31} - 1 = 2147483647
* \end{align*}
* ```
*
* <!-- <note> -->
*
* The constant \\( m \\) is a Mersenne prime (modulo \\(31\\)).
*
* <!-- </note> -->
*
* <!-- <note> -->
*
* The constant \\( a \\) is a primitive root (modulo \\(31\\)).
*
* <!-- </note> -->
*
* Accordingly, the maximum possible product is
*
* ```tex
* 16807 \cdot (m - 1) \approx 2^{46}
* ```
*
* The values for \\( a \\), \\( c \\), and \\( m \\) are taken from Park and Miller, "Random Number Generators: Good Ones Are Hard To Find". Park's and Miller's article is also the basis for a recipe in the second edition of _Numerical Recipes in C_.
*
* This implementation subsequently shuffles the output of a linear congruential pseudorandom number generator (LCG) using a shuffle table in accordance with the Bays-Durham algorithm.
*
*
* ## Notes
*
* - The generator has a period of approximately \\(2.1\mbox{e}9\\) (see [Numerical Recipes in C, 2nd Edition](#references), p. 279).
*
*
* ## References
*
* - Bays, Carter, and S. D. Durham. 1976. "Improving a Poor Random Number Generator." _ACM Transactions on Mathematical Software_ 2 (1). New York, NY, USA: ACM: 59–64. doi:[10.1145/355666.355670](http://dx.doi.org/10.1145/355666.355670).
* - Herzog, T.N., and G. Lord. 2002. _Applications of Monte Carlo Methods to Finance and Insurance_. ACTEX Publications. [https://books.google.com/books?id=vC7I\\\_gdX-A0C](https://books.google.com/books?id=vC7I\_gdX-A0C).
* - Press, William H., Brian P. Flannery, Saul A. Teukolsky, and William T. Vetterling. 1992. _Numerical Recipes in C: The Art of Scientific Computing, Second Edition_. Cambridge University Press.
*
*
* @function minstd
* @type {PRNG}
* @returns {PositiveInteger} pseudorandom integer
*
* @example
* var v = minstd();
* // returns <number>
*/
var minstd = factory({
'seed': randint32()
});
// EXPORTS //
module.exports = minstd;
},{"./factory.js":332,"./rand_int32.js":335}],335:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var INT32_MAX = require( '@stdlib/constants/int32/max' );
var floor = require( '@stdlib/math/base/special/floor' );
// VARIABLES //
var MAX = INT32_MAX - 1;
// MAIN //
/**
* Returns a pseudorandom integer on the interval \\([1, 2^{31}-1)\\).
*
* @private
* @returns {PositiveInteger} pseudorandom integer
*
* @example
* var v = randint32();
* // returns <number>
*/
function randint32() {
var v = floor( 1.0 + (MAX*Math.random()) ); // eslint-disable-line stdlib/no-builtin-math
return v|0; // asm type annotation
}
// EXPORTS //
module.exports = randint32;
},{"@stdlib/constants/int32/max":250,"@stdlib/math/base/special/floor":277}],336:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
/* eslint-disable max-len */
'use strict';
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var setReadOnlyAccessor = require( '@stdlib/utils/define-nonenumerable-read-only-accessor' );
var setReadWriteAccessor = require( '@stdlib/utils/define-nonenumerable-read-write-accessor' );
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var isObject = require( '@stdlib/assert/is-plain-object' );
var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive;
var isCollection = require( '@stdlib/assert/is-collection' );
var isPositiveInteger = require( '@stdlib/assert/is-positive-integer' ).isPrimitive;
var isInt32Array = require( '@stdlib/assert/is-int32array' );
var INT32_MAX = require( '@stdlib/constants/int32/max' );
var Int32Array = require( '@stdlib/array/int32' );
var gcopy = require( '@stdlib/blas/base/gcopy' );
var typedarray2json = require( '@stdlib/array/to-json' );
var randint32 = require( './rand_int32.js' );
// VARIABLES //
var NORMALIZATION_CONSTANT = (INT32_MAX - 1)|0; // asm type annotation
var MAX_SEED = (INT32_MAX - 1)|0; // asm type annotation
var A = 16807|0; // asm type annotation
// Define the state array schema version:
var STATE_ARRAY_VERSION = 1; // NOTE: anytime the state array schema changes, this value should be incremented!!!
// Define the number of sections in the state array:
var NUM_STATE_SECTIONS = 2; // state, seed
// Define the index offset of the "state" section in the state array:
var STATE_SECTION_OFFSET = 2; // | version | num_sections | state_length | ...state | seed_length | ...seed |
// Define the index offset of the seed section in the state array:
var SEED_SECTION_OFFSET = 4; // | version | num_sections | state_length | ...state | seed_length | ...seed |
// Define the length of the "fixed" length portion of the state array:
var STATE_FIXED_LENGTH = 5; // 1 (version) + 1 (num_sections) + 1 (state_length) + 1 (state) + 1 (seed_length)
// FUNCTIONS //
/**
* Verifies state array integrity.
*
* @private
* @param {Int32Array} state - state array
* @param {boolean} FLG - flag indicating whether the state array was provided as an option (true) or an argument (false)
* @returns {(Error|null)} an error or `null`
*/
function verifyState( state, FLG ) {
var s1;
if ( FLG ) {
s1 = 'option';
} else {
s1 = 'argument';
}
// The state array must have a minimum length...
if ( state.length < STATE_FIXED_LENGTH+1 ) {
return new RangeError( 'invalid '+s1+'. `state` array has insufficient length.' );
}
// The first element of the state array must equal the supported state array schema version...
if ( state[ 0 ] !== STATE_ARRAY_VERSION ) {
return new RangeError( 'invalid '+s1+'. `state` array has an incompatible schema version. Expected: '+STATE_ARRAY_VERSION+'. Actual: '+state[ 0 ]+'.' );
}
// The second element of the state array must contain the number of sections...
if ( state[ 1 ] !== NUM_STATE_SECTIONS ) {
return new RangeError( 'invalid '+s1+'. `state` array has an incompatible number of sections. Expected: '+NUM_STATE_SECTIONS+'. Actual: '+state[ 1 ]+'.' );
}
// The length of the "state" section must equal `1`...
if ( state[ STATE_SECTION_OFFSET ] !== 1 ) {
return new RangeError( 'invalid '+s1+'. `state` array has an incompatible state length. Expected: '+(1).toString()+'. Actual: '+state[ STATE_SECTION_OFFSET ]+'.' );
}
// The length of the "seed" section much match the empirical length...
if ( state[ SEED_SECTION_OFFSET ] !== state.length-STATE_FIXED_LENGTH ) {
return new RangeError( 'invalid '+s1+'. `state` array length is incompatible with seed section length. Expected: '+(state.length-STATE_FIXED_LENGTH)+'. Actual: '+state[ SEED_SECTION_OFFSET ]+'.' );
}
return null;
}
// MAIN //
/**
* Returns a linear congruential pseudorandom number generator (LCG) based on Park and Miller.
*
* @param {Options} [options] - options
* @param {PRNGSeedMINSTD} [options.seed] - pseudorandom number generator seed
* @param {PRNGStateMINSTD} [options.state] - pseudorandom number generator state
* @param {boolean} [options.copy=true] - boolean indicating whether to copy a provided pseudorandom number generator state
* @throws {TypeError} options argument must be an object
* @throws {TypeError} a seed must be either a positive integer less than the maximum signed 32-bit integer or an array-like object containing integers less than the maximum signed 32-bit integer
* @throws {RangeError} a numeric seed must be a positive integer less than the maximum signed 32-bit integer
* @throws {TypeError} state must be an `Int32Array`
* @throws {Error} must provide a valid state
* @throws {TypeError} `copy` option must be a boolean
* @returns {PRNG} LCG PRNG
*
* @example
* var minstd = factory();
*
* var v = minstd();
* // returns <number>
*
* @example
* // Return a seeded LCG:
* var minstd = factory({
* 'seed': 1234
* });
*
* var v = minstd();
* // returns 20739838
*/
function factory( options ) {
var STATE;
var state;
var opts;
var seed;
var slen;
var err;
opts = {};
if ( arguments.length ) {
if ( !isObject( options ) ) {
throw new TypeError( 'invalid argument. Options argument must be an object. Value: `' + options + '`.' );
}
if ( hasOwnProp( options, 'copy' ) ) {
opts.copy = options.copy;
if ( !isBoolean( options.copy ) ) {
throw new TypeError( 'invalid option. `copy` option must be a boolean. Option: `' + options.copy + '`.' );
}
}
if ( hasOwnProp( options, 'state' ) ) {
state = options.state;
opts.state = true;
if ( !isInt32Array( state ) ) {
throw new TypeError( 'invalid option. `state` option must be an Int32Array. Option: `' + state + '`.' );
}
err = verifyState( state, true );
if ( err ) {
throw err;
}
if ( opts.copy === false ) {
STATE = state;
} else {
STATE = new Int32Array( state.length );
gcopy( state.length, state, 1, STATE, 1 );
}
// Create a state "view":
state = new Int32Array( STATE.buffer, STATE.byteOffset+((STATE_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), 1 );
// Create a seed "view":
seed = new Int32Array( STATE.buffer, STATE.byteOffset+((SEED_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), state[ SEED_SECTION_OFFSET ] );
}
// If provided a PRNG state, we ignore the `seed` option...
if ( seed === void 0 ) {
if ( hasOwnProp( options, 'seed' ) ) {
seed = options.seed;
opts.seed = true;
if ( isPositiveInteger( seed ) ) {
if ( seed > MAX_SEED ) {
throw new RangeError( 'invalid option. `seed` option must be a positive integer less than the maximum signed 32-bit integer. Option: `' + seed + '`.' );
}
seed |= 0; // asm type annotation
} else if ( isCollection( seed ) && seed.length > 0 ) {
slen = seed.length;
STATE = new Int32Array( STATE_FIXED_LENGTH+slen );
// Initialize sections:
STATE[ 0 ] = STATE_ARRAY_VERSION;
STATE[ 1 ] = NUM_STATE_SECTIONS;
STATE[ STATE_SECTION_OFFSET ] = 1;
STATE[ SEED_SECTION_OFFSET ] = slen;
// Copy the provided seed array to prevent external mutation, as mutation would lead to an inability to reproduce PRNG values according to the PRNG's stated seed:
gcopy.ndarray( slen, seed, 1, 0, STATE, 1, SEED_SECTION_OFFSET+1 );
// Create a state "view":
state = new Int32Array( STATE.buffer, STATE.byteOffset+((STATE_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), 1 );
// Create a seed "view":
seed = new Int32Array( STATE.buffer, STATE.byteOffset+((SEED_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), slen );
// Initialize the internal PRNG state:
state[ 0 ] = seed[ 0 ];
} else {
throw new TypeError( 'invalid option. `seed` option must be either a positive integer less than the maximum signed 32-bit integer or an array-like object containing integer values less than the maximum signed 32-bit integer. Option: `' + seed + '`.' );
}
} else {
seed = randint32()|0; // asm type annotation
}
}
} else {
seed = randint32()|0; // asm type annotation
}
if ( state === void 0 ) {
STATE = new Int32Array( STATE_FIXED_LENGTH+1 );
// Initialize sections:
STATE[ 0 ] = STATE_ARRAY_VERSION;
STATE[ 1 ] = NUM_STATE_SECTIONS;
STATE[ STATE_SECTION_OFFSET ] = 1;
STATE[ SEED_SECTION_OFFSET ] = 1;
STATE[ SEED_SECTION_OFFSET+1 ] = seed;
// Create a state "view":
state = new Int32Array( STATE.buffer, STATE.byteOffset+((STATE_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), 1 );
// Create a seed "view":
seed = new Int32Array( STATE.buffer, STATE.byteOffset+((SEED_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), 1 );
// Initialize the internal PRNG state:
state[ 0 ] = seed[ 0 ];
}
setReadOnly( minstd, 'NAME', 'minstd' );
setReadOnlyAccessor( minstd, 'seed', getSeed );
setReadOnlyAccessor( minstd, 'seedLength', getSeedLength );
setReadWriteAccessor( minstd, 'state', getState, setState );
setReadOnlyAccessor( minstd, 'stateLength', getStateLength );
setReadOnlyAccessor( minstd, 'byteLength', getStateSize );
setReadOnly( minstd, 'toJSON', toJSON );
setReadOnly( minstd, 'MIN', 1 );
setReadOnly( minstd, 'MAX', INT32_MAX-1 );
setReadOnly( minstd, 'normalized', normalized );
setReadOnly( normalized, 'NAME', minstd.NAME );
setReadOnlyAccessor( normalized, 'seed', getSeed );
setReadOnlyAccessor( normalized, 'seedLength', getSeedLength );
setReadWriteAccessor( normalized, 'state', getState, setState );
setReadOnlyAccessor( normalized, 'stateLength', getStateLength );
setReadOnlyAccessor( normalized, 'byteLength', getStateSize );
setReadOnly( normalized, 'toJSON', toJSON );
setReadOnly( normalized, 'MIN', (minstd.MIN-1.0) / NORMALIZATION_CONSTANT );
setReadOnly( normalized, 'MAX', (minstd.MAX-1.0) / NORMALIZATION_CONSTANT );
return minstd;
/**
* Returns the PRNG seed.
*
* @private
* @returns {PRNGSeedMINSTD} seed
*/
function getSeed() {
var len = STATE[ SEED_SECTION_OFFSET ];
return gcopy( len, seed, 1, new Int32Array( len ), 1 );
}
/**
* Returns the PRNG seed length.
*
* @private
* @returns {PositiveInteger} seed length
*/
function getSeedLength() {
return STATE[ SEED_SECTION_OFFSET ];
}
/**
* Returns the PRNG state length.
*
* @private
* @returns {PositiveInteger} state length
*/
function getStateLength() {
return STATE.length;
}
/**
* Returns the PRNG state size (in bytes).
*
* @private
* @returns {PositiveInteger} state size (in bytes)
*/
function getStateSize() {
return STATE.byteLength;
}
/**
* Returns the current PRNG state.
*
* ## Notes
*
* - The PRNG state array is comprised of a preamble followed by `2` sections:
*
* 0. preamble (version + number of sections)
* 1. internal PRNG state
* 2. PRNG seed
*
* - The first element of the PRNG state array preamble is the state array schema version.
*
* - The second element of the PRNG state array preamble is the number of state array sections (i.e., `2`).
*
* - The first element of each section following the preamble specifies the section length. The remaining section elements comprise the section contents.
*
* @private
* @returns {PRNGStateMINSTD} current state
*/
function getState() {
var len = STATE.length;
return gcopy( len, STATE, 1, new Int32Array( len ), 1 );
}
/**
* Sets the PRNG state.
*
* ## Notes
*
* - If PRNG state is "shared" (meaning a state array was provided during PRNG creation and **not** copied) and one sets the generator state to a state array having a different length, the PRNG does **not** update the existing shared state and, instead, points to the newly provided state array. In order to synchronize PRNG output according to the new shared state array, the state array for **each** relevant PRNG must be **explicitly** set.
* - If PRNG state is "shared" and one sets the generator state to a state array of the same length, the PRNG state is updated (along with the state of all other PRNGs sharing the PRNG's state array).
*
* @private
* @param {PRNGStateMINSTD} s - generator state
* @throws {TypeError} must provide an `Int32Array`
* @throws {Error} must provide a valid state
*/
function setState( s ) {
var err;
if ( !isInt32Array( s ) ) {
throw new TypeError( 'invalid argument. Must provide an Int32Array. Value: `' + s + '`.' );
}
err = verifyState( s, false );
if ( err ) {
throw err;
}
if ( opts.copy === false ) {
if ( opts.state && s.length === STATE.length ) {
gcopy( s.length, s, 1, STATE, 1 ); // update current shared state
} else {
STATE = s; // point to new shared state
opts.state = true; // setting this flag allows updating a shared state even if a state array was not provided at PRNG creation
}
} else {
// Check if we can reuse allocated memory...
if ( s.length !== STATE.length ) {
STATE = new Int32Array( s.length ); // reallocate
}
gcopy( s.length, s, 1, STATE, 1 );
}
// Create a new state "view":
state = new Int32Array( STATE.buffer, STATE.byteOffset+((STATE_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), 1 );
// Create a new seed "view":
seed = new Int32Array( STATE.buffer, STATE.byteOffset+((SEED_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), STATE[ SEED_SECTION_OFFSET ] );
}
/**
* Serializes the pseudorandom number generator as a JSON object.
*
* ## Notes
*
* - `JSON.stringify()` implicitly calls this method when stringifying a PRNG.
*
* @private
* @returns {Object} JSON representation
*/
function toJSON() {
var out = {};
out.type = 'PRNG';
out.name = minstd.NAME;
out.state = typedarray2json( STATE );
out.params = [];
return out;
}
/**
* Generates a pseudorandom integer on the interval \\( [1,2^{31}-1) \\).
*
* @private
* @returns {integer32} pseudorandom integer
*/
function minstd() {
var s = state[ 0 ]|0; // asm type annotation
s = ( (A*s)%INT32_MAX )|0; // asm type annotation
state[ 0 ] = s;
return s|0; // asm type annotation
}
/**
* Generates a pseudorandom number on the interval \\( [0,1) \\).
*
* @private
* @returns {number} pseudorandom number
*/
function normalized() {
return (minstd()-1) / NORMALIZATION_CONSTANT;
}
}
// EXPORTS //
module.exports = factory;
},{"./rand_int32.js":339,"@stdlib/array/int32":10,"@stdlib/array/to-json":17,"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-boolean":81,"@stdlib/assert/is-collection":90,"@stdlib/assert/is-int32array":106,"@stdlib/assert/is-plain-object":147,"@stdlib/assert/is-positive-integer":149,"@stdlib/blas/base/gcopy":225,"@stdlib/constants/int32/max":250,"@stdlib/utils/define-nonenumerable-read-only-accessor":394,"@stdlib/utils/define-nonenumerable-read-only-property":396,"@stdlib/utils/define-nonenumerable-read-write-accessor":398}],337:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* A linear congruential pseudorandom number generator (LCG) based on Park and Miller.
*
* @module @stdlib/random/base/minstd
*
* @example
* var minstd = require( '@stdlib/random/base/minstd' );
*
* var v = minstd();
* // returns <number>
*
* @example
* var factory = require( '@stdlib/random/base/minstd' ).factory;
*
* var minstd = factory({
* 'seed': 1234
* });
*
* var v = minstd();
* // returns 20739838
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var minstd = require( './main.js' );
var factory = require( './factory.js' );
// MAIN //
setReadOnly( minstd, 'factory', factory );
// EXPORTS //
module.exports = minstd;
},{"./factory.js":336,"./main.js":338,"@stdlib/utils/define-nonenumerable-read-only-property":396}],338:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var factory = require( './factory.js' );
var randint32 = require( './rand_int32.js' );
// MAIN //
/**
* Generates a pseudorandom integer on the interval \\( [1,2^{31}-1) \\).
*
* ## Method
*
* Linear congruential generators (LCGs) use the recurrence relation
*
* ```tex
* X_{n+1} = ( a \cdot X_n + c ) \operatorname{mod}(m)
* ```
*
* where the modulus \\( m \\) is a prime number or power of a prime number and \\( a \\) is a primitive root modulo \\( m \\).
*
* <!-- <note> -->
*
* For an LCG to be a Lehmer RNG, the seed \\( X_0 \\) must be coprime to \\( m \\).
*
* <!-- </note> -->
*
* In this implementation, the constants \\( a \\), \\( c \\), and \\( m \\) have the values
*
* ```tex
* \begin{align*}
* a &= 7^5 = 16807 \\
* c &= 0 \\
* m &= 2^{31} - 1 = 2147483647
* \end{align*}
* ```
*
* <!-- <note> -->
*
* The constant \\( m \\) is a Mersenne prime (modulo \\(31\\)).
*
* <!-- </note> -->
*
* <!-- <note> -->
*
* The constant \\( a \\) is a primitive root (modulo \\(31\\)).
*
* <!-- </note> -->
*
* Accordingly, the maximum possible product is
*
* ```tex
* 16807 \cdot (m - 1) \approx 2^{46}
* ```
*
* The values for \\( a \\), \\( c \\), and \\( m \\) are taken from Park and Miller, "Random Number Generators: Good Ones Are Hard To Find". Park's and Miller's article is also the basis for a recipe in the second edition of _Numerical Recipes in C_.
*
*
* ## Notes
*
* - The generator has a period of approximately \\(2.1\mbox{e}9\\) (see [Numerical Recipes in C, 2nd Edition](#references), p. 279).
*
*
* ## References
*
* - Park, S. K., and K. W. Miller. 1988. "Random Number Generators: Good Ones Are Hard to Find." _Communications of the ACM_ 31 (10). New York, NY, USA: ACM: 1192–1201. doi:[10.1145/63039.63042](http://dx.doi.org/10.1145/63039.63042).
* - Press, William H., Brian P. Flannery, Saul A. Teukolsky, and William T. Vetterling. 1992. _Numerical Recipes in C: The Art of Scientific Computing, Second Edition_. Cambridge University Press.
*
*
* @function minstd
* @type {PRNG}
* @returns {PositiveInteger} pseudorandom integer
*
* @example
* var v = minstd();
* // returns <number>
*/
var minstd = factory({
'seed': randint32()
});
// EXPORTS //
module.exports = minstd;
},{"./factory.js":336,"./rand_int32.js":339}],339:[function(require,module,exports){
arguments[4][335][0].apply(exports,arguments)
},{"@stdlib/constants/int32/max":250,"@stdlib/math/base/special/floor":277,"dup":335}],340:[function(require,module,exports){
/* eslint-disable max-lines, max-len */
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*
*
* ## Notice
*
* The original C code and copyright notice are from the [source implementation]{@link http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/CODES/mt19937ar.c}. The implementation has been modified for JavaScript.
*
* ```text
* Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. The names of its contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* ```
*/
'use strict';
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var setReadOnlyAccessor = require( '@stdlib/utils/define-nonenumerable-read-only-accessor' );
var setReadWriteAccessor = require( '@stdlib/utils/define-nonenumerable-read-write-accessor' );
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var isObject = require( '@stdlib/assert/is-plain-object' );
var isCollection = require( '@stdlib/assert/is-collection' );
var isUint32Array = require( '@stdlib/assert/is-uint32array' );
var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive;
var isPositiveInteger = require( '@stdlib/assert/is-positive-integer' ).isPrimitive;
var FLOAT64_MAX_SAFE_INTEGER = require( '@stdlib/constants/float64/max-safe-integer' );
var UINT32_MAX = require( '@stdlib/constants/uint32/max' );
var Uint32Array = require( '@stdlib/array/uint32' );
var max = require( '@stdlib/math/base/special/max' );
var uimul = require( '@stdlib/math/base/special/uimul' );
var gcopy = require( '@stdlib/blas/base/gcopy' );
var typedarray2json = require( '@stdlib/array/to-json' );
var randuint32 = require( './rand_uint32.js' );
// VARIABLES //
// Define the size of the state array (see refs):
var N = 624;
// Define a (magic) constant used for indexing into the state array:
var M = 397;
// Define the maximum seed: 11111111111111111111111111111111
var MAX_SEED = UINT32_MAX >>> 0; // asm type annotation
// For seed arrays, define an initial state (magic) constant: 19650218 => 00000001001010111101011010101010
var SEED_ARRAY_INIT_STATE = 19650218 >>> 0; // asm type annotation
// Define a mask for the most significant `w-r` bits, where `w` is the word size (32 bits) and `r` is the separation point of one word (see refs): 2147483648 => 0x80000000 => 10000000000000000000000000000000
var UPPER_MASK = 0x80000000 >>> 0; // asm type annotation
// Define a mask for the least significant `r` bits (see refs): 2147483647 => 0x7fffffff => 01111111111111111111111111111111
var LOWER_MASK = 0x7fffffff >>> 0; // asm type annotation
// Define a multiplier (see Knuth TAOCP Vol2. 3rd Ed. P.106): 1812433253 => 01101100000001111000100101100101
var KNUTH_MULTIPLIER = 1812433253 >>> 0; // asm type annotation
// Define a (magic) multiplier: 1664525 => 00000000000110010110011000001101
var MAGIC_MULTIPLIER_1 = 1664525 >>> 0; // asm type annotation
// Define a (magic) multiplier: 1566083941 => 01011101010110001000101101100101
var MAGIC_MULTIPLIER_2 = 1566083941 >>> 0; // asm type annotation
// Define a tempering coefficient: 2636928640 => 0x9d2c5680 => 10011101001011000101011010000000
var TEMPERING_COEFFICIENT_1 = 0x9d2c5680 >>> 0; // asm type annotation
// Define a tempering coefficient: 4022730752 => 0xefc60000 => 11101111110001100000000000000000
var TEMPERING_COEFFICIENT_2 = 0xefc60000 >>> 0; // asm type annotation
// Define a constant vector `a` (see refs): 2567483615 => 0x9908b0df => 10011001000010001011000011011111
var MATRIX_A = 0x9908b0df >>> 0; // asm type annotation
// MAG01[x] = x * MATRIX_A; for x = {0,1}
var MAG01 = [ 0x0 >>> 0, MATRIX_A >>> 0 ]; // asm type annotation
// Define a normalization constant when generating double-precision floating-point numbers: 2^53 => 9007199254740992
var FLOAT64_NORMALIZATION_CONSTANT = 1.0 / ( FLOAT64_MAX_SAFE_INTEGER+1.0 ); // eslint-disable-line id-length
// 2^26: 67108864
var TWO_26 = 67108864 >>> 0; // asm type annotation
// 2^32: 2147483648 => 0x80000000 => 10000000000000000000000000000000
var TWO_32 = 0x80000000 >>> 0; // asm type annotation
// 1 (as a 32-bit unsigned integer): 1 => 0x1 => 00000000000000000000000000000001
var ONE = 0x1 >>> 0; // asm type annotation
// Define the maximum normalized pseudorandom double-precision floating-point number: ( (((2^32-1)>>>5)*2^26)+( (2^32-1)>>>6) ) / 2^53
var MAX_NORMALIZED = FLOAT64_MAX_SAFE_INTEGER * FLOAT64_NORMALIZATION_CONSTANT;
// Define the state array schema version:
var STATE_ARRAY_VERSION = 1; // NOTE: anytime the state array schema changes, this value should be incremented!!!
// Define the number of sections in the state array:
var NUM_STATE_SECTIONS = 3; // state, other, seed
// Define the index offset of the "state" section in the state array:
var STATE_SECTION_OFFSET = 2; // | version | num_sections | state_length | ...state | other_length | state_index | seed_length | ...seed |
// Define the index offset of the "other" section in the state array:
var OTHER_SECTION_OFFSET = N + 3; // | version | num_sections | state_length | ...state | other_length | state_index | seed_length | ...seed |
// Define the index offset of the seed section in the state array:
var SEED_SECTION_OFFSET = N + 5; // | version | num_sections | state_length | ...state | other_length | state_index | seed_length | ...seed |
// Define the length of the "fixed" length portion of the state array:
var STATE_FIXED_LENGTH = N + 6; // 1 (version) + 1 (num_sections) + 1 (state_length) + N (state) + 1 (other_length) + 1 (state_index) + 1 (seed_length)
// FUNCTIONS //
/**
* Verifies state array integrity.
*
* @private
* @param {Uint32Array} state - state array
* @param {boolean} FLG - flag indicating whether the state array was provided as an option (true) or an argument (false)
* @returns {(Error|null)} an error or `null`
*/
function verifyState( state, FLG ) {
var s1;
if ( FLG ) {
s1 = 'option';
} else {
s1 = 'argument';
}
// The state array must have a minimum length...
if ( state.length < STATE_FIXED_LENGTH+1 ) {
return new RangeError( 'invalid '+s1+'. `state` array has insufficient length.' );
}
// The first element of the state array must equal the supported state array schema version...
if ( state[ 0 ] !== STATE_ARRAY_VERSION ) {
return new RangeError( 'invalid '+s1+'. `state` array has an incompatible schema version. Expected: '+STATE_ARRAY_VERSION+'. Actual: '+state[ 0 ]+'.' );
}
// The second element of the state array must contain the number of sections...
if ( state[ 1 ] !== NUM_STATE_SECTIONS ) {
return new RangeError( 'invalid '+s1+'. `state` array has an incompatible number of sections. Expected: '+NUM_STATE_SECTIONS+'. Actual: '+state[ 1 ]+'.' );
}
// The length of the "state" section must equal `N`...
if ( state[ STATE_SECTION_OFFSET ] !== N ) {
return new RangeError( 'invalid '+s1+'. `state` array has an incompatible state length. Expected: '+N+'. Actual: '+state[ STATE_SECTION_OFFSET ]+'.' );
}
// The length of the "other" section must equal `1`...
if ( state[ OTHER_SECTION_OFFSET ] !== 1 ) {
return new RangeError( 'invalid '+s1+'. `state` array has an incompatible section length. Expected: '+(1).toString()+'. Actual: '+state[ OTHER_SECTION_OFFSET ]+'.' );
}
// The length of the "seed" section much match the empirical length...
if ( state[ SEED_SECTION_OFFSET ] !== state.length-STATE_FIXED_LENGTH ) {
return new RangeError( 'invalid '+s1+'. `state` array length is incompatible with seed section length. Expected: '+(state.length-STATE_FIXED_LENGTH)+'. Actual: '+state[ SEED_SECTION_OFFSET ]+'.' );
}
return null;
}
/**
* Returns an initial PRNG state.
*
* @private
* @param {Uint32Array} state - state array
* @param {PositiveInteger} N - state size
* @param {uinteger32} s - seed
* @returns {Uint32Array} state array
*/
function createState( state, N, s ) {
var i;
// Set the first element of the state array to the provided seed:
state[ 0 ] = s >>> 0; // equivalent to `s & 0xffffffffUL` in original C implementation
// Initialize the remaining state array elements:
for ( i = 1; i < N; i++ ) {
/*
* In the original C implementation (see `init_genrand()`),
*
* ```c
* mt[i] = (KNUTH_MULTIPLIER * (mt[i-1] ^ (mt[i-1] >> 30)) + i)
* ```
*
* In order to replicate this in JavaScript, we must emulate C-like multiplication of unsigned 32-bit integers.
*/
s = state[ i-1 ]>>>0; // asm type annotation
s = ( s^(s>>>30) )>>>0; // asm type annotation
state[ i ] = ( uimul( s, KNUTH_MULTIPLIER ) + i )>>>0; // asm type annotation
}
return state;
}
/**
* Initializes a PRNG state array according to a seed array.
*
* @private
* @param {Uint32Array} state - state array
* @param {NonNegativeInteger} N - state array length
* @param {Collection} seed - seed array
* @param {NonNegativeInteger} M - seed array length
* @returns {Uint32Array} state array
*/
function initState( state, N, seed, M ) {
var s;
var i;
var j;
var k;
i = 1;
j = 0;
for ( k = max( N, M ); k > 0; k-- ) {
/*
* In the original C implementation (see `init_by_array()`),
*
* ```c
* mt[i] = (mt[i]^((mt[i-1]^(mt[i-1]>>30))*1664525UL)) + seed[j] + j;
* ```
*
* In order to replicate this in JavaScript, we must emulate C-like multiplication of unsigned 32-bit integers.
*/
s = state[ i-1 ]>>>0; // asm type annotation
s = ( s^(s>>>30) )>>>0; // asm type annotation
s = ( uimul( s, MAGIC_MULTIPLIER_1 ) )>>>0; // asm type annotation
state[ i ] = ( ((state[i]>>>0)^s) + seed[j] + j )>>>0; /* non-linear */ // asm type annotation
i += 1;
j += 1;
if ( i >= N ) {
state[ 0 ] = state[ N-1 ];
i = 1;
}
if ( j >= M ) {
j = 0;
}
}
for ( k = N-1; k > 0; k-- ) {
/*
* In the original C implementation (see `init_by_array()`),
*
* ```c
* mt[i] = (mt[i]^((mt[i-1]^(mt[i-1]>>30))*1566083941UL)) - i;
* ```
*
* In order to replicate this in JavaScript, we must emulate C-like multiplication of unsigned 32-bit integers.
*/
s = state[ i-1 ]>>>0; // asm type annotation
s = ( s^(s>>>30) )>>>0; // asm type annotation
s = ( uimul( s, MAGIC_MULTIPLIER_2 ) )>>>0; // asm type annotation
state[ i ] = ( ((state[i]>>>0)^s) - i )>>>0; /* non-linear */ // asm type annotation
i += 1;
if ( i >= N ) {
state[ 0 ] = state[ N-1 ];
i = 1;
}
}
// Ensure a non-zero initial state array:
state[ 0 ] = TWO_32; // MSB (most significant bit) is 1
return state;
}
/**
* Updates a PRNG's internal state by generating the next `N` words.
*
* @private
* @param {Uint32Array} state - state array
* @returns {Uint32Array} state array
*/
function twist( state ) {
var w;
var i;
var j;
var k;
k = N - M;
for ( i = 0; i < k; i++ ) {
w = ( state[i]&UPPER_MASK ) | ( state[i+1]&LOWER_MASK );
state[ i ] = state[ i+M ] ^ ( w>>>1 ) ^ MAG01[ w&ONE ];
}
j = N - 1;
for ( ; i < j; i++ ) {
w = ( state[i]&UPPER_MASK ) | ( state[i+1]&LOWER_MASK );
state[ i ] = state[ i-k ] ^ ( w>>>1 ) ^ MAG01[ w&ONE ];
}
w = ( state[j]&UPPER_MASK ) | ( state[0]&LOWER_MASK );
state[ j ] = state[ M-1 ] ^ ( w>>>1 ) ^ MAG01[ w&ONE ];
return state;
}
// MAIN //
/**
* Returns a 32-bit Mersenne Twister pseudorandom number generator.
*
* ## Notes
*
* - In contrast to the original C implementation, array seeds of length `1` are considered integer seeds. This ensures that the seed `[ 1234 ]` generates the same output as the seed `1234`. In the original C implementation, the two seeds would yield different output, which is **not** obvious from a user perspective.
*
* @param {Options} [options] - options
* @param {PRNGSeedMT19937} [options.seed] - pseudorandom number generator seed
* @param {PRNGStateMT19937} [options.state] - pseudorandom number generator state
* @param {boolean} [options.copy=true] - boolean indicating whether to copy a provided pseudorandom number generator state
* @throws {TypeError} options argument must be an object
* @throws {TypeError} a seed must be either a positive integer less than or equal to the maximum unsigned 32-bit integer or an array-like object containing integers less than or equal to the maximum unsigned 32-bit integer
* @throws {RangeError} a numeric seed must be a positive integer less than or equal to the maximum unsigned 32-bit integer
* @throws {TypeError} state must be a `Uint32Array`
* @throws {Error} must provide a valid state
* @throws {TypeError} `copy` option must be a boolean
* @returns {PRNG} Mersenne Twister PRNG
*
* @example
* var mt19937 = factory();
*
* var v = mt19937();
* // returns <number>
*
* @example
* // Return a seeded Mersenne Twister PRNG:
* var mt19937 = factory({
* 'seed': 1234
* });
*
* var v = mt19937();
* // returns 822569775
*/
function factory( options ) {
var STATE;
var state;
var opts;
var seed;
var slen;
var err;
opts = {};
if ( arguments.length ) {
if ( !isObject( options ) ) {
throw new TypeError( 'invalid argument. Options argument must be an object. Value: `' + options + '`.' );
}
if ( hasOwnProp( options, 'copy' ) ) {
opts.copy = options.copy;
if ( !isBoolean( options.copy ) ) {
throw new TypeError( 'invalid option. `copy` option must be a boolean. Option: `' + options.copy + '`.' );
}
}
if ( hasOwnProp( options, 'state' ) ) {
state = options.state;
opts.state = true;
if ( !isUint32Array( state ) ) {
throw new TypeError( 'invalid option. `state` option must be a Uint32Array. Option: `' + state + '`.' );
}
err = verifyState( state, true );
if ( err ) {
throw err;
}
if ( opts.copy === false ) {
STATE = state;
} else {
STATE = new Uint32Array( state.length );
gcopy( state.length, state, 1, STATE, 1 );
}
// Create a state "view":
state = new Uint32Array( STATE.buffer, STATE.byteOffset+((STATE_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), N );
// Create a seed "view":
seed = new Uint32Array( STATE.buffer, STATE.byteOffset+((SEED_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), state[ SEED_SECTION_OFFSET ] );
}
// If provided a PRNG state, we ignore the `seed` option...
if ( seed === void 0 ) {
if ( hasOwnProp( options, 'seed' ) ) {
seed = options.seed;
opts.seed = true;
if ( isPositiveInteger( seed ) ) {
if ( seed > MAX_SEED ) {
throw new RangeError( 'invalid option. `seed` option must be a positive integer less than or equal to the maximum unsigned 32-bit integer. Option: `' + seed + '`.' );
}
seed >>>= 0; // asm type annotation
} else if ( isCollection( seed ) === false || seed.length < 1 ) {
throw new TypeError( 'invalid option. `seed` option must be either a positive integer less than or equal to the maximum unsigned 32-bit integer or an array-like object containing integer values less than or equal to the maximum unsigned 32-bit integer. Option: `' + seed + '`.' );
} else if ( seed.length === 1 ) {
seed = seed[ 0 ];
if ( !isPositiveInteger( seed ) ) {
throw new TypeError( 'invalid option. `seed` option must be either a positive integer less than or equal to the maximum unsigned 32-bit integer or an array-like object containing integer values less than or equal to the maximum unsigned 32-bit integer. Option: `' + seed + '`.' );
}
if ( seed > MAX_SEED ) {
throw new RangeError( 'invalid option. `seed` option must be either a positive integer less than or equal to the maximum unsigned 32-bit integer or an array-like object containing integer values less than or equal to the maximum unsigned 32-bit integer. Option: `' + seed + '`.' );
}
seed >>>= 0; // asm type annotation
} else {
slen = seed.length;
STATE = new Uint32Array( STATE_FIXED_LENGTH+slen );
// Initialize sections:
STATE[ 0 ] = STATE_ARRAY_VERSION;
STATE[ 1 ] = NUM_STATE_SECTIONS;
STATE[ STATE_SECTION_OFFSET ] = N;
STATE[ OTHER_SECTION_OFFSET ] = 1;
STATE[ OTHER_SECTION_OFFSET+1 ] = N; // state index
STATE[ SEED_SECTION_OFFSET ] = slen;
// Copy the provided seed array to prevent external mutation, as mutation would lead to an inability to reproduce PRNG values according to the PRNG's stated seed:
gcopy.ndarray( slen, seed, 1, 0, STATE, 1, SEED_SECTION_OFFSET+1 );
// Create a state "view":
state = new Uint32Array( STATE.buffer, STATE.byteOffset+((STATE_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), N );
// Create a seed "view":
seed = new Uint32Array( STATE.buffer, STATE.byteOffset+((SEED_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), slen );
// Initialize the internal PRNG state:
state = createState( state, N, SEED_ARRAY_INIT_STATE );
state = initState( state, N, seed, slen );
}
} else {
seed = randuint32() >>> 0; // asm type annotation
}
}
} else {
seed = randuint32() >>> 0; // asm type annotation
}
if ( state === void 0 ) {
STATE = new Uint32Array( STATE_FIXED_LENGTH+1 );
// Initialize sections:
STATE[ 0 ] = STATE_ARRAY_VERSION;
STATE[ 1 ] = NUM_STATE_SECTIONS;
STATE[ STATE_SECTION_OFFSET ] = N;
STATE[ OTHER_SECTION_OFFSET ] = 1;
STATE[ OTHER_SECTION_OFFSET+1 ] = N; // state index
STATE[ SEED_SECTION_OFFSET ] = 1;
STATE[ SEED_SECTION_OFFSET+1 ] = seed;
// Create a state "view":
state = new Uint32Array( STATE.buffer, STATE.byteOffset+((STATE_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), N );
// Create a seed "view":
seed = new Uint32Array( STATE.buffer, STATE.byteOffset+((SEED_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), 1 );
// Initialize the internal PRNG state:
state = createState( state, N, seed );
}
// Note: property order matters in order to maintain consistency of PRNG "shape" (hidden classes).
setReadOnly( mt19937, 'NAME', 'mt19937' );
setReadOnlyAccessor( mt19937, 'seed', getSeed );
setReadOnlyAccessor( mt19937, 'seedLength', getSeedLength );
setReadWriteAccessor( mt19937, 'state', getState, setState );
setReadOnlyAccessor( mt19937, 'stateLength', getStateLength );
setReadOnlyAccessor( mt19937, 'byteLength', getStateSize );
setReadOnly( mt19937, 'toJSON', toJSON );
setReadOnly( mt19937, 'MIN', 1 );
setReadOnly( mt19937, 'MAX', UINT32_MAX );
setReadOnly( mt19937, 'normalized', normalized );
setReadOnly( normalized, 'NAME', mt19937.NAME );
setReadOnlyAccessor( normalized, 'seed', getSeed );
setReadOnlyAccessor( normalized, 'seedLength', getSeedLength );
setReadWriteAccessor( normalized, 'state', getState, setState );
setReadOnlyAccessor( normalized, 'stateLength', getStateLength );
setReadOnlyAccessor( normalized, 'byteLength', getStateSize );
setReadOnly( normalized, 'toJSON', toJSON );
setReadOnly( normalized, 'MIN', 0.0 );
setReadOnly( normalized, 'MAX', MAX_NORMALIZED );
return mt19937;
/**
* Returns the PRNG seed.
*
* @private
* @returns {PRNGSeedMT19937} seed
*/
function getSeed() {
var len = STATE[ SEED_SECTION_OFFSET ];
return gcopy( len, seed, 1, new Uint32Array( len ), 1 );
}
/**
* Returns the PRNG seed length.
*
* @private
* @returns {PositiveInteger} seed length
*/
function getSeedLength() {
return STATE[ SEED_SECTION_OFFSET ];
}
/**
* Returns the PRNG state length.
*
* @private
* @returns {PositiveInteger} state length
*/
function getStateLength() {
return STATE.length;
}
/**
* Returns the PRNG state size (in bytes).
*
* @private
* @returns {PositiveInteger} state size (in bytes)
*/
function getStateSize() {
return STATE.byteLength;
}
/**
* Returns the current PRNG state.
*
* ## Notes
*
* - The PRNG state array is comprised of a preamble followed by `3` sections:
*
* 0. preamble (version + number of sections)
* 1. internal PRNG state
* 2. auxiliary state information
* 3. PRNG seed
*
* - The first element of the PRNG state array preamble is the state array schema version.
*
* - The second element of the PRNG state array preamble is the number of state array sections (i.e., `3`).
*
* - The first element of each section following the preamble specifies the section length. The remaining section elements comprise the section contents.
*
* @private
* @returns {PRNGStateMT19937} current state
*/
function getState() {
var len = STATE.length;
return gcopy( len, STATE, 1, new Uint32Array( len ), 1 );
}
/**
* Sets the PRNG state.
*
* ## Notes
*
* - If PRNG state is "shared" (meaning a state array was provided during PRNG creation and **not** copied) and one sets the generator state to a state array having a different length, the PRNG does **not** update the existing shared state and, instead, points to the newly provided state array. In order to synchronize PRNG output according to the new shared state array, the state array for **each** relevant PRNG must be **explicitly** set.
* - If PRNG state is "shared" and one sets the generator state to a state array of the same length, the PRNG state is updated (along with the state of all other PRNGs sharing the PRNG's state array).
*
* @private
* @param {PRNGStateMT19937} s - generator state
* @throws {TypeError} must provide a `Uint32Array`
* @throws {Error} must provide a valid state
*/
function setState( s ) {
var err;
if ( !isUint32Array( s ) ) {
throw new TypeError( 'invalid argument. Must provide a Uint32Array. Value: `' + s + '`.' );
}
err = verifyState( s, false );
if ( err ) {
throw err;
}
if ( opts.copy === false ) {
if ( opts.state && s.length === STATE.length ) {
gcopy( s.length, s, 1, STATE, 1 ); // update current shared state
} else {
STATE = s; // point to new shared state
opts.state = true; // setting this flag allows updating a shared state even if a state array was not provided at PRNG creation
}
} else {
// Check if we can reuse allocated memory...
if ( s.length !== STATE.length ) {
STATE = new Uint32Array( s.length ); // reallocate
}
gcopy( s.length, s, 1, STATE, 1 );
}
// Create a new state "view":
state = new Uint32Array( STATE.buffer, STATE.byteOffset+((STATE_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), N );
// Create a new seed "view":
seed = new Uint32Array( STATE.buffer, STATE.byteOffset+((SEED_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), STATE[ SEED_SECTION_OFFSET ] );
}
/**
* Serializes the pseudorandom number generator as a JSON object.
*
* ## Notes
*
* - `JSON.stringify()` implicitly calls this method when stringifying a PRNG.
*
* @private
* @returns {Object} JSON representation
*/
function toJSON() {
var out = {};
out.type = 'PRNG';
out.name = mt19937.NAME;
out.state = typedarray2json( STATE );
out.params = [];
return out;
}
/**
* Generates a pseudorandom integer on the interval \\( [1,2^{32}-1) \\).
*
* @private
* @returns {uinteger32} pseudorandom integer
*
* @example
* var r = mt19937();
* // returns <number>
*/
function mt19937() {
var r;
var i;
// Retrieve the current state index:
i = STATE[ OTHER_SECTION_OFFSET+1 ];
// Determine whether we need to update the PRNG state:
if ( i >= N ) {
state = twist( state );
i = 0;
}
// Get the next word of "raw"/untempered state:
r = state[ i ];
// Update the state index:
STATE[ OTHER_SECTION_OFFSET+1 ] = i + 1;
// Tempering transform to compensate for the reduced dimensionality of equidistribution:
r ^= r >>> 11;
r ^= ( r << 7 ) & TEMPERING_COEFFICIENT_1;
r ^= ( r << 15 ) & TEMPERING_COEFFICIENT_2;
r ^= r >>> 18;
return r >>> 0;
}
/**
* Generates a pseudorandom number on the interval \\( [0,1) \\).
*
* ## Notes
*
* - The original C implementation credits Isaku Wada for this algorithm (2002/01/09).
*
* @private
* @returns {number} pseudorandom number
*
* @example
* var r = normalized();
* // returns <number>
*/
function normalized() {
var x = mt19937() >>> 5;
var y = mt19937() >>> 6;
return ( (x*TWO_26)+y ) * FLOAT64_NORMALIZATION_CONSTANT;
}
}
// EXPORTS //
module.exports = factory;
},{"./rand_uint32.js":343,"@stdlib/array/to-json":17,"@stdlib/array/uint32":23,"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-boolean":81,"@stdlib/assert/is-collection":90,"@stdlib/assert/is-plain-object":147,"@stdlib/assert/is-positive-integer":149,"@stdlib/assert/is-uint32array":170,"@stdlib/blas/base/gcopy":225,"@stdlib/constants/float64/max-safe-integer":243,"@stdlib/constants/uint32/max":255,"@stdlib/math/base/special/max":281,"@stdlib/math/base/special/uimul":301,"@stdlib/utils/define-nonenumerable-read-only-accessor":394,"@stdlib/utils/define-nonenumerable-read-only-property":396,"@stdlib/utils/define-nonenumerable-read-write-accessor":398}],341:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* A 32-bit Mersenne Twister pseudorandom number generator.
*
* @module @stdlib/random/base/mt19937
*
* @example
* var mt19937 = require( '@stdlib/random/base/mt19937' );
*
* var v = mt19937();
* // returns <number>
*
* @example
* var factory = require( '@stdlib/random/base/mt19937' ).factory;
*
* var mt19937 = factory({
* 'seed': 1234
* });
*
* var v = mt19937();
* // returns 822569775
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var mt19937 = require( './main.js' );
var factory = require( './factory.js' );
// MAIN //
setReadOnly( mt19937, 'factory', factory );
// EXPORTS //
module.exports = mt19937;
},{"./factory.js":340,"./main.js":342,"@stdlib/utils/define-nonenumerable-read-only-property":396}],342:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var factory = require( './factory.js' );
var randuint32 = require( './rand_uint32.js' );
// MAIN //
/**
* Generates a pseudorandom integer on the interval \\( [1,2^{32}-1) \\).
*
* ## Method
*
* - When generating normalized double-precision floating-point numbers, we first generate two pseudorandom integers \\( x \\) and \\( y \\) on the interval \\( [1,2^{32}-1) \\) for a combined \\( 64 \\) random bits.
*
* - We would like \\( 53 \\) random bits to generate a 53-bit precision integer and, thus, want to discard \\( 11 \\) of the generated bits.
*
* - We do so by discarding \\( 5 \\) bits from \\( x \\) and \\( 6 \\) bits from \\( y \\).
*
* - Accordingly, \\( x \\) contains \\( 27 \\) random bits, which are subsequently shifted left \\( 26 \\) bits (multiplied by \\( 2^{26} \\), and \\( y \\) contains \\( 26 \\) random bits to fill in the lower \\( 26 \\) bits. When summed, they combine to comprise \\( 53 \\) random bits of a double-precision floating-point integer.
*
* - As an example, suppose, for the sake of argument, the 32-bit PRNG generates the maximum unsigned 32-bit integer \\( 2^{32}-1 \\) twice in a row. Then,
*
* ```javascript
* x = 4294967295 >>> 5; // 00000111111111111111111111111111
* y = 4294967295 >>> 6; // 00000011111111111111111111111111
* ```
*
* Multiplying \\( x \\) by \\( 2^{26} \\) returns \\( 9007199187632128 \\), which, in binary, is
*
* ```binarystring
* 0 10000110011 11111111111111111111 11111100000000000000000000000000
* ```
*
* Adding \\( y \\) yields \\( 9007199254740991 \\) (the maximum "safe" double-precision floating-point integer value), which, in binary, is
*
* ```binarystring
* 0 10000110011 11111111111111111111 11111111111111111111111111111111
* ```
*
* - Similarly, suppose the 32-bit PRNG generates the following values
*
* ```javascript
* x = 1 >>> 5; // 0 => 00000000000000000000000000000000
* y = 64 >>> 6; // 1 => 00000000000000000000000000000001
* ```
*
* Multiplying \\( x \\) by \\( 2^{26} \\) returns \\( 0 \\), which, in binary, is
*
* ```binarystring
* 0 00000000000 00000000000000000000 00000000000000000000000000000000
* ```
*
* Adding \\( y \\) yields \\( 1 \\), which, in binary, is
*
* ```binarystring
* 0 01111111111 00000000000000000000 00000000000000000000000000000000
* ```
*
* - As different combinations of \\( x \\) and \\( y \\) are generated, different combinations of double-precision floating-point exponent and significand bits will be toggled, thus generating pseudorandom double-precision floating-point numbers.
*
*
* ## References
*
* - Matsumoto, Makoto, and Takuji Nishimura. 1998. "Mersenne Twister: A 623-dimensionally Equidistributed Uniform Pseudo-random Number Generator." _ACM Transactions on Modeling and Computer Simulation_ 8 (1). New York, NY, USA: ACM: 3–30. doi:[10.1145/272991.272995][@matsumoto:1998a].
* - Harase, Shin. 2017. "Conversion of Mersenne Twister to double-precision floating-point numbers." _ArXiv_ abs/1708.06018 (September). <https://arxiv.org/abs/1708.06018>.
*
* [@matsumoto:1998a]: https://doi.org/10.1145/272991.272995
*
*
* @function mt19937
* @type {PRNG}
* @returns {PositiveInteger} pseudorandom integer
*
* @example
* var v = mt19937();
* // returns <number>
*/
var mt19937 = factory({
'seed': randuint32()
});
// EXPORTS //
module.exports = mt19937;
},{"./factory.js":340,"./rand_uint32.js":343}],343:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var UINT32_MAX = require( '@stdlib/constants/uint32/max' );
var floor = require( '@stdlib/math/base/special/floor' );
// VARIABLES //
var MAX = UINT32_MAX - 1;
// MAIN //
/**
* Returns a pseudorandom integer on the interval \\([1, 2^{32}-1)\\).
*
* @private
* @returns {PositiveInteger} pseudorandom integer
*
* @example
* var v = randuint32();
* // returns <number>
*/
function randuint32() {
var v = floor( 1.0 + (MAX*Math.random()) ); // eslint-disable-line stdlib/no-builtin-math
return v >>> 0; // asm type annotation
}
// EXPORTS //
module.exports = randuint32;
},{"@stdlib/constants/uint32/max":255,"@stdlib/math/base/special/floor":277}],344:[function(require,module,exports){
module.exports={
"name": "mt19937",
"copy": true
}
},{}],345:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var setReadOnlyAccessor = require( '@stdlib/utils/define-nonenumerable-read-only-accessor' );
var setReadWriteAccessor = require( '@stdlib/utils/define-nonenumerable-read-write-accessor' );
var isObject = require( '@stdlib/assert/is-plain-object' );
var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive;
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var typedarray2json = require( '@stdlib/array/to-json' );
var defaults = require( './defaults.json' );
var PRNGS = require( './prngs.js' );
// MAIN //
/**
* Returns a pseudorandom number generator for generating uniformly distributed random numbers on the interval \\( [0,1) \\).
*
* @param {Options} [options] - function options
* @param {string} [options.name='mt19937'] - name of pseudorandom number generator
* @param {*} [options.seed] - pseudorandom number generator seed
* @param {*} [options.state] - pseudorandom number generator state
* @param {boolean} [options.copy=true] - boolean indicating whether to copy a provided pseudorandom number generator state
* @throws {TypeError} must provide an object
* @throws {TypeError} must provide valid options
* @throws {Error} must provide the name of a supported pseudorandom number generator
* @returns {PRNG} pseudorandom number generator
*
* @example
* var uniform = factory();
* var v = uniform();
* // returns <number>
*
* @example
* var uniform = factory({
* 'name': 'minstd'
* });
* var v = uniform();
* // returns <number>
*
* @example
* var uniform = factory({
* 'seed': 12345
* });
* var v = uniform();
* // returns <number>
*
* @example
* var uniform = factory({
* 'name': 'minstd',
* 'seed': 12345
* });
* var v = uniform();
* // returns <number>
*/
function factory( options ) {
var opts;
var rand;
var prng;
opts = {
'name': defaults.name,
'copy': defaults.copy
};
if ( arguments.length ) {
if ( !isObject( options ) ) {
throw new TypeError( 'invalid argument. Must provide an object. Value: `' + options + '`.' );
}
if ( hasOwnProp( options, 'name' ) ) {
opts.name = options.name;
}
if ( hasOwnProp( options, 'state' ) ) {
opts.state = options.state;
if ( opts.state === void 0 ) {
throw new TypeError( 'invalid option. `state` option cannot be undefined. Option: `' + opts.state + '`.' );
}
} else if ( hasOwnProp( options, 'seed' ) ) {
opts.seed = options.seed;
if ( opts.seed === void 0 ) {
throw new TypeError( 'invalid option. `seed` option cannot be undefined. Option: `' + opts.seed + '`.' );
}
}
if ( hasOwnProp( options, 'copy' ) ) {
opts.copy = options.copy;
if ( !isBoolean( opts.copy ) ) {
throw new TypeError( 'invalid option. `copy` option must be a boolean. Option: `' + opts.copy + '`.' );
}
}
}
prng = PRNGS[ opts.name ];
if ( prng === void 0 ) {
throw new Error( 'invalid option. Unrecognized/unsupported PRNG. Option: `' + opts.name + '`.' );
}
if ( opts.state === void 0 ) {
if ( opts.seed === void 0 ) {
rand = prng.factory();
} else {
rand = prng.factory({
'seed': opts.seed
});
}
} else {
rand = prng.factory({
'state': opts.state,
'copy': opts.copy
});
}
setReadOnly( uniform, 'NAME', 'randu' );
setReadOnlyAccessor( uniform, 'seed', getSeed );
setReadOnlyAccessor( uniform, 'seedLength', getSeedLength );
setReadWriteAccessor( uniform, 'state', getState, setState );
setReadOnlyAccessor( uniform, 'stateLength', getStateLength );
setReadOnlyAccessor( uniform, 'byteLength', getStateSize );
setReadOnly( uniform, 'toJSON', toJSON );
setReadOnly( uniform, 'PRNG', rand );
setReadOnly( uniform, 'MIN', rand.normalized.MIN );
setReadOnly( uniform, 'MAX', rand.normalized.MAX );
return uniform;
/**
* Returns the PRNG seed.
*
* @private
* @returns {*} seed
*/
function getSeed() {
return rand.seed;
}
/**
* Returns the PRNG seed length.
*
* @private
* @returns {PositiveInteger} seed length
*/
function getSeedLength() {
return rand.seedLength;
}
/**
* Returns the PRNG state length.
*
* @private
* @returns {PositiveInteger} state length
*/
function getStateLength() {
return rand.stateLength;
}
/**
* Returns the PRNG state size (in bytes).
*
* @private
* @returns {PositiveInteger} state size (in bytes)
*/
function getStateSize() {
return rand.byteLength;
}
/**
* Returns the current pseudorandom number generator state.
*
* @private
* @returns {*} current state
*/
function getState() {
return rand.state;
}
/**
* Sets the pseudorandom number generator state.
*
* @private
* @param {*} s - generator state
* @throws {Error} must provide a valid state
*/
function setState( s ) {
rand.state = s;
}
/**
* Serializes the pseudorandom number generator as a JSON object.
*
* ## Notes
*
* - `JSON.stringify()` implicitly calls this method when stringifying a PRNG.
*
* @private
* @returns {Object} JSON representation
*/
function toJSON() {
var out = {};
out.type = 'PRNG';
out.name = uniform.NAME + '-' + rand.NAME;
out.state = typedarray2json( rand.state );
out.params = [];
return out;
}
/**
* Returns a uniformly distributed pseudorandom number on the interval \\( [0,1) \\).
*
* @private
* @returns {number} pseudorandom number
*
* @example
* var v = uniform();
* // returns <number>
*/
function uniform() {
return rand.normalized();
}
}
// EXPORTS //
module.exports = factory;
},{"./defaults.json":344,"./prngs.js":348,"@stdlib/array/to-json":17,"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-boolean":81,"@stdlib/assert/is-plain-object":147,"@stdlib/utils/define-nonenumerable-read-only-accessor":394,"@stdlib/utils/define-nonenumerable-read-only-property":396,"@stdlib/utils/define-nonenumerable-read-write-accessor":398}],346:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Uniformly distributed pseudorandom numbers on the interval \\( [0,1) \\).
*
* @module @stdlib/random/base/randu
*
* @example
* var randu = require( '@stdlib/random/base/randu' );
*
* var v = randu();
* // returns <number>
*
* @example
* var factory = require( '@stdlib/random/base/randu' ).factory;
*
* var randu = factory({
* 'name': 'minstd',
* 'seed': 12345
* });
*
* var v = randu();
* // returns <number>
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var randu = require( './main.js' );
var factory = require( './factory.js' );
// MAIN //
setReadOnly( randu, 'factory', factory );
// EXPORTS //
module.exports = randu;
},{"./factory.js":345,"./main.js":347,"@stdlib/utils/define-nonenumerable-read-only-property":396}],347:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var factory = require( './factory.js' );
// MAIN //
/**
* Returns a uniformly distributed random number on the interval \\( [0,1) \\).
*
* @name randu
* @type {PRNG}
* @returns {number} pseudorandom number
*
* @example
* var v = randu();
* // returns <number>
*/
var randu = factory();
// EXPORTS //
module.exports = randu;
},{"./factory.js":345}],348:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var prngs = {};
prngs[ 'minstd' ] = require( '@stdlib/random/base/minstd' );
prngs[ 'minstd-shuffle' ] = require( '@stdlib/random/base/minstd-shuffle' );
prngs[ 'mt19937' ] = require( '@stdlib/random/base/mt19937' );
// EXPORTS //
module.exports = prngs;
},{"@stdlib/random/base/minstd":337,"@stdlib/random/base/minstd-shuffle":333,"@stdlib/random/base/mt19937":341}],349:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Regular expression to match a newline character sequence.
*
* @module @stdlib/regexp/eol
*
* @example
* var reEOL = require( '@stdlib/regexp/eol' );
* var RE_EOL = reEOL();
*
* var bool = RE_EOL.test( '\n' );
* // returns true
*
* bool = RE_EOL.test( '\\r\\n' );
* // returns false
*
* @example
* var reEOL = require( '@stdlib/regexp/eol' );
* var replace = require( '@stdlib/string/replace' );
*
* var RE_EOL = reEOL({
* 'flags': 'g'
* });
* var str = '1\n2\n3';
* var out = replace( str, RE_EOL, '' );
*
* @example
* var reEOL = require( '@stdlib/regexp/eol' );
* var bool = reEOL.REGEXP.test( '\r\n' );
* // returns true
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var reEOL = require( './main.js' );
var REGEXP_CAPTURE = require( './regexp_capture.js' );
var REGEXP = require( './regexp.js' );
// MAIN //
setReadOnly( reEOL, 'REGEXP', REGEXP );
setReadOnly( reEOL, 'REGEXP_CAPTURE', REGEXP_CAPTURE );
// EXPORTS //
module.exports = reEOL;
},{"./main.js":350,"./regexp.js":351,"./regexp_capture.js":352,"@stdlib/utils/define-nonenumerable-read-only-property":396}],350:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var validate = require( './validate.js' );
// VARIABLES //
var REGEXP_STRING = '\\r?\\n';
// MAIN //
/**
* Returns a regular expression to match a newline character sequence.
*
* @param {Options} [options] - function options
* @param {string} [options.flags=''] - regular expression flags
* @param {boolean} [options.capture=false] - boolean indicating whether to create a capture group for the match
* @throws {TypeError} options argument must be an object
* @throws {TypeError} must provide valid options
* @returns {RegExp} regular expression
*
* @example
* var RE_EOL = reEOL();
* var bool = RE_EOL.test( '\r\n' );
* // returns true
*
* @example
* var replace = require( '@stdlib/string/replace' );
*
* var RE_EOL = reEOL({
* 'flags': 'g'
* });
* var str = '1\n2\n3';
* var out = replace( str, RE_EOL, '' );
*/
function reEOL( options ) {
var opts;
var err;
if ( arguments.length > 0 ) {
opts = {};
err = validate( opts, options );
if ( err ) {
throw err;
}
if ( opts.capture ) {
return new RegExp( '('+REGEXP_STRING+')', opts.flags );
}
return new RegExp( REGEXP_STRING, opts.flags );
}
return /\r?\n/;
}
// EXPORTS //
module.exports = reEOL;
},{"./validate.js":353}],351:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var reEOL = require( './main.js' );
// MAIN //
/**
* Matches a newline character sequence.
*
* Regular expression: `/\r?\n/`
*
* - `\r?`
* - match a carriage return character (optional)
*
* - `\n`
* - match a line feed character
*
* @constant
* @type {RegExp}
* @default /\r?\n/
*/
var REGEXP = reEOL();
// EXPORTS //
module.exports = REGEXP;
},{"./main.js":350}],352:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var reEOL = require( './main.js' );
// MAIN //
/**
* Captures a newline character sequence.
*
* Regular expression: `/\r?\n/`
*
* - `()`
* - capture
*
* - `\r?`
* - match a carriage return character (optional)
*
* - `\n`
* - match a line feed character
*
* @constant
* @type {RegExp}
* @default /(\r?\n)/
*/
var REGEXP_CAPTURE = reEOL({
'capture': true
});
// EXPORTS //
module.exports = REGEXP_CAPTURE;
},{"./main.js":350}],353:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isObject = require( '@stdlib/assert/is-plain-object' );
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive;
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
// MAIN //
/**
* Validates function options.
*
* @private
* @param {Object} opts - destination object
* @param {Options} options - function options
* @param {string} [options.flags] - regular expression flags
* @param {boolean} [options.capture] - boolean indicating whether to wrap a regular expression matching a decimal number with a capture group
* @returns {(Error|null)} null or an error object
*
* @example
* var opts = {};
* var options = {
* 'flags': 'gm'
* };
* var err = validate( opts, options );
* if ( err ) {
* throw err;
* }
*/
function validate( opts, options ) {
if ( !isObject( options ) ) {
return new TypeError( 'invalid argument. Options must be an object. Value: `' + options + '`.' );
}
if ( hasOwnProp( options, 'flags' ) ) {
opts.flags = options.flags;
if ( !isString( opts.flags ) ) {
return new TypeError( 'invalid option. `flags` option must be a string primitive. Option: `' + opts.flags + '`.' );
}
}
if ( hasOwnProp( options, 'capture' ) ) {
opts.capture = options.capture;
if ( !isBoolean( opts.capture ) ) {
return new TypeError( 'invalid option. `capture` option must be a boolean primitive. Option: `' + opts.capture + '`.' );
}
}
return null;
}
// EXPORTS //
module.exports = validate;
},{"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-boolean":81,"@stdlib/assert/is-plain-object":147,"@stdlib/assert/is-string":158}],354:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Regular expression to capture everything that is not a space immediately after the `function` keyword and before the first left parenthesis.
*
* @module @stdlib/regexp/function-name
*
* @example
* var reFunctionName = require( '@stdlib/regexp/function-name' );
* var RE_FUNCTION_NAME = reFunctionName();
*
* function fname( fcn ) {
* return RE_FUNCTION_NAME.exec( fcn.toString() )[ 1 ];
* }
*
* var fn = fname( Math.sqrt );
* // returns 'sqrt'
*
* fn = fname( Int8Array );
* // returns 'Int8Array'
*
* fn = fname( Object.prototype.toString );
* // returns 'toString'
*
* fn = fname( function(){} );
* // returns ''
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var reFunctionName = require( './main.js' );
var REGEXP = require( './regexp.js' );
// MAIN //
setReadOnly( reFunctionName, 'REGEXP', REGEXP );
// EXPORTS //
module.exports = reFunctionName;
},{"./main.js":355,"./regexp.js":356,"@stdlib/utils/define-nonenumerable-read-only-property":396}],355:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Returns a regular expression to capture everything that is not a space immediately after the `function` keyword and before the first left parenthesis.
*
* @returns {RegExp} regular expression
*
* @example
* var RE_FUNCTION_NAME = reFunctionName();
*
* function fname( fcn ) {
* return RE_FUNCTION_NAME.exec( fcn.toString() )[ 1 ];
* }
*
* var fn = fname( Math.sqrt );
* // returns 'sqrt'
*
* fn = fname( Int8Array );
* // returns 'Int8Array'
*
* fn = fname( Object.prototype.toString );
* // returns 'toString'
*
* fn = fname( function(){} );
* // returns ''
*/
function reFunctionName() {
return /^\s*function\s*([^(]*)/i;
}
// EXPORTS //
module.exports = reFunctionName;
},{}],356:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var reFunctionName = require( './main.js' );
// MAIN //
/**
* Captures everything that is not a space immediately after the `function` keyword and before the first left parenthesis.
*
* Regular expression: `/^\s*function\s*([^(]*)/i`
*
* - `/^\s*`
* - Match zero or more spaces at beginning
*
* - `function`
* - Match the word `function`
*
* - `\s*`
* - Match zero or more spaces after the word `function`
*
* - `()`
* - Capture
*
* - `[^(]*`
* - Match anything except a left parenthesis `(` zero or more times
*
* - `/i`
* - ignore case
*
* @constant
* @type {RegExp}
* @default /^\s*function\s*([^(]*)/i
*/
var RE_FUNCTION_NAME = reFunctionName();
// EXPORTS //
module.exports = RE_FUNCTION_NAME;
},{"./main.js":355}],357:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Return a regular expression to parse a regular expression string.
*
* @module @stdlib/regexp/regexp
*
* @example
* var reRegExp = require( '@stdlib/regexp/regexp' );
*
* var RE_REGEXP = reRegExp();
*
* var bool = RE_REGEXP.test( '/^beep$/' );
* // returns true
*
* bool = RE_REGEXP.test( '' );
* // returns false
*
* @example
* var reRegExp = require( '@stdlib/regexp/regexp' );
*
* var RE_REGEXP = reRegExp();
*
* var parts = RE_REGEXP.exec( '/^.*$/ig' );
* // returns [ '/^.*$/ig', '^.*$', 'ig', 'index': 0, 'input': '/^.*$/ig' ]
*/
// MAIN //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var reRegExp = require( './main.js' );
var REGEXP = require( './regexp.js' );
// MAIN //
setReadOnly( reRegExp, 'REGEXP', REGEXP );
// EXPORTS //
module.exports = reRegExp;
// EXPORTS //
module.exports = reRegExp;
},{"./main.js":358,"./regexp.js":359,"@stdlib/utils/define-nonenumerable-read-only-property":396}],358:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Returns a regular expression to parse a regular expression string.
*
* @returns {RegExp} regular expression
*
* @example
* var RE_REGEXP = reRegExp();
*
* var bool = RE_REGEXP.test( '/^beep$/' );
* // returns true
*
* bool = RE_REGEXP.test( '' );
* // returns false
*/
function reRegExp() {
return /^\/((?:\\\/|[^\/])+)\/([imgy]*)$/; // eslint-disable-line no-useless-escape
}
// EXPORTS //
module.exports = reRegExp;
},{}],359:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var reRegExp = require( './main.js' );
// MAIN //
/**
* Matches parts of a regular expression string.
*
* Regular expression: `/^\/((?:\\\/|[^\/])+)\/([imgy]*)$/`
*
* - `/^\/`
* - match a string that begins with a `/`
*
* - `()`
* - capture
*
* - `(?:)+`
* - capture, but do not remember, a group of characters which occur one or more times
*
* - `\\\/`
* - match the literal `\/`
*
* - `|`
* - OR
*
* - `[^\/]`
* - anything which is not the literal `\/`
*
* - `\/`
* - match the literal `/`
*
* - `([imgy]*)`
* - capture any characters matching `imgy` occurring zero or more times
*
* - `$/`
* - string end
*
*
* @constant
* @type {RegExp}
* @default /^\/((?:\\\/|[^\/])+)\/([imgy]*)$/
*/
var RE_REGEXP = reRegExp();
// EXPORTS //
module.exports = RE_REGEXP;
},{"./main.js":358}],360:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2020 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var bench = require( '@stdlib/bench' );
var randu = require( '@stdlib/random/base/randu' );
var isnanf = require( '@stdlib/math/base/assert/is-nanf' );
var pow = require( '@stdlib/math/base/special/pow' );
var Float32Array = require( '@stdlib/array/float32' );
var pkg = require( './../package.json' ).name;
var snanvarianceyc = require( './../lib/snanvarianceyc.js' );
// FUNCTIONS //
/**
* Creates a benchmark function.
*
* @private
* @param {PositiveInteger} len - array length
* @returns {Function} benchmark function
*/
function createBenchmark( len ) {
var x;
var i;
x = new Float32Array( len );
for ( i = 0; i < x.length; i++ ) {
if ( randu() < 0.2 ) {
x[ i ] = NaN;
} else {
x[ i ] = ( randu()*20.0 ) - 10.0;
}
}
return benchmark;
function benchmark( b ) {
var v;
var i;
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
v = snanvarianceyc( x.length, 1, x, 1 );
if ( isnanf( v ) ) {
b.fail( 'should not return NaN' );
}
}
b.toc();
if ( isnanf( v ) ) {
b.fail( 'should not return NaN' );
}
b.pass( 'benchmark finished' );
b.end();
}
}
// MAIN //
/**
* Main execution sequence.
*
* @private
*/
function main() {
var len;
var min;
var max;
var f;
var i;
min = 1; // 10^min
max = 6; // 10^max
for ( i = min; i <= max; i++ ) {
len = pow( 10, i );
f = createBenchmark( len );
bench( pkg+':len='+len, f );
}
}
main();
},{"./../lib/snanvarianceyc.js":365,"./../package.json":366,"@stdlib/array/float32":2,"@stdlib/bench":224,"@stdlib/math/base/assert/is-nanf":267,"@stdlib/math/base/special/pow":286,"@stdlib/random/base/randu":346}],361:[function(require,module,exports){
(function (__dirname){(function (){
/**
* @license Apache-2.0
*
* Copyright (c) 2020 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var resolve = require( 'path' ).resolve;
var bench = require( '@stdlib/bench' );
var randu = require( '@stdlib/random/base/randu' );
var isnanf = require( '@stdlib/math/base/assert/is-nanf' );
var pow = require( '@stdlib/math/base/special/pow' );
var Float32Array = require( '@stdlib/array/float32' );
var tryRequire = require( '@stdlib/utils/try-require' );
var pkg = require( './../package.json' ).name;
// VARIABLES //
var snanvarianceyc = tryRequire( resolve( __dirname, './../lib/snanvarianceyc.native.js' ) );
var opts = {
'skip': ( snanvarianceyc instanceof Error )
};
// FUNCTIONS //
/**
* Creates a benchmark function.
*
* @private
* @param {PositiveInteger} len - array length
* @returns {Function} benchmark function
*/
function createBenchmark( len ) {
var x;
var i;
x = new Float32Array( len );
for ( i = 0; i < x.length; i++ ) {
if ( randu() < 0.2 ) {
x[ i ] = NaN;
} else {
x[ i ] = ( randu()*20.0 ) - 10.0;
}
}
return benchmark;
function benchmark( b ) {
var v;
var i;
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
v = snanvarianceyc( x.length, 1, x, 1 );
if ( isnanf( v ) ) {
b.fail( 'should not return NaN' );
}
}
b.toc();
if ( isnanf( v ) ) {
b.fail( 'should not return NaN' );
}
b.pass( 'benchmark finished' );
b.end();
}
}
// MAIN //
/**
* Main execution sequence.
*
* @private
*/
function main() {
var len;
var min;
var max;
var f;
var i;
min = 1; // 10^min
max = 6; // 10^max
for ( i = min; i <= max; i++ ) {
len = pow( 10, i );
f = createBenchmark( len );
bench( pkg+'::native:len='+len, opts, f );
}
}
main();
}).call(this)}).call(this,"/lib/node_modules/@stdlib/stats/base/snanvarianceyc/benchmark")
},{"./../package.json":366,"@stdlib/array/float32":2,"@stdlib/bench":224,"@stdlib/math/base/assert/is-nanf":267,"@stdlib/math/base/special/pow":286,"@stdlib/random/base/randu":346,"@stdlib/utils/try-require":468,"path":480}],362:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2020 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var bench = require( '@stdlib/bench' );
var randu = require( '@stdlib/random/base/randu' );
var isnanf = require( '@stdlib/math/base/assert/is-nanf' );
var pow = require( '@stdlib/math/base/special/pow' );
var Float32Array = require( '@stdlib/array/float32' );
var pkg = require( './../package.json' ).name;
var snanvarianceyc = require( './../lib/ndarray.js' );
// FUNCTIONS //
/**
* Creates a benchmark function.
*
* @private
* @param {PositiveInteger} len - array length
* @returns {Function} benchmark function
*/
function createBenchmark( len ) {
var x;
var i;
x = new Float32Array( len );
for ( i = 0; i < x.length; i++ ) {
if ( randu() < 0.2 ) {
x[ i ] = NaN;
} else {
x[ i ] = ( randu()*20.0 ) - 10.0;
}
}
return benchmark;
function benchmark( b ) {
var v;
var i;
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
v = snanvarianceyc( x.length, 1, x, 1, 0 );
if ( isnanf( v ) ) {
b.fail( 'should not return NaN' );
}
}
b.toc();
if ( isnanf( v ) ) {
b.fail( 'should not return NaN' );
}
b.pass( 'benchmark finished' );
b.end();
}
}
// MAIN //
/**
* Main execution sequence.
*
* @private
*/
function main() {
var len;
var min;
var max;
var f;
var i;
min = 1; // 10^min
max = 6; // 10^max
for ( i = min; i <= max; i++ ) {
len = pow( 10, i );
f = createBenchmark( len );
bench( pkg+':ndarray:len='+len, f );
}
}
main();
},{"./../lib/ndarray.js":364,"./../package.json":366,"@stdlib/array/float32":2,"@stdlib/bench":224,"@stdlib/math/base/assert/is-nanf":267,"@stdlib/math/base/special/pow":286,"@stdlib/random/base/randu":346}],363:[function(require,module,exports){
(function (__dirname){(function (){
/**
* @license Apache-2.0
*
* Copyright (c) 2020 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var resolve = require( 'path' ).resolve;
var bench = require( '@stdlib/bench' );
var randu = require( '@stdlib/random/base/randu' );
var isnanf = require( '@stdlib/math/base/assert/is-nanf' );
var pow = require( '@stdlib/math/base/special/pow' );
var Float32Array = require( '@stdlib/array/float32' );
var tryRequire = require( '@stdlib/utils/try-require' );
var pkg = require( './../package.json' ).name;
// VARIABLES //
var snanvarianceyc = tryRequire( resolve( __dirname, './../lib/ndarray.native.js' ) );
var opts = {
'skip': ( snanvarianceyc instanceof Error )
};
// FUNCTIONS //
/**
* Creates a benchmark function.
*
* @private
* @param {PositiveInteger} len - array length
* @returns {Function} benchmark function
*/
function createBenchmark( len ) {
var x;
var i;
x = new Float32Array( len );
for ( i = 0; i < x.length; i++ ) {
if ( randu() < 0.2 ) {
x[ i ] = NaN;
} else {
x[ i ] = ( randu()*20.0 ) - 10.0;
}
}
return benchmark;
function benchmark( b ) {
var v;
var i;
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
v = snanvarianceyc( x.length, 1, x, 1, 0 );
if ( isnanf( v ) ) {
b.fail( 'should not return NaN' );
}
}
b.toc();
if ( isnanf( v ) ) {
b.fail( 'should not return NaN' );
}
b.pass( 'benchmark finished' );
b.end();
}
}
// MAIN //
/**
* Main execution sequence.
*
* @private
*/
function main() {
var len;
var min;
var max;
var f;
var i;
min = 1; // 10^min
max = 6; // 10^max
for ( i = min; i <= max; i++ ) {
len = pow( 10, i );
f = createBenchmark( len );
bench( pkg+'::native:ndarray:len='+len, opts, f );
}
}
main();
}).call(this)}).call(this,"/lib/node_modules/@stdlib/stats/base/snanvarianceyc/benchmark")
},{"./../package.json":366,"@stdlib/array/float32":2,"@stdlib/bench":224,"@stdlib/math/base/assert/is-nanf":267,"@stdlib/math/base/special/pow":286,"@stdlib/random/base/randu":346,"@stdlib/utils/try-require":468,"path":480}],364:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2020 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var float64ToFloat32 = require( '@stdlib/number/float64/base/to-float32' );
// MAIN //
/**
* Computes the variance of a single-precision floating-point strided array ignoring `NaN` values and using a one-pass algorithm proposed by Youngs and Cramer.
*
* ## Method
*
* - This implementation uses a one-pass algorithm, as proposed by Youngs and Cramer (1971).
*
* ## References
*
* - Youngs, Edward A., and Elliot M. Cramer. 1971. "Some Results Relevant to Choice of Sum and Sum-of-Product Algorithms." _Technometrics_ 13 (3): 657–65. doi:[10.1080/00401706.1971.10488826](https://doi.org/10.1080/00401706.1971.10488826).
*
* @param {PositiveInteger} N - number of indexed elements
* @param {number} correction - degrees of freedom adjustment
* @param {Float32Array} x - input array
* @param {integer} stride - stride length
* @param {NonNegativeInteger} offset - starting index
* @returns {number} variance
*
* @example
* var Float32Array = require( '@stdlib/array/float32' );
* var floor = require( '@stdlib/math/base/special/floor' );
*
* var x = new Float32Array( [ 2.0, 1.0, 2.0, -2.0, -2.0, 2.0, 3.0, 4.0, NaN, NaN ] );
* var N = floor( x.length / 2 );
*
* var v = snanvarianceyc( N, 1, x, 2, 1 );
* // returns 6.25
*/
function snanvarianceyc( N, correction, x, stride, offset ) {
var sum;
var ix;
var nc;
var S;
var v;
var d;
var n;
var i;
if ( N <= 0 ) {
return NaN;
}
if ( N === 1 || stride === 0 ) {
v = x[ offset ];
if ( v === v && N-correction > 0.0 ) {
return 0.0;
}
return NaN;
}
ix = offset;
// Find the first non-NaN element...
for ( i = 0; i < N; i++ ) {
v = x[ ix ];
if ( v === v ) {
break;
}
ix += stride;
}
if ( i === N ) {
return NaN;
}
ix += stride;
sum = v;
S = 0.0;
i += 1;
n = 1;
for ( i; i < N; i++ ) {
v = x[ ix ];
if ( v === v ) {
n += 1;
sum = float64ToFloat32( sum + v );
d = float64ToFloat32( float64ToFloat32(n*v) - sum );
S = float64ToFloat32( S + float64ToFloat32( float64ToFloat32( float64ToFloat32(1.0/(n*(n-1))) * d ) * d ) ); // eslint-disable-line max-len
}
ix += stride;
}
nc = n - correction;
if ( nc <= 0.0 ) {
return NaN;
}
return float64ToFloat32( S / nc );
}
// EXPORTS //
module.exports = snanvarianceyc;
},{"@stdlib/number/float64/base/to-float32":322}],365:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2020 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var float64ToFloat32 = require( '@stdlib/number/float64/base/to-float32' );
// MAIN //
/**
* Computes the variance of a single-precision floating-point strided array ignoring `NaN` values and using a one-pass algorithm proposed by Youngs and Cramer.
*
* ## Method
*
* - This implementation uses a one-pass algorithm, as proposed by Youngs and Cramer (1971).
*
* ## References
*
* - Youngs, Edward A., and Elliot M. Cramer. 1971. "Some Results Relevant to Choice of Sum and Sum-of-Product Algorithms." _Technometrics_ 13 (3): 657–65. doi:[10.1080/00401706.1971.10488826](https://doi.org/10.1080/00401706.1971.10488826).
*
* @param {PositiveInteger} N - number of indexed elements
* @param {number} correction - degrees of freedom adjustment
* @param {Float32Array} x - input array
* @param {integer} stride - stride length
* @returns {number} variance
*
* @example
* var Float32Array = require( '@stdlib/array/float32' );
*
* var x = new Float32Array( [ 1.0, -2.0, NaN, 2.0 ] );
* var N = x.length;
*
* var v = snanvarianceyc( N, 1, x, 1 );
* // returns ~4.3333
*/
function snanvarianceyc( N, correction, x, stride ) {
var sum;
var ix;
var nc;
var S;
var v;
var d;
var n;
var i;
if ( N <= 0 ) {
return NaN;
}
if ( N === 1 || stride === 0 ) {
v = x[ 0 ];
if ( v === v && N-correction > 0.0 ) {
return 0.0;
}
return NaN;
}
if ( stride < 0 ) {
ix = (1-N) * stride;
} else {
ix = 0;
}
// Find the first non-NaN element...
for ( i = 0; i < N; i++ ) {
v = x[ ix ];
if ( v === v ) {
break;
}
ix += stride;
}
if ( i === N ) {
return NaN;
}
ix += stride;
sum = v;
S = 0.0;
i += 1;
n = 1;
for ( i; i < N; i++ ) {
v = x[ ix ];
if ( v === v ) {
n += 1;
sum = float64ToFloat32( sum + v );
d = float64ToFloat32( float64ToFloat32(n*v) - sum );
S = float64ToFloat32( S + float64ToFloat32( float64ToFloat32( float64ToFloat32(1.0/(n*(n-1))) * d ) * d ) ); // eslint-disable-line max-len
}
ix += stride;
}
nc = n - correction;
if ( nc <= 0.0 ) {
return NaN;
}
return float64ToFloat32( S / nc );
}
// EXPORTS //
module.exports = snanvarianceyc;
},{"@stdlib/number/float64/base/to-float32":322}],366:[function(require,module,exports){
module.exports={
"name": "@stdlib/stats/base/snanvarianceyc",
"version": "0.0.0",
"description": "Calculate the variance of a single-precision floating-point strided array ignoring NaN values and using a one-pass algorithm proposed by Youngs and Cramer.",
"license": "Apache-2.0",
"author": {
"name": "The Stdlib Authors",
"url": "https://github.com/stdlib-js/stdlib/graphs/contributors"
},
"contributors": [
{
"name": "The Stdlib Authors",
"url": "https://github.com/stdlib-js/stdlib/graphs/contributors"
}
],
"main": "./lib",
"browser": "./lib/main.js",
"gypfile": true,
"directories": {
"benchmark": "./benchmark",
"doc": "./docs",
"example": "./examples",
"include": "./include",
"lib": "./lib",
"src": "./src",
"test": "./test"
},
"types": "./docs/types",
"scripts": {},
"homepage": "https://github.com/stdlib-js/stdlib",
"repository": {
"type": "git",
"url": "git://github.com/stdlib-js/stdlib.git"
},
"bugs": {
"url": "https://github.com/stdlib-js/stdlib/issues"
},
"dependencies": {},
"devDependencies": {},
"engines": {
"node": ">=0.10.0",
"npm": ">2.7.0"
},
"os": [
"aix",
"darwin",
"freebsd",
"linux",
"macos",
"openbsd",
"sunos",
"win32",
"windows"
],
"keywords": [
"stdlib",
"stdmath",
"statistics",
"stats",
"mathematics",
"math",
"variance",
"var",
"deviation",
"dispersion",
"sample variance",
"unbiased",
"stdev",
"std",
"standard deviation",
"strided",
"strided array",
"typed",
"array",
"float32",
"float",
"single",
"float32array"
],
"__stdlib__": {}
}
},{}],367:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var logger = require( 'debug' );
// VARIABLES //
var debug = logger( 'transform-stream:transform' );
// MAIN //
/**
* Implements the `_transform` method as a pass through.
*
* @private
* @param {(Uint8Array|Buffer|string)} chunk - streamed chunk
* @param {string} encoding - Buffer encoding
* @param {Callback} clbk - callback to invoke after transforming the streamed chunk
*/
function transform( chunk, encoding, clbk ) {
debug( 'Received a new chunk. Chunk: %s. Encoding: %s.', chunk.toString(), encoding );
clbk( null, chunk );
}
// EXPORTS //
module.exports = transform;
},{"debug":483}],368:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var logger = require( 'debug' );
var Transform = require( 'readable-stream' ).Transform;
var inherit = require( '@stdlib/utils/inherit' );
var copy = require( '@stdlib/utils/copy' );
var DEFAULTS = require( './defaults.json' );
var validate = require( './validate.js' );
var destroy = require( './destroy.js' );
var _transform = require( './_transform.js' ); // eslint-disable-line no-underscore-dangle
// VARIABLES //
var debug = logger( 'transform-stream:ctor' );
// MAIN //
/**
* Transform stream constructor factory.
*
* @param {Options} [options] - stream options
* @param {Function} [options.transform] - callback to invoke upon receiving a new chunk
* @param {Function} [options.flush] - callback to invoke after receiving all chunks and prior to the stream closing
* @param {boolean} [options.objectMode=false] - specifies whether a stream should operate in object mode
* @param {(string|null)} [options.encoding=null] - specifies how `Buffer` objects should be decoded to `strings`
* @param {NonNegativeNumber} [options.highWaterMark] - specifies the `Buffer` level for when `write()` starts returning `false`
* @param {boolean} [options.allowHalfOpen=false] - specifies whether the stream should remain open even if one side ends
* @param {boolean} [options.decodeStrings=true] - specifies whether to decode `strings` into `Buffer` objects when writing
* @throws {TypeError} options argument must be an object
* @throws {TypeError} must provide valid options
* @returns {Function} Transform stream constructor
*
* @example
* var stdout = require( '@stdlib/streams/node/stdout' );
*
* function transform( chunk, enc, clbk ) {
* clbk( null, chunk.toString()+'\n' );
* }
*
* var opts = {
* 'transform': transform
* };
*
* var TransformStream = ctor( opts );
*
* var stream = new TransformStream();
*
* stream.pipe( stdout );
*
* stream.write( '1' );
* stream.write( '2' );
* stream.write( '3' );
*
* stream.end();
*
* // prints: '1\n2\n3\n'
*/
function ctor( options ) {
var transform;
var copts;
var err;
copts = copy( DEFAULTS );
if ( arguments.length ) {
err = validate( copts, options );
if ( err ) {
throw err;
}
}
if ( copts.transform ) {
transform = copts.transform;
} else {
transform = _transform;
}
/**
* Transform stream constructor.
*
* @private
* @constructor
* @param {Options} [options] - stream options
* @param {boolean} [options.objectMode=false] - specifies whether a stream should operate in object mode
* @param {(string|null)} [options.encoding=null] - specifies how `Buffer` objects should be decoded to `strings`
* @param {NonNegativeNumber} [options.highWaterMark] - specifies the `Buffer` level for when `write()` starts returning `false`
* @param {boolean} [options.allowHalfOpen=false] - specifies whether the stream should remain open even if one side ends
* @param {boolean} [options.decodeStrings=true] - specifies whether to decode `strings` into `Buffer` objects when writing
* @throws {TypeError} options argument must be an object
* @throws {TypeError} must provide valid options
* @returns {TransformStream} transform stream
*
* @example
* var stdout = require( '@stdlib/streams/node/stdout' );
*
* var stream = new TransformStream();
*
* stream.pipe( stdout );
*
* stream.write( '1' );
* stream.write( '2' );
* stream.write( '3' );
*
* stream.end();
*
* // prints: '1\n2\n3\n'
*/
function TransformStream( options ) {
var opts;
var err;
if ( !( this instanceof TransformStream ) ) {
if ( arguments.length ) {
return new TransformStream( options );
}
return new TransformStream();
}
opts = copy( copts );
if ( arguments.length ) {
err = validate( opts, options );
if ( err ) {
throw err;
}
}
debug( 'Creating a transform stream configured with the following options: %s.', JSON.stringify( opts ) );
Transform.call( this, opts );
this._destroyed = false;
return this;
}
/**
* Inherit from the `Transform` prototype.
*/
inherit( TransformStream, Transform );
/**
* Implements the `_transform` method.
*
* @private
* @name _transform
* @memberof TransformStream.prototype
* @type {Function}
* @param {(Buffer|string)} chunk - streamed chunk
* @param {string} encoding - Buffer encoding
* @param {Callback} clbk - callback to invoke after transforming the streamed chunk
*/
TransformStream.prototype._transform = transform; // eslint-disable-line no-underscore-dangle
if ( copts.flush ) {
/**
* Implements the `_flush` method.
*
* @private
* @name _flush
* @memberof TransformStream.prototype
* @type {Function}
* @param {Callback} callback to invoke after performing flush tasks
*/
TransformStream.prototype._flush = copts.flush; // eslint-disable-line no-underscore-dangle
}
/**
* Gracefully destroys a stream, providing backward compatibility.
*
* @private
* @name destroy
* @memberof TransformStream.prototype
* @type {Function}
* @param {Object} [error] - optional error message
* @returns {TransformStream} stream instance
*/
TransformStream.prototype.destroy = destroy;
return TransformStream;
}
// EXPORTS //
module.exports = ctor;
},{"./_transform.js":367,"./defaults.json":369,"./destroy.js":370,"./validate.js":375,"@stdlib/utils/copy":392,"@stdlib/utils/inherit":424,"debug":483,"readable-stream":500}],369:[function(require,module,exports){
module.exports={
"objectMode": false,
"encoding": null,
"allowHalfOpen": false,
"decodeStrings": true
}
},{}],370:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var logger = require( 'debug' );
var nextTick = require( '@stdlib/utils/next-tick' );
// VARIABLES //
var debug = logger( 'transform-stream:destroy' );
// MAIN //
/**
* Gracefully destroys a stream, providing backward compatibility.
*
* @private
* @param {Object} [error] - optional error message
* @returns {Stream} stream instance
*/
function destroy( error ) {
/* eslint-disable no-invalid-this */
var self;
if ( this._destroyed ) {
debug( 'Attempted to destroy an already destroyed stream.' );
return this;
}
self = this;
this._destroyed = true;
nextTick( close );
return this;
/**
* Closes a stream.
*
* @private
*/
function close() {
if ( error ) {
debug( 'Stream was destroyed due to an error. Error: %s.', JSON.stringify( error ) );
self.emit( 'error', error );
}
debug( 'Closing the stream...' );
self.emit( 'close' );
}
}
// EXPORTS //
module.exports = destroy;
},{"@stdlib/utils/next-tick":450,"debug":483}],371:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isObject = require( '@stdlib/assert/is-plain-object' );
var copy = require( '@stdlib/utils/copy' );
var Stream = require( './main.js' );
// MAIN //
/**
* Creates a reusable transform stream factory.
*
* @param {Options} [options] - stream options
* @param {boolean} [options.objectMode=false] - specifies whether a stream should operate in object mode
* @param {(string|null)} [options.encoding=null] - specifies how `Buffer` objects should be decoded to `strings`
* @param {NonNegativeNumber} [options.highWaterMark] - specifies the `Buffer` level for when `write()` starts returning `false`
* @param {boolean} [options.allowHalfOpen=false] - specifies whether the stream should remain open even if one side ends
* @param {boolean} [options.decodeStrings=true] - specifies whether to decode `strings` into `Buffer` objects when writing
* @throws {TypeError} options argument must be an object
* @returns {Function} transform stream factory
*
* @example
* function transform( chunk, enc, clbk ) {
* clbk( null, chunk.toString()+'\n' );
* }
*
* var opts = {
* 'objectMode': true,
* 'encoding': 'utf8',
* 'highWaterMark': 64,
* 'decodeStrings': false
* };
*
* var factory = streamFactory( opts );
*
* // Create 10 identically configured streams...
* var streams = [];
* var i;
* for ( i = 0; i < 10; i++ ) {
* streams.push( factory( transform ) );
* }
*/
function streamFactory( options ) {
var opts;
if ( arguments.length ) {
if ( !isObject( options ) ) {
throw new TypeError( 'invalid argument. Options argument must be an object. Value: `' + options + '`.' );
}
opts = copy( options );
} else {
opts = {};
}
return createStream;
/**
* Creates a transform stream.
*
* @private
* @param {Function} transform - callback to invoke upon receiving a new chunk
* @param {Function} [flush] - callback to invoke after receiving all chunks and prior to the stream closing
* @throws {TypeError} must provide valid options
* @throws {TypeError} transform callback must be a function
* @throws {TypeError} flush callback must be a function
* @returns {TransformStream} transform stream
*/
function createStream( transform, flush ) {
opts.transform = transform;
if ( arguments.length > 1 ) {
opts.flush = flush;
} else {
delete opts.flush; // clear any previous `flush`
}
return new Stream( opts );
}
}
// EXPORTS //
module.exports = streamFactory;
},{"./main.js":373,"@stdlib/assert/is-plain-object":147,"@stdlib/utils/copy":392}],372:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Transform stream.
*
* @module @stdlib/streams/node/transform
*
* @example
* var stdout = require( '@stdlib/streams/node/stdout' );
* var transformStream = require( '@stdlib/streams/node/transform' );
*
* function transform( chunk, enc, clbk ) {
* clbk( null, chunk.toString()+'\n' );
* }
*
* var opts = {
* 'transform': transform
* };
* var stream = transformStream( opts );
*
* stream.pipe( stdout );
*
* stream.write( '1' );
* stream.write( '2' );
* stream.write( '3' );
*
* stream.end();
* // => '1\n2\n3\n'
*
*
* @example
* var transformStream = require( '@stdlib/streams/node/transform' );
*
* function transform( chunk, enc, clbk ) {
* clbk( null, chunk.toString()+'\n' );
* }
*
* var opts = {
* 'objectMode': true,
* 'encoding': 'utf8',
* 'highWaterMark': 64,
* 'decodeStrings': false
* };
*
* var factory = transformStream.factory( opts );
*
* // Create 10 identically configured streams...
* var streams = [];
* var i;
* for ( i = 0; i < 10; i++ ) {
* streams.push( factory( transform ) );
* }
*
*
* @example
* var stdout = require( '@stdlib/streams/node/stdout' );
* var transformStream = require( '@stdlib/streams/node/transform' );
*
* function stringify( chunk, enc, clbk ) {
* clbk( null, JSON.stringify( chunk ) );
* }
*
* function newline( chunk, enc, clbk ) {
* clbk( null, chunk+'\n' );
* }
*
* var s1 = transformStream.objectMode({
* 'transform': stringify
* });
*
* var s2 = transformStream.objectMode({
* 'transform': newline
* });
*
* s1.pipe( s2 ).pipe( stdout );
*
* s1.write( {'value': 'a'} );
* s1.write( {'value': 'b'} );
* s1.write( {'value': 'c'} );
*
* s1.end();
* // => '{"value":"a"}\n{"value":"b"}\n{"value":"c"}\n'
*
*
* @example
* var stdout = require( '@stdlib/streams/node/stdout' );
* var transformStream = require( '@stdlib/streams/node/transform' );
*
* function transform( chunk, enc, clbk ) {
* clbk( null, chunk.toString()+'\n' );
* }
*
* var opts = {
* 'transform': transform
* };
*
* var Stream = transformStream.ctor( opts );
*
* var stream = new Stream();
*
* stream.pipe( stdout );
*
* stream.write( '1' );
* stream.write( '2' );
* stream.write( '3' );
*
* stream.end();
* // => '1\n2\n3\n'
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var transform = require( './main.js' );
var objectMode = require( './object_mode.js' );
var factory = require( './factory.js' );
var ctor = require( './ctor.js' );
// MAIN //
setReadOnly( transform, 'objectMode', objectMode );
setReadOnly( transform, 'factory', factory );
setReadOnly( transform, 'ctor', ctor );
// EXPORTS //
module.exports = transform;
},{"./ctor.js":368,"./factory.js":371,"./main.js":373,"./object_mode.js":374,"@stdlib/utils/define-nonenumerable-read-only-property":396}],373:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var logger = require( 'debug' );
var Transform = require( 'readable-stream' ).Transform;
var inherit = require( '@stdlib/utils/inherit' );
var copy = require( '@stdlib/utils/copy' );
var DEFAULTS = require( './defaults.json' );
var validate = require( './validate.js' );
var destroy = require( './destroy.js' );
var _transform = require( './_transform.js' ); // eslint-disable-line no-underscore-dangle
// VARIABLES //
var debug = logger( 'transform-stream:main' );
// MAIN //
/**
* Transform stream constructor.
*
* @constructor
* @param {Options} [options] - stream options
* @param {Function} [options.transform] - callback to invoke upon receiving a new chunk
* @param {Function} [options.flush] - callback to invoke after receiving all chunks and prior to the stream closing
* @param {boolean} [options.objectMode=false] - specifies whether stream should operate in object mode
* @param {(string|null)} [options.encoding=null] - specifies how `Buffer` objects should be decoded to `strings`
* @param {NonNegativeNumber} [options.highWaterMark] - specifies the `Buffer` level for when `write()` starts returning `false`
* @param {boolean} [options.allowHalfOpen=false] - specifies whether the stream should remain open even if one side ends
* @param {boolean} [options.decodeStrings=true] - specifies whether to decode `strings` into `Buffer` objects when writing
* @throws {TypeError} must provide valid options
* @returns {TransformStream} transform stream
*
* @example
* var stdout = require( '@stdlib/streams/node/stdout' );
*
* function transform( chunk, enc, clbk ) {
* clbk( null, chunk.toString()+'\n' );
* }
*
* var opts = {
* 'transform': transform
* };
* var stream = new TransformStream( opts );
*
* stream.pipe( stdout );
*
* stream.write( '1' );
* stream.write( '2' );
* stream.write( '3' );
*
* stream.end();
*
* // prints: '1\n2\n3\n'
*/
function TransformStream( options ) {
var opts;
var err;
if ( !( this instanceof TransformStream ) ) {
if ( arguments.length ) {
return new TransformStream( options );
}
return new TransformStream();
}
opts = copy( DEFAULTS );
if ( arguments.length ) {
err = validate( opts, options );
if ( err ) {
throw err;
}
}
debug( 'Creating a transform stream configured with the following options: %s.', JSON.stringify( opts ) );
Transform.call( this, opts );
this._destroyed = false;
if ( opts.transform ) {
this._transform = opts.transform;
} else {
this._transform = _transform;
}
if ( opts.flush ) {
this._flush = opts.flush;
}
return this;
}
/*
* Inherit from the `Transform` prototype.
*/
inherit( TransformStream, Transform );
/**
* Gracefully destroys a stream, providing backward compatibility.
*
* @name destroy
* @memberof TransformStream.prototype
* @type {Function}
* @param {Object} [error] - optional error message
* @returns {TransformStream} stream instance
*/
TransformStream.prototype.destroy = destroy;
// EXPORTS //
module.exports = TransformStream;
},{"./_transform.js":367,"./defaults.json":369,"./destroy.js":370,"./validate.js":375,"@stdlib/utils/copy":392,"@stdlib/utils/inherit":424,"debug":483,"readable-stream":500}],374:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isObject = require( '@stdlib/assert/is-plain-object' );
var copy = require( '@stdlib/utils/copy' );
var Stream = require( './main.js' );
// MAIN //
/**
* Returns a transform stream with `objectMode` set to `true`.
*
* @param {Options} [options] - stream options
* @param {Function} [options.transform] - callback to invoke upon receiving a new chunk
* @param {Function} [options.flush] - callback to invoke after receiving all chunks and prior to the stream closing
* @param {(string|null)} [options.encoding=null] - specifies how `Buffer` objects should be decoded to `strings`
* @param {NonNegativeNumber} [options.highWaterMark] - specifies the `Buffer` level for when `write()` starts returning `false`
* @param {boolean} [options.allowHalfOpen=false] - specifies whether the stream should remain open even if one side ends
* @param {boolean} [options.decodeStrings=true] - specifies whether to decode `strings` into `Buffer` objects when writing
* @throws {TypeError} options argument must be an object
* @throws {TypeError} must provide valid options
* @returns {TransformStream} transform stream
*
* @example
* var stdout = require( '@stdlib/streams/node/stdout' );
*
* function stringify( chunk, enc, clbk ) {
* clbk( null, JSON.stringify( chunk ) );
* }
*
* function newline( chunk, enc, clbk ) {
* clbk( null, chunk+'\n' );
* }
*
* var s1 = objectMode({
* 'transform': stringify
* });
*
* var s2 = objectMode({
* 'transform': newline
* });
*
* s1.pipe( s2 ).pipe( stdout );
*
* s1.write( {'value': 'a'} );
* s1.write( {'value': 'b'} );
* s1.write( {'value': 'c'} );
*
* s1.end();
*
* // prints: '{"value":"a"}\n{"value":"b"}\n{"value":"c"}\n'
*/
function objectMode( options ) {
var opts;
if ( arguments.length ) {
if ( !isObject( options ) ) {
throw new TypeError( 'invalid argument. Options argument must be an object. Value: `' + options + '`.' );
}
opts = copy( options );
} else {
opts = {};
}
opts.objectMode = true;
return new Stream( opts );
}
// EXPORTS //
module.exports = objectMode;
},{"./main.js":373,"@stdlib/assert/is-plain-object":147,"@stdlib/utils/copy":392}],375:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isObject = require( '@stdlib/assert/is-plain-object' );
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var isFunction = require( '@stdlib/assert/is-function' );
var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive;
var isNonNegative = require( '@stdlib/assert/is-nonnegative-number' ).isPrimitive;
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
// MAIN //
/**
* Validates function options.
*
* @private
* @param {Object} opts - destination object
* @param {Options} options - function options
* @param {Function} [options.transform] - callback to invoke upon receiving a new chunk
* @param {Function} [options.flush] - callback to invoke after receiving all chunks and prior to the stream closing
* @param {boolean} [options.objectMode] - specifies whether a stream should operate in object mode
* @param {(string|null)} [options.encoding] - specifies how `Buffer` objects should be decoded to `strings`
* @param {NonNegativeNumber} [options.highWaterMark] - specifies the `Buffer` level for when `write()` starts returning `false`
* @param {boolean} [options.allowHalfOpen] - specifies whether the stream should remain open even if one side ends
* @param {boolean} [options.decodeStrings] - specifies whether to decode `strings` into `Buffer` objects when writing
* @returns {(Error|null)} null or an error object
*/
function validate( opts, options ) {
if ( !isObject( options ) ) {
return new TypeError( 'invalid argument. Options must be an object. Value: `' + options + '`.' );
}
if ( hasOwnProp( options, 'transform' ) ) {
opts.transform = options.transform;
if ( !isFunction( opts.transform ) ) {
return new TypeError( 'invalid option. `transform` option must be a function. Option: `' + opts.transform + '`.' );
}
}
if ( hasOwnProp( options, 'flush' ) ) {
opts.flush = options.flush;
if ( !isFunction( opts.flush ) ) {
return new TypeError( 'invalid option. `flush` option must be a function. Option: `' + opts.flush + '`.' );
}
}
if ( hasOwnProp( options, 'objectMode' ) ) {
opts.objectMode = options.objectMode;
if ( !isBoolean( opts.objectMode ) ) {
return new TypeError( 'invalid option. `objectMode` option must be a primitive boolean. Option: `' + opts.objectMode + '`.' );
}
}
if ( hasOwnProp( options, 'encoding' ) ) {
opts.encoding = options.encoding;
if ( !isString( opts.encoding ) ) {
return new TypeError( 'invalid option. `encoding` option must be a primitive string. Option: `' + opts.encoding + '`.' );
}
}
if ( hasOwnProp( options, 'allowHalfOpen' ) ) {
opts.allowHalfOpen = options.allowHalfOpen;
if ( !isBoolean( opts.allowHalfOpen ) ) {
return new TypeError( 'invalid option. `allowHalfOpen` option must be a primitive boolean. Option: `' + opts.allowHalfOpen + '`.' );
}
}
if ( hasOwnProp( options, 'highWaterMark' ) ) {
opts.highWaterMark = options.highWaterMark;
if ( !isNonNegative( opts.highWaterMark ) ) {
return new TypeError( 'invalid option. `highWaterMark` option must be a nonnegative number. Option: `' + opts.highWaterMark + '`.' );
}
}
if ( hasOwnProp( options, 'decodeStrings' ) ) {
opts.decodeStrings = options.decodeStrings;
if ( !isBoolean( opts.decodeStrings ) ) {
return new TypeError( 'invalid option. `decodeStrings` option must be a primitive boolean. Option: `' + opts.decodeStrings + '`.' );
}
}
return null;
}
// EXPORTS //
module.exports = validate;
},{"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-boolean":81,"@stdlib/assert/is-function":102,"@stdlib/assert/is-nonnegative-number":131,"@stdlib/assert/is-plain-object":147,"@stdlib/assert/is-string":158}],376:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Create a string from a sequence of Unicode code points.
*
* @module @stdlib/string/from-code-point
*
* @example
* var fromCodePoint = require( '@stdlib/string/from-code-point' );
*
* var str = fromCodePoint( 9731 );
* // returns '☃'
*/
// MODULES //
var fromCodePoint = require( './main.js' );
// EXPORTS //
module.exports = fromCodePoint;
},{"./main.js":377}],377:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ).isPrimitive;
var isCollection = require( '@stdlib/assert/is-collection' );
var UNICODE_MAX = require( '@stdlib/constants/unicode/max' );
var UNICODE_MAX_BMP = require( '@stdlib/constants/unicode/max-bmp' );
// VARIABLES //
var fromCharCode = String.fromCharCode;
// Factor to rescale a code point from a supplementary plane:
var Ox10000 = 0x10000|0; // 65536
// Factor added to obtain a high surrogate:
var OxD800 = 0xD800|0; // 55296
// Factor added to obtain a low surrogate:
var OxDC00 = 0xDC00|0; // 56320
// 10-bit mask: 2^10-1 = 1023 => 0x3ff => 00000000 00000000 00000011 11111111
var Ox3FF = 1023|0;
// MAIN //
/**
* Creates a string from a sequence of Unicode code points.
*
* ## Notes
*
* - UTF-16 encoding uses one 16-bit unit for non-surrogates (U+0000 to U+D7FF and U+E000 to U+FFFF).
* - UTF-16 encoding uses two 16-bit units (surrogate pairs) for U+10000 to U+10FFFF and encodes U+10000-U+10FFFF by subtracting 0x10000 from the code point, expressing the result as a 20-bit binary, and splitting the 20 bits of 0x0-0xFFFFF as upper and lower 10-bits. The respective 10-bits are stored in two 16-bit words: a high and a low surrogate.
*
*
* @param {...NonNegativeInteger} args - sequence of code points
* @throws {Error} must provide either an array-like object of code points or one or more code points as separate arguments
* @throws {TypeError} a code point must be a nonnegative integer
* @throws {RangeError} must provide a valid Unicode code point
* @returns {string} created string
*
* @example
* var str = fromCodePoint( 9731 );
* // returns '☃'
*/
function fromCodePoint( args ) {
var len;
var str;
var arr;
var low;
var hi;
var pt;
var i;
len = arguments.length;
if ( len === 1 && isCollection( args ) ) {
arr = arguments[ 0 ];
len = arr.length;
} else {
arr = [];
for ( i = 0; i < len; i++ ) {
arr.push( arguments[ i ] );
}
}
if ( len === 0 ) {
throw new Error( 'insufficient input arguments. Must provide either an array of code points or one or more code points as separate arguments.' );
}
str = '';
for ( i = 0; i < len; i++ ) {
pt = arr[ i ];
if ( !isNonNegativeInteger( pt ) ) {
throw new TypeError( 'invalid argument. Must provide valid code points (nonnegative integers). Value: `'+pt+'`.' );
}
if ( pt > UNICODE_MAX ) {
throw new RangeError( 'invalid argument. Must provide a valid code point (cannot exceed max). Value: `'+pt+'`.' );
}
if ( pt <= UNICODE_MAX_BMP ) {
str += fromCharCode( pt );
} else {
// Code point from a supplementary plane. Split into two 16-bit code units (surrogate pair).
pt -= Ox10000;
hi = (pt >> 10) + OxD800;
low = (pt & Ox3FF) + OxDC00;
str += fromCharCode( hi, low );
}
}
return str;
}
// EXPORTS //
module.exports = fromCodePoint;
},{"@stdlib/assert/is-collection":90,"@stdlib/assert/is-nonnegative-integer":127,"@stdlib/constants/unicode/max":258,"@stdlib/constants/unicode/max-bmp":257}],378:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Replace search occurrences with a replacement string.
*
* @module @stdlib/string/replace
*
* @example
* var replace = require( '@stdlib/string/replace' );
*
* var str = 'beep';
* var out = replace( str, 'e', 'o' );
* // returns 'boop'
*
* str = 'Hello World';
* out = replace( str, /world/i, 'Mr. President' );
* // returns 'Hello Mr. President'
*/
// MODULES //
var replace = require( './replace.js' );
// EXPORTS //
module.exports = replace;
},{"./replace.js":379}],379:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var rescape = require( '@stdlib/utils/escape-regexp-string' );
var isFunction = require( '@stdlib/assert/is-function' );
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var isRegExp = require( '@stdlib/assert/is-regexp' );
// MAIN //
/**
* Replace search occurrences with a replacement string.
*
* @param {string} str - input string
* @param {(string|RegExp)} search - search expression
* @param {(string|Function)} newval - replacement value or function
* @throws {TypeError} first argument must be a string primitive
* @throws {TypeError} second argument argument must be a string primitive or regular expression
* @throws {TypeError} third argument must be a string primitive or function
* @returns {string} new string containing replacement(s)
*
* @example
* var str = 'beep';
* var out = replace( str, 'e', 'o' );
* // returns 'boop'
*
* @example
* var str = 'Hello World';
* var out = replace( str, /world/i, 'Mr. President' );
* // returns 'Hello Mr. President'
*
* @example
* var capitalize = require( '@stdlib/string/capitalize' );
*
* var str = 'Oranges and lemons say the bells of St. Clement\'s';
*
* function replacer( match, p1 ) {
* return capitalize( p1 );
* }
*
* var out = replace( str, /([^\s]*)/gi, replacer);
* // returns 'Oranges And Lemons Say The Bells Of St. Clement\'s'
*/
function replace( str, search, newval ) {
if ( !isString( str ) ) {
throw new TypeError( 'invalid argument. First argument must be a string primitive. Value: `' + str + '`.' );
}
if ( isString( search ) ) {
search = rescape( search );
search = new RegExp( search, 'g' );
}
else if ( !isRegExp( search ) ) {
throw new TypeError( 'invalid argument. Second argument must be a string primitive or regular expression. Value: `' + search + '`.' );
}
if ( !isString( newval ) && !isFunction( newval ) ) {
throw new TypeError( 'invalid argument. Third argument must be a string primitive or replacement function. Value: `' + newval + '`.' );
}
return str.replace( search, newval );
}
// EXPORTS //
module.exports = replace;
},{"@stdlib/assert/is-function":102,"@stdlib/assert/is-regexp":154,"@stdlib/assert/is-string":158,"@stdlib/utils/escape-regexp-string":405}],380:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Trim whitespace characters from the beginning and end of a string.
*
* @module @stdlib/string/trim
*
* @example
* var trim = require( '@stdlib/string/trim' );
*
* var out = trim( ' Whitespace ' );
* // returns 'Whitespace'
*
* out = trim( '\t\t\tTabs\t\t\t' );
* // returns 'Tabs'
*
* out = trim( '\n\n\nNew Lines\n\n\n' );
* // returns 'New Lines'
*/
// MODULES //
var trim = require( './trim.js' );
// EXPORTS //
module.exports = trim;
},{"./trim.js":381}],381:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var replace = require( '@stdlib/string/replace' );
// VARIABLES //
// The following regular expression should suffice to polyfill (most?) all environments.
var RE = /^[\u0020\f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]*([\S\s]*?)[\u0020\f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]*$/;
// MAIN //
/**
* Trim whitespace characters from beginning and end of a string.
*
* @param {string} str - input string
* @throws {TypeError} must provide a string primitive
* @returns {string} trimmed string
*
* @example
* var out = trim( ' Whitespace ' );
* // returns 'Whitespace'
*
* @example
* var out = trim( '\t\t\tTabs\t\t\t' );
* // returns 'Tabs'
*
* @example
* var out = trim( '\n\n\nNew Lines\n\n\n' );
* // returns 'New Lines'
*/
function trim( str ) {
if ( !isString( str ) ) {
throw new TypeError( 'invalid argument. Must provide a string primitive. Value: `' + str + '`.' );
}
return replace( str, RE, '$1' );
}
// EXPORTS //
module.exports = trim;
},{"@stdlib/assert/is-string":158,"@stdlib/string/replace":378}],382:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var getGlobal = require( '@stdlib/utils/global' );
var isObject = require( '@stdlib/assert/is-object' );
var modf = require( '@stdlib/math/base/special/modf' );
var round = require( '@stdlib/math/base/special/round' );
var now = require( './now.js' );
// VARIABLES //
var Global = getGlobal();
var ts;
var ns;
if ( isObject( Global.performance ) ) {
ns = Global.performance;
} else {
ns = {};
}
if ( ns.now ) {
ts = ns.now.bind( ns );
} else if ( ns.mozNow ) {
ts = ns.mozNow.bind( ns );
} else if ( ns.msNow ) {
ts = ns.msNow.bind( ns );
} else if ( ns.oNow ) {
ts = ns.oNow.bind( ns );
} else if ( ns.webkitNow ) {
ts = ns.webkitNow.bind( ns );
} else {
ts = now;
}
// MAIN //
/**
* Returns a high-resolution time.
*
* ## Notes
*
* - Output format: `[seconds, nanoseconds]`.
*
*
* @private
* @returns {NumberArray} high-resolution time
*
* @example
* var t = tic();
* // returns [<number>,<number>]
*/
function tic() {
var parts;
var t;
// Get a millisecond timestamp and convert to seconds:
t = ts() / 1000;
// Decompose the timestamp into integer (seconds) and fractional parts:
parts = modf( t );
// Convert the fractional part to nanoseconds:
parts[ 1 ] = round( parts[1] * 1.0e9 );
// Return the high-resolution time:
return parts;
}
// EXPORTS //
module.exports = tic;
},{"./now.js":384,"@stdlib/assert/is-object":145,"@stdlib/math/base/special/modf":283,"@stdlib/math/base/special/round":297,"@stdlib/utils/global":417}],383:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isFunction = require( '@stdlib/assert/is-function' );
// MAIN //
var bool = isFunction( Date.now );
// EXPORTS //
module.exports = bool;
},{"@stdlib/assert/is-function":102}],384:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var bool = require( './detect.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var now;
if ( bool ) {
now = Date.now;
} else {
now = polyfill;
}
// EXPORTS //
module.exports = now;
},{"./detect.js":383,"./polyfill.js":385}],385:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Returns the time in milliseconds since the epoch.
*
* @private
* @returns {number} time
*
* @example
* var ts = now();
* // returns <number>
*/
function now() {
var d = new Date();
return d.getTime();
}
// EXPORTS //
module.exports = now;
},{}],386:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Return a high-resolution time difference.
*
* @module @stdlib/time/toc
*
* @example
* var tic = require( '@stdlib/time/tic' );
* var toc = require( '@stdlib/time/toc' );
*
* var start = tic();
* var delta = toc( start );
* // returns [<number>,<number>]
*/
// MODULES //
var toc = require( './toc.js' );
// EXPORTS //
module.exports = toc;
},{"./toc.js":387}],387:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isNonNegativeIntegerArray = require( '@stdlib/assert/is-nonnegative-integer-array' ).primitives;
var tic = require( '@stdlib/time/tic' );
// MAIN //
/**
* Returns a high-resolution time difference.
*
* ## Notes
*
* - Output format: `[seconds, nanoseconds]`.
*
*
* @param {NonNegativeIntegerArray} time - high-resolution time
* @throws {TypeError} must provide a nonnegative integer array
* @throws {RangeError} input array must have length `2`
* @returns {NumberArray} high resolution time difference
*
* @example
* var tic = require( '@stdlib/time/tic' );
*
* var start = tic();
* var delta = toc( start );
* // returns [<number>,<number>]
*/
function toc( time ) {
var now = tic();
var sec;
var ns;
if ( !isNonNegativeIntegerArray( time ) ) {
throw new TypeError( 'invalid argument. Must provide an array of nonnegative integers. Value: `' + time + '`.' );
}
if ( time.length !== 2 ) {
throw new RangeError( 'invalid argument. Input array must have length `2`.' );
}
sec = now[ 0 ] - time[ 0 ];
ns = now[ 1 ] - time[ 1 ];
if ( sec > 0 && ns < 0 ) {
sec -= 1;
ns += 1e9;
}
else if ( sec < 0 && ns > 0 ) {
sec += 1;
ns -= 1e9;
}
return [ sec, ns ];
}
// EXPORTS //
module.exports = toc;
},{"@stdlib/assert/is-nonnegative-integer-array":126,"@stdlib/time/tic":382}],388:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Determine the name of a value's constructor.
*
* @module @stdlib/utils/constructor-name
*
* @example
* var constructorName = require( '@stdlib/utils/constructor-name' );
*
* var v = constructorName( 'a' );
* // returns 'String'
*
* v = constructorName( {} );
* // returns 'Object'
*
* v = constructorName( true );
* // returns 'Boolean'
*/
// MODULES //
var constructorName = require( './main.js' );
// EXPORTS //
module.exports = constructorName;
},{"./main.js":389}],389:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var nativeClass = require( '@stdlib/utils/native-class' );
var RE = require( '@stdlib/regexp/function-name' ).REGEXP;
var isBuffer = require( '@stdlib/assert/is-buffer' );
// MAIN //
/**
* Determines the name of a value's constructor.
*
* @param {*} v - input value
* @returns {string} name of a value's constructor
*
* @example
* var v = constructorName( 'a' );
* // returns 'String'
*
* @example
* var v = constructorName( 5 );
* // returns 'Number'
*
* @example
* var v = constructorName( null );
* // returns 'Null'
*
* @example
* var v = constructorName( undefined );
* // returns 'Undefined'
*
* @example
* var v = constructorName( function noop() {} );
* // returns 'Function'
*/
function constructorName( v ) {
var match;
var name;
var ctor;
name = nativeClass( v ).slice( 8, -1 );
if ( (name === 'Object' || name === 'Error') && v.constructor ) {
ctor = v.constructor;
if ( typeof ctor.name === 'string' ) {
return ctor.name;
}
match = RE.exec( ctor.toString() );
if ( match ) {
return match[ 1 ];
}
}
if ( isBuffer( v ) ) {
return 'Buffer';
}
return name;
}
// EXPORTS //
module.exports = constructorName;
},{"@stdlib/assert/is-buffer":88,"@stdlib/regexp/function-name":354,"@stdlib/utils/native-class":445}],390:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isArray = require( '@stdlib/assert/is-array' );
var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ).isPrimitive;
var PINF = require( '@stdlib/constants/float64/pinf' );
var deepCopy = require( './deep_copy.js' );
// MAIN //
/**
* Copies or deep clones a value to an arbitrary depth.
*
* @param {*} value - value to copy
* @param {NonNegativeInteger} [level=+infinity] - copy depth
* @throws {TypeError} `level` must be a nonnegative integer
* @returns {*} value copy
*
* @example
* var out = copy( 'beep' );
* // returns 'beep'
*
* @example
* var value = [
* {
* 'a': 1,
* 'b': true,
* 'c': [ 1, 2, 3 ]
* }
* ];
* var out = copy( value );
* // returns [ { 'a': 1, 'b': true, 'c': [ 1, 2, 3 ] } ]
*
* var bool = ( value[0].c === out[0].c );
* // returns false
*/
function copy( value, level ) {
var out;
if ( arguments.length > 1 ) {
if ( !isNonNegativeInteger( level ) ) {
throw new TypeError( 'invalid argument. `level` must be a nonnegative integer. Value: `' + level + '`.' );
}
if ( level === 0 ) {
return value;
}
} else {
level = PINF;
}
out = ( isArray( value ) ) ? new Array( value.length ) : {};
return deepCopy( value, out, [value], [out], level );
}
// EXPORTS //
module.exports = copy;
},{"./deep_copy.js":391,"@stdlib/assert/is-array":79,"@stdlib/assert/is-nonnegative-integer":127,"@stdlib/constants/float64/pinf":246}],391:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var isArray = require( '@stdlib/assert/is-array' );
var isBuffer = require( '@stdlib/assert/is-buffer' );
var isError = require( '@stdlib/assert/is-error' );
var typeOf = require( '@stdlib/utils/type-of' );
var regexp = require( '@stdlib/utils/regexp-from-string' );
var indexOf = require( '@stdlib/utils/index-of' );
var objectKeys = require( '@stdlib/utils/keys' );
var propertyNames = require( '@stdlib/utils/property-names' );
var propertyDescriptor = require( '@stdlib/utils/property-descriptor' );
var getPrototypeOf = require( '@stdlib/utils/get-prototype-of' );
var defineProperty = require( '@stdlib/utils/define-property' );
var copyBuffer = require( '@stdlib/buffer/from-buffer' );
var typedArrays = require( './typed_arrays.js' );
// FUNCTIONS //
/**
* Clones a class instance.
*
* ## Notes
*
* - This should **only** be used for simple cases. Any instances with privileged access to variables (e.g., within closures) cannot be cloned. This approach should be considered **fragile**.
* - The function is greedy, disregarding the notion of a `level`. Instead, the function deep copies all properties, as we assume the concept of `level` applies only to the class instance reference but not to its internal state. This prevents, in theory, two instances from sharing state.
*
*
* @private
* @param {Object} val - class instance
* @returns {Object} new instance
*/
function cloneInstance( val ) {
var cache;
var names;
var name;
var refs;
var desc;
var tmp;
var ref;
var i;
cache = [];
refs = [];
ref = Object.create( getPrototypeOf( val ) );
cache.push( val );
refs.push( ref );
names = propertyNames( val );
for ( i = 0; i < names.length; i++ ) {
name = names[ i ];
desc = propertyDescriptor( val, name );
if ( hasOwnProp( desc, 'value' ) ) {
tmp = ( isArray( val[name] ) ) ? [] : {};
desc.value = deepCopy( val[name], tmp, cache, refs, -1 );
}
defineProperty( ref, name, desc );
}
if ( !Object.isExtensible( val ) ) {
Object.preventExtensions( ref );
}
if ( Object.isSealed( val ) ) {
Object.seal( ref );
}
if ( Object.isFrozen( val ) ) {
Object.freeze( ref );
}
return ref;
}
/**
* Copies an error object.
*
* @private
* @param {(Error|TypeError|SyntaxError|URIError|ReferenceError|RangeError|EvalError)} error - error to copy
* @returns {(Error|TypeError|SyntaxError|URIError|ReferenceError|RangeError|EvalError)} error copy
*
* @example
* var err1 = new TypeError( 'beep' );
*
* var err2 = copyError( err1 );
* // returns <TypeError>
*/
function copyError( error ) {
var cache = [];
var refs = [];
var keys;
var desc;
var tmp;
var key;
var err;
var i;
// Create a new error...
err = new error.constructor( error.message );
cache.push( error );
refs.push( err );
// If a `stack` property is present, copy it over...
if ( error.stack ) {
err.stack = error.stack;
}
// Node.js specific (system errors)...
if ( error.code ) {
err.code = error.code;
}
if ( error.errno ) {
err.errno = error.errno;
}
if ( error.syscall ) {
err.syscall = error.syscall;
}
// Any enumerable properties...
keys = objectKeys( error );
for ( i = 0; i < keys.length; i++ ) {
key = keys[ i ];
desc = propertyDescriptor( error, key );
if ( hasOwnProp( desc, 'value' ) ) {
tmp = ( isArray( error[ key ] ) ) ? [] : {};
desc.value = deepCopy( error[ key ], tmp, cache, refs, -1 );
}
defineProperty( err, key, desc );
}
return err;
}
// MAIN //
/**
* Recursively performs a deep copy of an input object.
*
* @private
* @param {*} val - value to copy
* @param {(Array|Object)} copy - copy
* @param {Array} cache - an array of visited objects
* @param {Array} refs - an array of object references
* @param {NonNegativeInteger} level - copy depth
* @returns {*} deep copy
*/
function deepCopy( val, copy, cache, refs, level ) {
var parent;
var keys;
var name;
var desc;
var ctor;
var key;
var ref;
var x;
var i;
var j;
level -= 1;
// Primitives and functions...
if (
typeof val !== 'object' ||
val === null
) {
return val;
}
if ( isBuffer( val ) ) {
return copyBuffer( val );
}
if ( isError( val ) ) {
return copyError( val );
}
// Objects...
name = typeOf( val );
if ( name === 'date' ) {
return new Date( +val );
}
if ( name === 'regexp' ) {
return regexp( val.toString() );
}
if ( name === 'set' ) {
return new Set( val );
}
if ( name === 'map' ) {
return new Map( val );
}
if (
name === 'string' ||
name === 'boolean' ||
name === 'number'
) {
// If provided an `Object`, return an equivalent primitive!
return val.valueOf();
}
ctor = typedArrays[ name ];
if ( ctor ) {
return ctor( val );
}
// Class instances...
if (
name !== 'array' &&
name !== 'object'
) {
// Cloning requires ES5 or higher...
if ( typeof Object.freeze === 'function' ) {
return cloneInstance( val );
}
return {};
}
// Arrays and plain objects...
keys = objectKeys( val );
if ( level > 0 ) {
parent = name;
for ( j = 0; j < keys.length; j++ ) {
key = keys[ j ];
x = val[ key ];
// Primitive, Buffer, special class instance...
name = typeOf( x );
if (
typeof x !== 'object' ||
x === null ||
(
name !== 'array' &&
name !== 'object'
) ||
isBuffer( x )
) {
if ( parent === 'object' ) {
desc = propertyDescriptor( val, key );
if ( hasOwnProp( desc, 'value' ) ) {
desc.value = deepCopy( x );
}
defineProperty( copy, key, desc );
} else {
copy[ key ] = deepCopy( x );
}
continue;
}
// Circular reference...
i = indexOf( cache, x );
if ( i !== -1 ) {
copy[ key ] = refs[ i ];
continue;
}
// Plain array or object...
ref = ( isArray( x ) ) ? new Array( x.length ) : {};
cache.push( x );
refs.push( ref );
if ( parent === 'array' ) {
copy[ key ] = deepCopy( x, ref, cache, refs, level );
} else {
desc = propertyDescriptor( val, key );
if ( hasOwnProp( desc, 'value' ) ) {
desc.value = deepCopy( x, ref, cache, refs, level );
}
defineProperty( copy, key, desc );
}
}
} else if ( name === 'array' ) {
for ( j = 0; j < keys.length; j++ ) {
key = keys[ j ];
copy[ key ] = val[ key ];
}
} else {
for ( j = 0; j < keys.length; j++ ) {
key = keys[ j ];
desc = propertyDescriptor( val, key );
defineProperty( copy, key, desc );
}
}
if ( !Object.isExtensible( val ) ) {
Object.preventExtensions( copy );
}
if ( Object.isSealed( val ) ) {
Object.seal( copy );
}
if ( Object.isFrozen( val ) ) {
Object.freeze( copy );
}
return copy;
}
// EXPORTS //
module.exports = deepCopy;
},{"./typed_arrays.js":393,"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-array":79,"@stdlib/assert/is-buffer":88,"@stdlib/assert/is-error":96,"@stdlib/buffer/from-buffer":232,"@stdlib/utils/define-property":403,"@stdlib/utils/get-prototype-of":411,"@stdlib/utils/index-of":421,"@stdlib/utils/keys":438,"@stdlib/utils/property-descriptor":460,"@stdlib/utils/property-names":464,"@stdlib/utils/regexp-from-string":467,"@stdlib/utils/type-of":474}],392:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Copy or deep clone a value to an arbitrary depth.
*
* @module @stdlib/utils/copy
*
* @example
* var copy = require( '@stdlib/utils/copy' );
*
* var out = copy( 'beep' );
* // returns 'beep'
*
* @example
* var copy = require( '@stdlib/utils/copy' );
*
* var value = [
* {
* 'a': 1,
* 'b': true,
* 'c': [ 1, 2, 3 ]
* }
* ];
* var out = copy( value );
* // returns [ {'a': 1, 'b': true, 'c': [ 1, 2, 3 ] } ]
*
* var bool = ( value[0].c === out[0].c );
* // returns false
*/
// MODULES //
var copy = require( './copy.js' );
// EXPORTS //
module.exports = copy;
},{"./copy.js":390}],393:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var Int8Array = require( '@stdlib/array/int8' );
var Uint8Array = require( '@stdlib/array/uint8' );
var Uint8ClampedArray = require( '@stdlib/array/uint8c' );
var Int16Array = require( '@stdlib/array/int16' );
var Uint16Array = require( '@stdlib/array/uint16' );
var Int32Array = require( '@stdlib/array/int32' );
var Uint32Array = require( '@stdlib/array/uint32' );
var Float32Array = require( '@stdlib/array/float32' );
var Float64Array = require( '@stdlib/array/float64' );
// VARIABLES //
var hash;
// FUNCTIONS //
/**
* Copies an `Int8Array`.
*
* @private
* @param {Int8Array} arr - array to copy
* @returns {Int8Array} new array
*/
function int8array( arr ) {
return new Int8Array( arr );
}
/**
* Copies a `Uint8Array`.
*
* @private
* @param {Uint8Array} arr - array to copy
* @returns {Uint8Array} new array
*/
function uint8array( arr ) {
return new Uint8Array( arr );
}
/**
* Copies a `Uint8ClampedArray`.
*
* @private
* @param {Uint8ClampedArray} arr - array to copy
* @returns {Uint8ClampedArray} new array
*/
function uint8clampedarray( arr ) {
return new Uint8ClampedArray( arr );
}
/**
* Copies an `Int16Array`.
*
* @private
* @param {Int16Array} arr - array to copy
* @returns {Int16Array} new array
*/
function int16array( arr ) {
return new Int16Array( arr );
}
/**
* Copies a `Uint16Array`.
*
* @private
* @param {Uint16Array} arr - array to copy
* @returns {Uint16Array} new array
*/
function uint16array( arr ) {
return new Uint16Array( arr );
}
/**
* Copies an `Int32Array`.
*
* @private
* @param {Int32Array} arr - array to copy
* @returns {Int32Array} new array
*/
function int32array( arr ) {
return new Int32Array( arr );
}
/**
* Copies a `Uint32Array`.
*
* @private
* @param {Uint32Array} arr - array to copy
* @returns {Uint32Array} new array
*/
function uint32array( arr ) {
return new Uint32Array( arr );
}
/**
* Copies a `Float32Array`.
*
* @private
* @param {Float32Array} arr - array to copy
* @returns {Float32Array} new array
*/
function float32array( arr ) {
return new Float32Array( arr );
}
/**
* Copies a `Float64Array`.
*
* @private
* @param {Float64Array} arr - array to copy
* @returns {Float64Array} new array
*/
function float64array( arr ) {
return new Float64Array( arr );
}
/**
* Returns a hash of functions for copying typed arrays.
*
* @private
* @returns {Object} function hash
*/
function typedarrays() {
var out = {
'int8array': int8array,
'uint8array': uint8array,
'uint8clampedarray': uint8clampedarray,
'int16array': int16array,
'uint16array': uint16array,
'int32array': int32array,
'uint32array': uint32array,
'float32array': float32array,
'float64array': float64array
};
return out;
}
// MAIN //
hash = typedarrays();
// EXPORTS //
module.exports = hash;
},{"@stdlib/array/float32":2,"@stdlib/array/float64":5,"@stdlib/array/int16":7,"@stdlib/array/int32":10,"@stdlib/array/int8":13,"@stdlib/array/uint16":20,"@stdlib/array/uint32":23,"@stdlib/array/uint8":26,"@stdlib/array/uint8c":29}],394:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Define a non-enumerable read-only accessor.
*
* @module @stdlib/utils/define-nonenumerable-read-only-accessor
*
* @example
* var setNonEnumerableReadOnlyAccessor = require( '@stdlib/utils/define-nonenumerable-read-only-accessor' );
*
* function getter() {
* return 'bar';
* }
*
* var obj = {};
*
* setNonEnumerableReadOnlyAccessor( obj, 'foo', getter );
*
* try {
* obj.foo = 'boop';
* } catch ( err ) {
* console.error( err.message );
* }
*/
// MODULES //
var setNonEnumerableReadOnlyAccessor = require( './main.js' ); // eslint-disable-line id-length
// EXPORTS //
module.exports = setNonEnumerableReadOnlyAccessor;
},{"./main.js":395}],395:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var defineProperty = require( '@stdlib/utils/define-property' );
// MAIN //
/**
* Defines a non-enumerable read-only accessor.
*
* @param {Object} obj - object on which to define the property
* @param {(string|symbol)} prop - property name
* @param {Function} getter - accessor
*
* @example
* function getter() {
* return 'bar';
* }
*
* var obj = {};
*
* setNonEnumerableReadOnlyAccessor( obj, 'foo', getter );
*
* try {
* obj.foo = 'boop';
* } catch ( err ) {
* console.error( err.message );
* }
*/
function setNonEnumerableReadOnlyAccessor( obj, prop, getter ) { // eslint-disable-line id-length
defineProperty( obj, prop, {
'configurable': false,
'enumerable': false,
'get': getter
});
}
// EXPORTS //
module.exports = setNonEnumerableReadOnlyAccessor;
},{"@stdlib/utils/define-property":403}],396:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Define a non-enumerable read-only property.
*
* @module @stdlib/utils/define-nonenumerable-read-only-property
*
* @example
* var setNonEnumerableReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
*
* var obj = {};
*
* setNonEnumerableReadOnly( obj, 'foo', 'bar' );
*
* try {
* obj.foo = 'boop';
* } catch ( err ) {
* console.error( err.message );
* }
*/
// MODULES //
var setNonEnumerableReadOnly = require( './main.js' );
// EXPORTS //
module.exports = setNonEnumerableReadOnly;
},{"./main.js":397}],397:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var defineProperty = require( '@stdlib/utils/define-property' );
// MAIN //
/**
* Defines a non-enumerable read-only property.
*
* @param {Object} obj - object on which to define the property
* @param {(string|symbol)} prop - property name
* @param {*} value - value to set
*
* @example
* var obj = {};
*
* setNonEnumerableReadOnly( obj, 'foo', 'bar' );
*
* try {
* obj.foo = 'boop';
* } catch ( err ) {
* console.error( err.message );
* }
*/
function setNonEnumerableReadOnly( obj, prop, value ) {
defineProperty( obj, prop, {
'configurable': false,
'enumerable': false,
'writable': false,
'value': value
});
}
// EXPORTS //
module.exports = setNonEnumerableReadOnly;
},{"@stdlib/utils/define-property":403}],398:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Define a non-enumerable read-write accessor.
*
* @module @stdlib/utils/define-nonenumerable-read-write-accessor
*
* @example
* var setNonEnumerableReadWriteAccessor = require( '@stdlib/utils/define-nonenumerable-read-write-accessor' );
*
* function getter() {
* return name + ' foo';
* }
*
* function setter( v ) {
* name = v;
* }
*
* var name = 'bar';
* var obj = {};
*
* setNonEnumerableReadWriteAccessor( obj, 'foo', getter, setter );
*
* var v = obj.foo;
* // returns 'bar foo'
*
* obj.foo = 'beep';
*
* v = obj.foo;
* // returns 'beep foo'
*/
// MODULES //
var setNonEnumerableReadWriteAccessor = require( './main.js' );
// EXPORTS //
module.exports = setNonEnumerableReadWriteAccessor;
},{"./main.js":399}],399:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var defineProperty = require( '@stdlib/utils/define-property' );
// MAIN //
/**
* Defines a non-enumerable read-write accessor.
*
* @param {Object} obj - object on which to define the property
* @param {(string|symbol)} prop - property name
* @param {Function} getter - get accessor
* @param {Function} setter - set accessor
*
* @example
* function getter() {
* return name + ' foo';
* }
*
* function setter( v ) {
* name = v;
* }
*
* var name = 'bar';
* var obj = {};
*
* setNonEnumerableReadWriteAccessor( obj, 'foo', getter, setter );
*
* var v = obj.foo;
* // returns 'bar foo'
*
* obj.foo = 'beep';
*
* v = obj.foo;
* // returns 'beep foo'
*/
function setNonEnumerableReadWriteAccessor( obj, prop, getter, setter ) { // eslint-disable-line id-length
defineProperty( obj, prop, {
'configurable': false,
'enumerable': false,
'get': getter,
'set': setter
});
}
// EXPORTS //
module.exports = setNonEnumerableReadWriteAccessor;
},{"@stdlib/utils/define-property":403}],400:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Defines (or modifies) an object property.
*
* ## Notes
*
* - Property descriptors come in two flavors: **data descriptors** and **accessor descriptors**. A data descriptor is a property that has a value, which may or may not be writable. An accessor descriptor is a property described by a getter-setter function pair. A descriptor must be one of these two flavors and cannot be both.
*
* @name defineProperty
* @type {Function}
* @param {Object} obj - object on which to define the property
* @param {(string|symbol)} prop - property name
* @param {Object} descriptor - property descriptor
* @param {boolean} [descriptor.configurable=false] - boolean indicating if property descriptor can be changed and if the property can be deleted from the provided object
* @param {boolean} [descriptor.enumerable=false] - boolean indicating if the property shows up when enumerating object properties
* @param {boolean} [descriptor.writable=false] - boolean indicating if the value associated with the property can be changed with an assignment operator
* @param {*} [descriptor.value] - property value
* @param {(Function|void)} [descriptor.get=undefined] - function which serves as a getter for the property, or, if no getter, undefined. When the property is accessed, a getter function is called without arguments and with the `this` context set to the object through which the property is accessed (which may not be the object on which the property is defined due to inheritance). The return value will be used as the property value.
* @param {(Function|void)} [descriptor.set=undefined] - function which serves as a setter for the property, or, if no setter, undefined. When assigning a property value, a setter function is called with one argument (the value being assigned to the property) and with the `this` context set to the object through which the property is assigned.
* @throws {TypeError} first argument must be an object
* @throws {TypeError} third argument must be an object
* @throws {Error} property descriptor cannot have both a value and a setter and/or getter
* @returns {Object} object with added property
*
* @example
* var obj = {};
*
* defineProperty( obj, 'foo', {
* 'value': 'bar'
* });
*
* var str = obj.foo;
* // returns 'bar'
*/
var defineProperty = Object.defineProperty;
// EXPORTS //
module.exports = defineProperty;
},{}],401:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var main = ( typeof Object.defineProperty === 'function' ) ? Object.defineProperty : null;
// EXPORTS //
module.exports = main;
},{}],402:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var defineProperty = require( './define_property.js' );
// MAIN //
/**
* Tests for `Object.defineProperty` support.
*
* @private
* @returns {boolean} boolean indicating if an environment has `Object.defineProperty` support
*
* @example
* var bool = hasDefinePropertySupport();
* // returns <boolean>
*/
function hasDefinePropertySupport() {
// Test basic support...
try {
defineProperty( {}, 'x', {} );
return true;
} catch ( err ) { // eslint-disable-line no-unused-vars
return false;
}
}
// EXPORTS //
module.exports = hasDefinePropertySupport;
},{"./define_property.js":401}],403:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Define (or modify) an object property.
*
* @module @stdlib/utils/define-property
*
* @example
* var defineProperty = require( '@stdlib/utils/define-property' );
*
* var obj = {};
* defineProperty( obj, 'foo', {
* 'value': 'bar',
* 'writable': false,
* 'configurable': false,
* 'enumerable': false
* });
* obj.foo = 'boop'; // => throws
*/
// MODULES //
var hasDefinePropertySupport = require( './has_define_property_support.js' );
var builtin = require( './builtin.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var defineProperty;
if ( hasDefinePropertySupport() ) {
defineProperty = builtin;
} else {
defineProperty = polyfill;
}
// EXPORTS //
module.exports = defineProperty;
},{"./builtin.js":400,"./has_define_property_support.js":402,"./polyfill.js":404}],404:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
/* eslint-disable no-underscore-dangle, no-proto */
'use strict';
// VARIABLES //
var objectProtoype = Object.prototype;
var toStr = objectProtoype.toString;
var defineGetter = objectProtoype.__defineGetter__;
var defineSetter = objectProtoype.__defineSetter__;
var lookupGetter = objectProtoype.__lookupGetter__;
var lookupSetter = objectProtoype.__lookupSetter__;
// MAIN //
/**
* Defines (or modifies) an object property.
*
* ## Notes
*
* - Property descriptors come in two flavors: **data descriptors** and **accessor descriptors**. A data descriptor is a property that has a value, which may or may not be writable. An accessor descriptor is a property described by a getter-setter function pair. A descriptor must be one of these two flavors and cannot be both.
*
* @param {Object} obj - object on which to define the property
* @param {string} prop - property name
* @param {Object} descriptor - property descriptor
* @param {boolean} [descriptor.configurable=false] - boolean indicating if property descriptor can be changed and if the property can be deleted from the provided object
* @param {boolean} [descriptor.enumerable=false] - boolean indicating if the property shows up when enumerating object properties
* @param {boolean} [descriptor.writable=false] - boolean indicating if the value associated with the property can be changed with an assignment operator
* @param {*} [descriptor.value] - property value
* @param {(Function|void)} [descriptor.get=undefined] - function which serves as a getter for the property, or, if no getter, undefined. When the property is accessed, a getter function is called without arguments and with the `this` context set to the object through which the property is accessed (which may not be the object on which the property is defined due to inheritance). The return value will be used as the property value.
* @param {(Function|void)} [descriptor.set=undefined] - function which serves as a setter for the property, or, if no setter, undefined. When assigning a property value, a setter function is called with one argument (the value being assigned to the property) and with the `this` context set to the object through which the property is assigned.
* @throws {TypeError} first argument must be an object
* @throws {TypeError} third argument must be an object
* @throws {Error} property descriptor cannot have both a value and a setter and/or getter
* @returns {Object} object with added property
*
* @example
* var obj = {};
*
* defineProperty( obj, 'foo', {
* 'value': 'bar'
* });
*
* var str = obj.foo;
* // returns 'bar'
*/
function defineProperty( obj, prop, descriptor ) {
var prototype;
var hasValue;
var hasGet;
var hasSet;
if ( typeof obj !== 'object' || obj === null || toStr.call( obj ) === '[object Array]' ) {
throw new TypeError( 'invalid argument. First argument must be an object. Value: `' + obj + '`.' );
}
if ( typeof descriptor !== 'object' || descriptor === null || toStr.call( descriptor ) === '[object Array]' ) {
throw new TypeError( 'invalid argument. Property descriptor must be an object. Value: `' + descriptor + '`.' );
}
hasValue = ( 'value' in descriptor );
if ( hasValue ) {
if (
lookupGetter.call( obj, prop ) ||
lookupSetter.call( obj, prop )
) {
// Override `__proto__` to avoid touching inherited accessors:
prototype = obj.__proto__;
obj.__proto__ = objectProtoype;
// Delete property as existing getters/setters prevent assigning value to specified property:
delete obj[ prop ];
obj[ prop ] = descriptor.value;
// Restore original prototype:
obj.__proto__ = prototype;
} else {
obj[ prop ] = descriptor.value;
}
}
hasGet = ( 'get' in descriptor );
hasSet = ( 'set' in descriptor );
if ( hasValue && ( hasGet || hasSet ) ) {
throw new Error( 'invalid argument. Cannot specify one or more accessors and a value or writable attribute in the property descriptor.' );
}
if ( hasGet && defineGetter ) {
defineGetter.call( obj, prop, descriptor.get );
}
if ( hasSet && defineSetter ) {
defineSetter.call( obj, prop, descriptor.set );
}
return obj;
}
// EXPORTS //
module.exports = defineProperty;
},{}],405:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Escape a regular expression string or pattern.
*
* @module @stdlib/utils/escape-regexp-string
*
* @example
* var rescape = require( '@stdlib/utils/escape-regexp-string' );
*
* var str = rescape( '[A-Z]*' );
* // returns '\\[A\\-Z\\]\\*'
*/
// MODULES //
var rescape = require( './main.js' );
// EXPORTS //
module.exports = rescape;
},{"./main.js":406}],406:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
// VARIABLES //
var RE_CHARS = /[-\/\\^$*+?.()|[\]{}]/g; // eslint-disable-line no-useless-escape
// MAIN //
/**
* Escapes a regular expression string.
*
* @param {string} str - regular expression string
* @throws {TypeError} first argument must be a string primitive
* @returns {string} escaped string
*
* @example
* var str = rescape( '[A-Z]*' );
* // returns '\\[A\\-Z\\]\\*'
*/
function rescape( str ) {
var len;
var s;
var i;
if ( !isString( str ) ) {
throw new TypeError( 'invalid argument. Must provide a regular expression string. Value: `' + str + '`.' );
}
// Check if the string starts with a forward slash...
if ( str[ 0 ] === '/' ) {
// Find the last forward slash...
len = str.length;
for ( i = len-1; i >= 0; i-- ) {
if ( str[ i ] === '/' ) {
break;
}
}
}
// If we searched the string to no avail or if the first letter is not `/`, assume that the string is not of the form `/[...]/[guimy]`:
if ( i === void 0 || i <= 0 ) {
return str.replace( RE_CHARS, '\\$&' );
}
// We need to de-construct the string...
s = str.substring( 1, i );
// Only escape the characters between the `/`:
s = s.replace( RE_CHARS, '\\$&' );
// Reassemble:
str = str[ 0 ] + s + str.substring( i );
return str;
}
// EXPORTS //
module.exports = rescape;
},{"@stdlib/assert/is-string":158}],407:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isFunction = require( '@stdlib/assert/is-function' );
var hasFunctionNameSupport = require( '@stdlib/assert/has-function-name-support' );
var RE = require( '@stdlib/regexp/function-name' ).REGEXP;
// VARIABLES //
var isFunctionNameSupported = hasFunctionNameSupport();
// MAIN //
/**
* Returns the name of a function.
*
* @param {Function} fcn - input function
* @throws {TypeError} must provide a function
* @returns {string} function name
*
* @example
* var v = functionName( Math.sqrt );
* // returns 'sqrt'
*
* @example
* var v = functionName( function foo(){} );
* // returns 'foo'
*
* @example
* var v = functionName( function(){} );
* // returns '' || 'anonymous'
*
* @example
* var v = functionName( String );
* // returns 'String'
*/
function functionName( fcn ) {
// TODO: add support for generator functions?
if ( isFunction( fcn ) === false ) {
throw new TypeError( 'invalid argument. Must provide a function. Value: `' + fcn + '`.' );
}
if ( isFunctionNameSupported ) {
return fcn.name;
}
return RE.exec( fcn.toString() )[ 1 ];
}
// EXPORTS //
module.exports = functionName;
},{"@stdlib/assert/has-function-name-support":39,"@stdlib/assert/is-function":102,"@stdlib/regexp/function-name":354}],408:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Return the name of a function.
*
* @module @stdlib/utils/function-name
*
* @example
* var functionName = require( '@stdlib/utils/function-name' );
*
* var v = functionName( String );
* // returns 'String'
*
* v = functionName( function foo(){} );
* // returns 'foo'
*
* v = functionName( function(){} );
* // returns '' || 'anonymous'
*/
// MODULES //
var functionName = require( './function_name.js' );
// EXPORTS //
module.exports = functionName;
},{"./function_name.js":407}],409:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isFunction = require( '@stdlib/assert/is-function' );
var builtin = require( './native.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var getProto;
if ( isFunction( Object.getPrototypeOf ) ) {
getProto = builtin;
} else {
getProto = polyfill;
}
// EXPORTS //
module.exports = getProto;
},{"./native.js":412,"./polyfill.js":413,"@stdlib/assert/is-function":102}],410:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var getProto = require( './detect.js' );
// MAIN //
/**
* Returns the prototype of a provided object.
*
* @param {*} value - input value
* @returns {(Object|null)} prototype
*
* @example
* var proto = getPrototypeOf( {} );
* // returns {}
*/
function getPrototypeOf( value ) {
if (
value === null ||
value === void 0
) {
return null;
}
// In order to ensure consistent ES5/ES6 behavior, cast input value to an object (strings, numbers, booleans); ES5 `Object.getPrototypeOf` throws when provided primitives and ES6 `Object.getPrototypeOf` casts:
value = Object( value );
return getProto( value );
}
// EXPORTS //
module.exports = getPrototypeOf;
},{"./detect.js":409}],411:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Return the prototype of a provided object.
*
* @module @stdlib/utils/get-prototype-of
*
* @example
* var getPrototype = require( '@stdlib/utils/get-prototype-of' );
*
* var proto = getPrototype( {} );
* // returns {}
*/
// MODULES //
var getPrototype = require( './get_prototype_of.js' );
// EXPORTS //
module.exports = getPrototype;
},{"./get_prototype_of.js":410}],412:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var getProto = Object.getPrototypeOf;
// EXPORTS //
module.exports = getProto;
},{}],413:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var nativeClass = require( '@stdlib/utils/native-class' );
var getProto = require( './proto.js' );
// MAIN //
/**
* Returns the prototype of a provided object.
*
* @private
* @param {Object} obj - input object
* @returns {(Object|null)} prototype
*/
function getPrototypeOf( obj ) {
var proto = getProto( obj );
if ( proto || proto === null ) {
return proto;
}
if ( nativeClass( obj.constructor ) === '[object Function]' ) {
// May break if the constructor has been tampered with...
return obj.constructor.prototype;
}
if ( obj instanceof Object ) {
return Object.prototype;
}
// Return `null` for objects created via `Object.create( null )`. Also return `null` for cross-realm objects on browsers that lack `__proto__` support, such as IE < 11.
return null;
}
// EXPORTS //
module.exports = getPrototypeOf;
},{"./proto.js":414,"@stdlib/utils/native-class":445}],414:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Returns the value of the `__proto__` property.
*
* @private
* @param {Object} obj - input object
* @returns {*} value of `__proto__` property
*/
function getProto( obj ) {
// eslint-disable-next-line no-proto
return obj.__proto__;
}
// EXPORTS //
module.exports = getProto;
},{}],415:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Returns the global object using code generation.
*
* @private
* @returns {Object} global object
*/
function getGlobal() {
return new Function( 'return this;' )(); // eslint-disable-line no-new-func
}
// EXPORTS //
module.exports = getGlobal;
},{}],416:[function(require,module,exports){
(function (global){(function (){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var obj = ( typeof global === 'object' ) ? global : null;
// EXPORTS //
module.exports = obj;
}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],417:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Return the global object.
*
* @module @stdlib/utils/global
*
* @example
* var getGlobal = require( '@stdlib/utils/global' );
*
* var g = getGlobal();
* // returns {...}
*/
// MODULES //
var getGlobal = require( './main.js' );
// EXPORTS //
module.exports = getGlobal;
},{"./main.js":418}],418:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive;
var getThis = require( './codegen.js' );
var Self = require( './self.js' );
var Win = require( './window.js' );
var Global = require( './global.js' );
// MAIN //
/**
* Returns the global object.
*
* ## Notes
*
* - Using code generation is the **most** reliable way to resolve the global object; however, doing so is likely to violate content security policies (CSPs) in, e.g., Chrome Apps and elsewhere.
*
* @param {boolean} [codegen=false] - boolean indicating whether to use code generation to resolve the global object
* @throws {TypeError} must provide a boolean
* @throws {Error} unable to resolve global object
* @returns {Object} global object
*
* @example
* var g = getGlobal();
* // returns {...}
*/
function getGlobal( codegen ) {
if ( arguments.length ) {
if ( !isBoolean( codegen ) ) {
throw new TypeError( 'invalid argument. Must provide a boolean primitive. Value: `'+codegen+'`.' );
}
if ( codegen ) {
return getThis();
}
// Fall through...
}
// Case: browsers and web workers
if ( Self ) {
return Self;
}
// Case: browsers
if ( Win ) {
return Win;
}
// Case: Node.js
if ( Global ) {
return Global;
}
// Case: unknown
throw new Error( 'unexpected error. Unable to resolve global object.' );
}
// EXPORTS //
module.exports = getGlobal;
},{"./codegen.js":415,"./global.js":416,"./self.js":419,"./window.js":420,"@stdlib/assert/is-boolean":81}],419:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var obj = ( typeof self === 'object' ) ? self : null;
// EXPORTS //
module.exports = obj;
},{}],420:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var obj = ( typeof window === 'object' ) ? window : null;
// EXPORTS //
module.exports = obj;
},{}],421:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Return the first index at which a given element can be found.
*
* @module @stdlib/utils/index-of
*
* @example
* var indexOf = require( '@stdlib/utils/index-of' );
*
* var arr = [ 4, 3, 2, 1 ];
* var idx = indexOf( arr, 3 );
* // returns 1
*
* arr = [ 4, 3, 2, 1 ];
* idx = indexOf( arr, 5 );
* // returns -1
*
* // Using a `fromIndex`:
* arr = [ 1, 2, 3, 4, 5, 2, 6 ];
* idx = indexOf( arr, 2, 3 );
* // returns 5
*
* // `fromIndex` which exceeds `array` length:
* arr = [ 1, 2, 3, 4, 2, 5 ];
* idx = indexOf( arr, 2, 10 );
* // returns -1
*
* // Negative `fromIndex`:
* arr = [ 1, 2, 3, 4, 5, 2, 6, 2 ];
* idx = indexOf( arr, 2, -4 );
* // returns 5
*
* idx = indexOf( arr, 2, -1 );
* // returns 7
*
* // Negative `fromIndex` exceeding input `array` length:
* arr = [ 1, 2, 3, 4, 5, 2, 6 ];
* idx = indexOf( arr, 2, -10 );
* // returns 1
*
* // Array-like objects:
* var str = 'bebop';
* idx = indexOf( str, 'o' );
* // returns 3
*/
// MODULES //
var indexOf = require( './index_of.js' );
// EXPORTS //
module.exports = indexOf;
},{"./index_of.js":422}],422:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isnan = require( '@stdlib/assert/is-nan' );
var isCollection = require( '@stdlib/assert/is-collection' );
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var isInteger = require( '@stdlib/assert/is-integer' ).isPrimitive;
// MAIN //
/**
* Returns the first index at which a given element can be found.
*
* @param {ArrayLike} arr - array-like object
* @param {*} searchElement - element to find
* @param {integer} [fromIndex] - starting index (if negative, the start index is determined relative to last element)
* @throws {TypeError} must provide an array-like object
* @throws {TypeError} `fromIndex` must be an integer
* @returns {integer} index or -1
*
* @example
* var arr = [ 4, 3, 2, 1 ];
* var idx = indexOf( arr, 3 );
* // returns 1
*
* @example
* var arr = [ 4, 3, 2, 1 ];
* var idx = indexOf( arr, 5 );
* // returns -1
*
* @example
* // Using a `fromIndex`:
* var arr = [ 1, 2, 3, 4, 5, 2, 6 ];
* var idx = indexOf( arr, 2, 3 );
* // returns 5
*
* @example
* // `fromIndex` which exceeds `array` length:
* var arr = [ 1, 2, 3, 4, 2, 5 ];
* var idx = indexOf( arr, 2, 10 );
* // returns -1
*
* @example
* // Negative `fromIndex`:
* var arr = [ 1, 2, 3, 4, 5, 2, 6, 2 ];
* var idx = indexOf( arr, 2, -4 );
* // returns 5
*
* idx = indexOf( arr, 2, -1 );
* // returns 7
*
* @example
* // Negative `fromIndex` exceeding input `array` length:
* var arr = [ 1, 2, 3, 4, 5, 2, 6 ];
* var idx = indexOf( arr, 2, -10 );
* // returns 1
*
* @example
* // Array-like objects:
* var str = 'bebop';
* var idx = indexOf( str, 'o' );
* // returns 3
*/
function indexOf( arr, searchElement, fromIndex ) {
var len;
var i;
if ( !isCollection( arr ) && !isString( arr ) ) {
throw new TypeError( 'invalid argument. First argument must be an array-like object. Value: `' + arr + '`.' );
}
len = arr.length;
if ( len === 0 ) {
return -1;
}
if ( arguments.length === 3 ) {
if ( !isInteger( fromIndex ) ) {
throw new TypeError( 'invalid argument. `fromIndex` must be an integer. Value: `' + fromIndex + '`.' );
}
if ( fromIndex >= 0 ) {
if ( fromIndex >= len ) {
return -1;
}
i = fromIndex;
} else {
i = len + fromIndex;
if ( i < 0 ) {
i = 0;
}
}
} else {
i = 0;
}
// Check for `NaN`...
if ( isnan( searchElement ) ) {
for ( ; i < len; i++ ) {
if ( isnan( arr[i] ) ) {
return i;
}
}
} else {
for ( ; i < len; i++ ) {
if ( arr[ i ] === searchElement ) {
return i;
}
}
}
return -1;
}
// EXPORTS //
module.exports = indexOf;
},{"@stdlib/assert/is-collection":90,"@stdlib/assert/is-integer":110,"@stdlib/assert/is-nan":118,"@stdlib/assert/is-string":158}],423:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var builtin = require( './native.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var createObject;
if ( typeof builtin === 'function' ) {
createObject = builtin;
} else {
createObject = polyfill;
}
// EXPORTS //
module.exports = createObject;
},{"./native.js":426,"./polyfill.js":427}],424:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Implement prototypical inheritance by replacing the prototype of one constructor with the prototype of another constructor.
*
* @module @stdlib/utils/inherit
*
* @example
* var inherit = require( '@stdlib/utils/inherit' );
*
* function Foo() {
* return this;
* }
* Foo.prototype.beep = function beep() {
* return 'boop';
* };
*
* function Bar() {
* Foo.call( this );
* return this;
* }
* inherit( Bar, Foo );
*
* var bar = new Bar();
* var v = bar.beep();
* // returns 'boop'
*/
// MODULES //
var inherit = require( './inherit.js' );
// EXPORTS //
module.exports = inherit;
},{"./inherit.js":425}],425:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var defineProperty = require( '@stdlib/utils/define-property' );
var validate = require( './validate.js' );
var createObject = require( './detect.js' );
// MAIN //
/**
* Implements prototypical inheritance by replacing the prototype of one constructor with the prototype of another constructor.
*
* ## Notes
*
* - This implementation is not designed to work with ES2015/ES6 classes. For ES2015/ES6 classes, use `class` with `extends`.
* - For reference, see [node#3455](https://github.com/nodejs/node/pull/3455), [node#4179](https://github.com/nodejs/node/issues/4179), [node#3452](https://github.com/nodejs/node/issues/3452), and [node commit](https://github.com/nodejs/node/commit/29da8cf8d7ab8f66b9091ab22664067d4468461e#diff-3deb3f32958bb937ae05c6f3e4abbdf5).
*
*
* @param {(Object|Function)} ctor - constructor which will inherit
* @param {(Object|Function)} superCtor - super (parent) constructor
* @throws {TypeError} first argument must be either an object or a function which can inherit
* @throws {TypeError} second argument must be either an object or a function from which a constructor can inherit
* @throws {TypeError} second argument must have an inheritable prototype
* @returns {(Object|Function)} child constructor
*
* @example
* function Foo() {
* return this;
* }
* Foo.prototype.beep = function beep() {
* return 'boop';
* };
*
* function Bar() {
* Foo.call( this );
* return this;
* }
* inherit( Bar, Foo );
*
* var bar = new Bar();
* var v = bar.beep();
* // returns 'boop'
*/
function inherit( ctor, superCtor ) {
var err = validate( ctor );
if ( err ) {
throw err;
}
err = validate( superCtor );
if ( err ) {
throw err;
}
if ( typeof superCtor.prototype === 'undefined' ) {
throw new TypeError( 'invalid argument. Second argument must have a prototype from which another object can inherit. Value: `'+superCtor.prototype+'`.' );
}
// Create a prototype which inherits from the parent prototype:
ctor.prototype = createObject( superCtor.prototype );
// Set the constructor to refer to the child constructor:
defineProperty( ctor.prototype, 'constructor', {
'configurable': true,
'enumerable': false,
'writable': true,
'value': ctor
});
return ctor;
}
// EXPORTS //
module.exports = inherit;
},{"./detect.js":423,"./validate.js":428,"@stdlib/utils/define-property":403}],426:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// EXPORTS //
module.exports = Object.create;
},{}],427:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// FUNCTIONS //
/**
* Dummy constructor.
*
* @private
*/
function Ctor() {
// Empty...
}
// MAIN //
/**
* An `Object.create` shim for older JavaScript engines.
*
* @private
* @param {Object} proto - prototype
* @returns {Object} created object
*
* @example
* var obj = createObject( Object.prototype );
* // returns {}
*/
function createObject( proto ) {
Ctor.prototype = proto;
return new Ctor();
}
// EXPORTS //
module.exports = createObject;
},{}],428:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Tests that a value is a valid constructor.
*
* @private
* @param {*} value - value to test
* @returns {(Error|null)} error object or null
*
* @example
* var ctor = function ctor() {};
*
* var err = validate( ctor );
* // returns null
*
* err = validate( null );
* // returns <TypeError>
*/
function validate( value ) {
var type = typeof value;
if (
value === null ||
(type !== 'object' && type !== 'function')
) {
return new TypeError( 'invalid argument. A provided constructor must be either an object (except null) or a function. Value: `'+value+'`.' );
}
return null;
}
// EXPORTS //
module.exports = validate;
},{}],429:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Returns an array of an object's own enumerable property names.
*
* ## Notes
*
* - In contrast to the built-in `Object.keys()`, this function returns an empty array if provided `undefined` or `null`, rather than throwing an error.
*
* @private
* @param {*} value - input object
* @returns {Array} a list of own enumerable property names
*
* @example
* var obj = {
* 'beep': 'boop',
* 'foo': 3.14
* };
*
* var k = keys( obj );
* // e.g., returns [ 'beep', 'foo' ]
*/
function keys( value ) {
return Object.keys( Object( value ) );
}
// EXPORTS //
module.exports = keys;
},{}],430:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isArguments = require( '@stdlib/assert/is-arguments' );
var builtin = require( './builtin.js' );
// VARIABLES //
var slice = Array.prototype.slice;
// MAIN //
/**
* Returns an array of an object's own enumerable property names.
*
* @private
* @param {*} value - input object
* @returns {Array} a list of own enumerable property names
*
* @example
* var obj = {
* 'beep': 'boop',
* 'foo': 3.14
* };
*
* var k = keys( obj );
* // e.g., returns [ 'beep', 'foo' ]
*/
function keys( value ) {
if ( isArguments( value ) ) {
return builtin( slice.call( value ) );
}
return builtin( value );
}
// EXPORTS //
module.exports = keys;
},{"./builtin.js":429,"@stdlib/assert/is-arguments":74}],431:[function(require,module,exports){
module.exports=[
"console",
"external",
"frame",
"frameElement",
"frames",
"innerHeight",
"innerWidth",
"outerHeight",
"outerWidth",
"pageXOffset",
"pageYOffset",
"parent",
"scrollLeft",
"scrollTop",
"scrollX",
"scrollY",
"self",
"webkitIndexedDB",
"webkitStorageInfo",
"window"
]
},{}],432:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var keys = require( './builtin.js' );
// FUNCTIONS //
/**
* Tests the built-in `Object.keys()` implementation when provided `arguments`.
*
* @private
* @returns {boolean} boolean indicating whether the built-in implementation returns the expected number of keys
*/
function test() {
return ( keys( arguments ) || '' ).length !== 2;
}
// MAIN //
/**
* Tests whether the built-in `Object.keys()` implementation supports providing `arguments` as an input value.
*
* ## Notes
*
* - Safari 5.0 does **not** support `arguments` as an input value.
*
* @private
* @returns {boolean} boolean indicating whether a built-in implementation supports `arguments`
*/
function check() {
return test( 1, 2 );
}
// EXPORTS //
module.exports = check;
},{"./builtin.js":429}],433:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var indexOf = require( '@stdlib/utils/index-of' );
var typeOf = require( '@stdlib/utils/type-of' );
var isConstructorPrototype = require( './is_constructor_prototype.js' );
var EXCLUDED_KEYS = require( './excluded_keys.json' );
var win = require( './window.js' );
// VARIABLES //
var bool;
// FUNCTIONS //
/**
* Determines whether an environment throws when comparing to the prototype of a value's constructor (e.g., [IE9][1]).
*
* [1]: https://stackoverflow.com/questions/7688070/why-is-comparing-the-constructor-property-of-two-windows-unreliable
*
* @private
* @returns {boolean} boolean indicating whether an environment is buggy
*/
function check() {
var k;
if ( typeOf( win ) === 'undefined' ) {
return false;
}
for ( k in win ) { // eslint-disable-line guard-for-in
try {
if (
indexOf( EXCLUDED_KEYS, k ) === -1 &&
hasOwnProp( win, k ) &&
win[ k ] !== null &&
typeOf( win[ k ] ) === 'object'
) {
isConstructorPrototype( win[ k ] );
}
} catch ( err ) { // eslint-disable-line no-unused-vars
return true;
}
}
return false;
}
// MAIN //
bool = check();
// EXPORTS //
module.exports = bool;
},{"./excluded_keys.json":431,"./is_constructor_prototype.js":439,"./window.js":444,"@stdlib/assert/has-own-property":53,"@stdlib/utils/index-of":421,"@stdlib/utils/type-of":474}],434:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var bool = ( typeof Object.keys !== 'undefined' );
// EXPORTS //
module.exports = bool;
},{}],435:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isEnumerableProperty = require( '@stdlib/assert/is-enumerable-property' );
var noop = require( '@stdlib/utils/noop' );
// MAIN //
// Note: certain environments treat an object's prototype as enumerable, which, as a matter of convention, it shouldn't be...
var bool = isEnumerableProperty( noop, 'prototype' );
// EXPORTS //
module.exports = bool;
},{"@stdlib/assert/is-enumerable-property":93,"@stdlib/utils/noop":452}],436:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isEnumerableProperty = require( '@stdlib/assert/is-enumerable-property' );
// VARIABLES //
var obj = {
'toString': null
};
// MAIN //
// Note: certain environments don't allow enumeration of overwritten properties which are considered non-enumerable...
var bool = !isEnumerableProperty( obj, 'toString' );
// EXPORTS //
module.exports = bool;
},{"@stdlib/assert/is-enumerable-property":93}],437:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var bool = ( typeof window !== 'undefined' );
// EXPORTS //
module.exports = bool;
},{}],438:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Return an array of an object's own enumerable property names.
*
* @module @stdlib/utils/keys
*
* @example
* var keys = require( '@stdlib/utils/keys' );
*
* var obj = {
* 'beep': 'boop',
* 'foo': 3.14
* };
*
* var k = keys( obj );
* // e.g., returns [ 'beep', 'foo' ]
*/
// MODULES //
var keys = require( './main.js' );
// EXPORTS //
module.exports = keys;
},{"./main.js":441}],439:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Tests whether a value equals the prototype of its constructor.
*
* @private
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether a value equals the prototype of its constructor
*/
function isConstructorPrototype( value ) {
return ( value.constructor && value.constructor.prototype === value );
}
// EXPORTS //
module.exports = isConstructorPrototype;
},{}],440:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var hasAutomationEqualityBug = require( './has_automation_equality_bug.js' );
var isConstructorPrototype = require( './is_constructor_prototype.js' );
var HAS_WINDOW = require( './has_window.js' );
// MAIN //
/**
* Wraps the test for constructor prototype equality to accommodate buggy environments (e.g., environments which throw when testing equality).
*
* @private
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether a value equals the prototype of its constructor
*/
function wrapper( value ) {
if ( HAS_WINDOW === false && !hasAutomationEqualityBug ) {
return isConstructorPrototype( value );
}
try {
return isConstructorPrototype( value );
} catch ( error ) { // eslint-disable-line no-unused-vars
return false;
}
}
// EXPORTS //
module.exports = wrapper;
},{"./has_automation_equality_bug.js":433,"./has_window.js":437,"./is_constructor_prototype.js":439}],441:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var hasArgumentsBug = require( './has_arguments_bug.js' );
var HAS_BUILTIN = require( './has_builtin.js' );
var builtin = require( './builtin.js' );
var wrapper = require( './builtin_wrapper.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
/**
* Returns an array of an object's own enumerable property names.
*
* @name keys
* @type {Function}
* @param {*} value - input object
* @returns {Array} a list of own enumerable property names
*
* @example
* var obj = {
* 'beep': 'boop',
* 'foo': 3.14
* };
*
* var k = keys( obj );
* // e.g., returns [ 'beep', 'foo' ]
*/
var keys;
if ( HAS_BUILTIN ) {
if ( hasArgumentsBug() ) {
keys = wrapper;
} else {
keys = builtin;
}
} else {
keys = polyfill;
}
// EXPORTS //
module.exports = keys;
},{"./builtin.js":429,"./builtin_wrapper.js":430,"./has_arguments_bug.js":432,"./has_builtin.js":434,"./polyfill.js":443}],442:[function(require,module,exports){
module.exports=[
"toString",
"toLocaleString",
"valueOf",
"hasOwnProperty",
"isPrototypeOf",
"propertyIsEnumerable",
"constructor"
]
},{}],443:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isObjectLike = require( '@stdlib/assert/is-object-like' );
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var isArguments = require( '@stdlib/assert/is-arguments' );
var HAS_ENUM_PROTO_BUG = require( './has_enumerable_prototype_bug.js' );
var HAS_NON_ENUM_PROPS_BUG = require( './has_non_enumerable_properties_bug.js' );
var isConstructorPrototype = require( './is_constructor_prototype_wrapper.js' );
var NON_ENUMERABLE = require( './non_enumerable.json' );
// MAIN //
/**
* Returns an array of an object's own enumerable property names.
*
* @private
* @param {*} value - input object
* @returns {Array} a list of own enumerable property names
*
* @example
* var obj = {
* 'beep': 'boop',
* 'foo': 3.14
* };
*
* var k = keys( obj );
* // e.g., returns [ 'beep', 'foo' ]
*/
function keys( value ) {
var skipConstructor;
var skipPrototype;
var isFcn;
var out;
var k;
var p;
var i;
out = [];
if ( isArguments( value ) ) {
// Account for environments which treat `arguments` differently...
for ( i = 0; i < value.length; i++ ) {
out.push( i.toString() );
}
// Note: yes, we are precluding the `arguments` array-like object from having other enumerable properties; however, this should (1) be very rare and (2) not be encouraged (e.g., doing something like `arguments.a = 'b'`; in certain engines directly manipulating the `arguments` value results in automatic de-optimization).
return out;
}
if ( typeof value === 'string' ) {
// Account for environments which do not treat string character indices as "own" properties...
if ( value.length > 0 && !hasOwnProp( value, '0' ) ) {
for ( i = 0; i < value.length; i++ ) {
out.push( i.toString() );
}
}
} else {
isFcn = ( typeof value === 'function' );
if ( isFcn === false && !isObjectLike( value ) ) {
return out;
}
skipPrototype = ( HAS_ENUM_PROTO_BUG && isFcn );
}
for ( k in value ) {
if ( !( skipPrototype && k === 'prototype' ) && hasOwnProp( value, k ) ) {
out.push( String( k ) );
}
}
if ( HAS_NON_ENUM_PROPS_BUG ) {
skipConstructor = isConstructorPrototype( value );
for ( i = 0; i < NON_ENUMERABLE.length; i++ ) {
p = NON_ENUMERABLE[ i ];
if ( !( skipConstructor && p === 'constructor' ) && hasOwnProp( value, p ) ) {
out.push( String( p ) );
}
}
}
return out;
}
// EXPORTS //
module.exports = keys;
},{"./has_enumerable_prototype_bug.js":435,"./has_non_enumerable_properties_bug.js":436,"./is_constructor_prototype_wrapper.js":440,"./non_enumerable.json":442,"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-arguments":74,"@stdlib/assert/is-object-like":143}],444:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var w = ( typeof window === 'undefined' ) ? void 0 : window;
// EXPORTS //
module.exports = w;
},{}],445:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Return a string value indicating a specification defined classification of an object.
*
* @module @stdlib/utils/native-class
*
* @example
* var nativeClass = require( '@stdlib/utils/native-class' );
*
* var str = nativeClass( 'a' );
* // returns '[object String]'
*
* str = nativeClass( 5 );
* // returns '[object Number]'
*
* function Beep() {
* return this;
* }
* str = nativeClass( new Beep() );
* // returns '[object Object]'
*/
// MODULES //
var hasToStringTag = require( '@stdlib/assert/has-tostringtag-support' );
var builtin = require( './native_class.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var nativeClass;
if ( hasToStringTag() ) {
nativeClass = polyfill;
} else {
nativeClass = builtin;
}
// EXPORTS //
module.exports = nativeClass;
},{"./native_class.js":446,"./polyfill.js":447,"@stdlib/assert/has-tostringtag-support":57}],446:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var toStr = require( './tostring.js' );
// MAIN //
/**
* Returns a string value indicating a specification defined classification (via the internal property `[[Class]]`) of an object.
*
* @param {*} v - input value
* @returns {string} string value indicating a specification defined classification of the input value
*
* @example
* var str = nativeClass( 'a' );
* // returns '[object String]'
*
* @example
* var str = nativeClass( 5 );
* // returns '[object Number]'
*
* @example
* function Beep() {
* return this;
* }
* var str = nativeClass( new Beep() );
* // returns '[object Object]'
*/
function nativeClass( v ) {
return toStr.call( v );
}
// EXPORTS //
module.exports = nativeClass;
},{"./tostring.js":448}],447:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var toStringTag = require( './tostringtag.js' );
var toStr = require( './tostring.js' );
// MAIN //
/**
* Returns a string value indicating a specification defined classification of an object in environments supporting `Symbol.toStringTag`.
*
* @param {*} v - input value
* @returns {string} string value indicating a specification defined classification of the input value
*
* @example
* var str = nativeClass( 'a' );
* // returns '[object String]'
*
* @example
* var str = nativeClass( 5 );
* // returns '[object Number]'
*
* @example
* function Beep() {
* return this;
* }
* var str = nativeClass( new Beep() );
* // returns '[object Object]'
*/
function nativeClass( v ) {
var isOwn;
var tag;
var out;
if ( v === null || v === void 0 ) {
return toStr.call( v );
}
tag = v[ toStringTag ];
isOwn = hasOwnProp( v, toStringTag );
// Attempt to override the `toStringTag` property. For built-ins having a `Symbol.toStringTag` property (e.g., `JSON`, `Math`, etc), the `Symbol.toStringTag` property is read-only (e.g., , so we need to wrap in a `try/catch`.
try {
v[ toStringTag ] = void 0;
} catch ( err ) { // eslint-disable-line no-unused-vars
return toStr.call( v );
}
out = toStr.call( v );
if ( isOwn ) {
v[ toStringTag ] = tag;
} else {
delete v[ toStringTag ];
}
return out;
}
// EXPORTS //
module.exports = nativeClass;
},{"./tostring.js":448,"./tostringtag.js":449,"@stdlib/assert/has-own-property":53}],448:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var toStr = Object.prototype.toString;
// EXPORTS //
module.exports = toStr;
},{}],449:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var toStrTag = ( typeof Symbol === 'function' ) ? Symbol.toStringTag : '';
// EXPORTS //
module.exports = toStrTag;
},{}],450:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2020 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Add a callback to the "next tick queue".
*
* @module @stdlib/utils/next-tick
*
* @example
* var nextTick = require( '@stdlib/utils/next-tick' );
*
* function beep() {
* console.log( 'boop' );
* }
*
* nextTick( beep );
*/
// MODULES //
var nextTick = require( './main.js' );
// EXPORTS //
module.exports = nextTick;
},{"./main.js":451}],451:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2020 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var proc = require( 'process' );
// MAIN //
/**
* Adds a callback to the "next tick queue".
*
* ## Notes
*
* - The queue is fully drained after the current operation on the JavaScript stack runs to completion and before the event loop is allowed to continue.
*
* @param {Callback} clbk - callback
* @param {...*} [args] - arguments to provide to the callback upon invocation
*
* @example
* function beep() {
* console.log( 'boop' );
* }
*
* nextTick( beep );
*/
function nextTick( clbk ) {
var args;
var i;
args = [];
for ( i = 1; i < arguments.length; i++ ) {
args.push( arguments[ i ] );
}
proc.nextTick( wrapper );
/**
* Callback wrapper.
*
* ## Notes
*
* - The ability to provide additional arguments was added in Node.js v1.8.1. The wrapper provides support for earlier Node.js versions.
*
* @private
*/
function wrapper() {
clbk.apply( null, args );
}
}
// EXPORTS //
module.exports = nextTick;
},{"process":491}],452:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* No operation.
*
* @module @stdlib/utils/noop
*
* @example
* var noop = require( '@stdlib/utils/noop' );
*
* noop();
* // ...does nothing.
*/
// MODULES //
var noop = require( './noop.js' );
// EXPORTS //
module.exports = noop;
},{"./noop.js":453}],453:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* No operation.
*
* @example
* noop();
* // ...does nothing.
*/
function noop() {
// Empty function...
}
// EXPORTS //
module.exports = noop;
},{}],454:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Return a partial object copy excluding specified keys.
*
* @module @stdlib/utils/omit
*
* @example
* var omit = require( '@stdlib/utils/omit' );
*
* var obj1 = {
* 'a': 1,
* 'b': 2
* };
*
* var obj2 = omit( obj1, 'b' );
* // returns { 'a': 1 }
*/
// MODULES //
var omit = require( './omit.js' );
// EXPORTS //
module.exports = omit;
},{"./omit.js":455}],455:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var objectKeys = require( '@stdlib/utils/keys' );
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var isStringArray = require( '@stdlib/assert/is-string-array' ).primitives;
var indexOf = require( '@stdlib/utils/index-of' );
// MAIN //
/**
* Returns a partial object copy excluding specified keys.
*
* @param {Object} obj - source object
* @param {(string|StringArray)} keys - keys to exclude
* @throws {TypeError} first argument must be an object
* @throws {TypeError} second argument must be either a string or an array of strings
* @returns {Object} new object
*
* @example
* var obj1 = {
* 'a': 1,
* 'b': 2
* };
*
* var obj2 = omit( obj1, 'b' );
* // returns { 'a': 1 }
*/
function omit( obj, keys ) {
var ownKeys;
var out;
var key;
var i;
if ( typeof obj !== 'object' || obj === null ) {
throw new TypeError( 'invalid argument. First argument must be an object. Value: `'+obj+'`.' );
}
ownKeys = objectKeys( obj );
out = {};
if ( isString( keys ) ) {
for ( i = 0; i < ownKeys.length; i++ ) {
key = ownKeys[ i ];
if ( key !== keys ) {
out[ key ] = obj[ key ];
}
}
return out;
}
if ( isStringArray( keys ) ) {
for ( i = 0; i < ownKeys.length; i++ ) {
key = ownKeys[ i ];
if ( indexOf( keys, key ) === -1 ) {
out[ key ] = obj[ key ];
}
}
return out;
}
throw new TypeError( 'invalid argument. Second argument must be either a string primitive or an array of string primitives. Value: `'+keys+'`.' );
}
// EXPORTS //
module.exports = omit;
},{"@stdlib/assert/is-string":158,"@stdlib/assert/is-string-array":157,"@stdlib/utils/index-of":421,"@stdlib/utils/keys":438}],456:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Return a partial object copy containing only specified keys.
*
* @module @stdlib/utils/pick
*
* @example
* var pick = require( '@stdlib/utils/pick' );
*
* var obj1 = {
* 'a': 1,
* 'b': 2
* };
*
* var obj2 = pick( obj1, 'b' );
* // returns { 'b': 2 }
*/
// MODULES //
var pick = require( './pick.js' );
// EXPORTS //
module.exports = pick;
},{"./pick.js":457}],457:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var isStringArray = require( '@stdlib/assert/is-string-array' ).primitives;
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
// MAIN //
/**
* Returns a partial object copy containing only specified keys. If a key does not exist as an own property in a source object, the key is ignored.
*
* @param {Object} obj - source object
* @param {(string|StringArray)} keys - keys to copy
* @throws {TypeError} first argument must be an object
* @throws {TypeError} second argument must be either a string or an array of strings
* @returns {Object} new object
*
* @example
* var obj1 = {
* 'a': 1,
* 'b': 2
* };
*
* var obj2 = pick( obj1, 'b' );
* // returns { 'b': 2 }
*/
function pick( obj, keys ) {
var out;
var key;
var i;
if ( typeof obj !== 'object' || obj === null ) {
throw new TypeError( 'invalid argument. First argument must be an object. Value: `'+obj+'`.' );
}
out = {};
if ( isString( keys ) ) {
if ( hasOwnProp( obj, keys ) ) {
out[ keys ] = obj[ keys ];
}
return out;
}
if ( isStringArray( keys ) ) {
for ( i = 0; i < keys.length; i++ ) {
key = keys[ i ];
if ( hasOwnProp( obj, key ) ) {
out[ key ] = obj[ key ];
}
}
return out;
}
throw new TypeError( 'invalid argument. Second argument must be either a string primitive or an array of string primitives. Value: `'+keys+'`.' );
}
// EXPORTS //
module.exports = pick;
},{"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-string":158,"@stdlib/assert/is-string-array":157}],458:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// VARIABLES //
var propertyDescriptor = Object.getOwnPropertyDescriptor;
// MAIN //
/**
* Returns a property descriptor for an object's own property.
*
* ## Notes
*
* - In contrast to the built-in `Object.getOwnPropertyDescriptor()`, this function returns `null` if provided `undefined` or `null`, rather than throwing an error.
* - In contrast to the built-in `Object.getOwnPropertyDescriptor()`, this function returns `null` if an object does not have a provided property, rather than `undefined`.
*
* @private
* @param {*} value - input object
* @param {(string|symbol)} property - property
* @returns {(Object|null)} property descriptor or null
*
* @example
* var obj = {
* 'beep': 'boop',
* 'foo': 3.14
* };
*
* var desc = getOwnPropertyDescriptor( obj, 'foo' );
* // returns {'configurable':true,'enumerable':true,'writable':true,'value':3.14}
*/
function getOwnPropertyDescriptor( value, property ) {
var desc;
if ( value === null || value === void 0 ) {
return null;
}
desc = propertyDescriptor( value, property );
return ( desc === void 0 ) ? null : desc;
}
// EXPORTS //
module.exports = getOwnPropertyDescriptor;
},{}],459:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var bool = ( typeof Object.getOwnPropertyDescriptor !== 'undefined' );
// EXPORTS //
module.exports = bool;
},{}],460:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Return a property descriptor for an object's own property.
*
* @module @stdlib/utils/property-descriptor
*
* @example
* var getOwnPropertyDescriptor = require( '@stdlib/utils/property-descriptor' );
*
* var obj = {
* 'foo': 'bar',
* 'beep': 'boop'
* };
*
* var keys = getOwnPropertyDescriptor( obj, 'foo' );
* // returns {'configurable':true,'enumerable':true,'writable':true,'value':'bar'}
*/
// MODULES //
var HAS_BUILTIN = require( './has_builtin.js' );
var builtin = require( './builtin.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var main;
if ( HAS_BUILTIN ) {
main = builtin;
} else {
main = polyfill;
}
// EXPORTS //
module.exports = main;
},{"./builtin.js":458,"./has_builtin.js":459,"./polyfill.js":461}],461:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
// MAIN //
/**
* Returns a property descriptor for an object's own property.
*
* ## Notes
*
* - In contrast to the built-in `Object.getOwnPropertyDescriptor()`, this function returns `null` if provided `undefined` or `null`, rather than throwing an error.
* - In contrast to the built-in `Object.getOwnPropertyDescriptor()`, this function returns `null` if an object does not have a provided property, rather than `undefined`.
* - In environments lacking `Object.getOwnPropertyDescriptor()` support, property descriptors do not exist. In non-supporting environment, if an object has a provided property, this function returns a descriptor object equivalent to that returned in a supporting environment; otherwise, the function returns `null`.
*
* @private
* @param {*} value - input object
* @param {(string|symbol)} property - property
* @returns {(Object|null)} property descriptor or null
*
* @example
* var obj = {
* 'beep': 'boop',
* 'foo': 3.14
* };
*
* var desc = getOwnPropertyDescriptor( obj, 'foo' );
* // returns {'configurable':true,'enumerable':true,'writable':true,'value':3.14}
*/
function getOwnPropertyDescriptor( value, property ) {
if ( hasOwnProp( value, property ) ) {
return {
'configurable': true,
'enumerable': true,
'writable': true,
'value': value[ property ]
};
}
return null;
}
// EXPORTS //
module.exports = getOwnPropertyDescriptor;
},{"@stdlib/assert/has-own-property":53}],462:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// VARIABLES //
var propertyNames = Object.getOwnPropertyNames;
// MAIN //
/**
* Returns an array of an object's own enumerable and non-enumerable property names.
*
* ## Notes
*
* - In contrast to the built-in `Object.getOwnPropertyNames()`, this function returns an empty array if provided `undefined` or `null`, rather than throwing an error.
*
* @private
* @param {*} value - input object
* @returns {Array} a list of own property names
*
* @example
* var obj = {
* 'beep': 'boop',
* 'foo': 3.14
* };
*
* var keys = getOwnPropertyNames( obj );
* // e.g., returns [ 'beep', 'foo' ]
*/
function getOwnPropertyNames( value ) {
return propertyNames( Object( value ) );
}
// EXPORTS //
module.exports = getOwnPropertyNames;
},{}],463:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var bool = ( typeof Object.getOwnPropertyNames !== 'undefined' );
// EXPORTS //
module.exports = bool;
},{}],464:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Return an array of an object's own enumerable and non-enumerable property names.
*
* @module @stdlib/utils/property-names
*
* @example
* var getOwnPropertyNames = require( '@stdlib/utils/property-names' );
*
* var keys = getOwnPropertyNames({
* 'foo': 'bar',
* 'beep': 'boop'
* });
* // e.g., returns [ 'foo', 'beep' ]
*/
// MODULES //
var HAS_BUILTIN = require( './has_builtin.js' );
var builtin = require( './builtin.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var main;
if ( HAS_BUILTIN ) {
main = builtin;
} else {
main = polyfill;
}
// EXPORTS //
module.exports = main;
},{"./builtin.js":462,"./has_builtin.js":463,"./polyfill.js":465}],465:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var keys = require( '@stdlib/utils/keys' );
// MAIN //
/**
* Returns an array of an object's own enumerable and non-enumerable property names.
*
* ## Notes
*
* - In contrast to the built-in `Object.getOwnPropertyNames()`, this function returns an empty array if provided `undefined` or `null`, rather than throwing an error.
* - In environments lacking support for `Object.getOwnPropertyNames()`, property descriptors are unavailable, and thus all properties can be safely assumed to be enumerable. Hence, we can defer to calling `Object.keys`, which retrieves all own enumerable property names.
*
* @private
* @param {*} value - input object
* @returns {Array} a list of own property names
*
* @example
* var obj = {
* 'beep': 'boop',
* 'foo': 3.14
* };
*
* var keys = getOwnPropertyNames( obj );
* // e.g., returns [ 'beep', 'foo' ]
*/
function getOwnPropertyNames( value ) {
return keys( Object( value ) );
}
// EXPORTS //
module.exports = getOwnPropertyNames;
},{"@stdlib/utils/keys":438}],466:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var reRegExp = require( '@stdlib/regexp/regexp' );
// MAIN //
/**
* Parses a regular expression string and returns a new regular expression.
*
* @param {string} str - regular expression string
* @throws {TypeError} must provide a regular expression string
* @returns {(RegExp|null)} regular expression or null
*
* @example
* var re = reFromString( '/beep/' );
* // returns /beep/
*/
function reFromString( str ) {
if ( !isString( str ) ) {
throw new TypeError( 'invalid argument. Must provide a regular expression string. Value: `' + str + '`.' );
}
// Capture the regular expression pattern and any flags:
str = reRegExp().exec( str );
// Create a new regular expression:
return ( str ) ? new RegExp( str[1], str[2] ) : null;
}
// EXPORTS //
module.exports = reFromString;
},{"@stdlib/assert/is-string":158,"@stdlib/regexp/regexp":357}],467:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Create a regular expression from a regular expression string.
*
* @module @stdlib/utils/regexp-from-string
*
* @example
* var reFromString = require( '@stdlib/utils/regexp-from-string' );
*
* var re = reFromString( '/beep/' );
* // returns /beep/
*/
// MODULES //
var reFromString = require( './from_string.js' );
// EXPORTS //
module.exports = reFromString;
},{"./from_string.js":466}],468:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Wrap `require` in a try/catch block.
*
* @module @stdlib/utils/try-require
*
* @example
* var tryRequire = require( '@stdlib/utils/try-require' );
*
* var out = tryRequire( 'beepboop' );
*
* if ( out instanceof Error ) {
* console.log( out.message );
* }
*/
// MODULES //
var tryRequire = require( './try_require.js' );
// EXPORTS //
module.exports = tryRequire;
},{"./try_require.js":469}],469:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isError = require( '@stdlib/assert/is-error' );
// MAIN //
/**
* Wraps `require` in a try/catch block.
*
* @param {string} id - module id
* @returns {*|Error} `module.exports` of the resolved module or an error
*
* @example
* var out = tryRequire( 'beepboop' );
*
* if ( out instanceof Error ) {
* console.error( out.message );
* }
*/
function tryRequire( id ) {
try {
return require( id ); // eslint-disable-line stdlib/no-dynamic-require
} catch ( error ) {
if ( isError( error ) ) {
return error;
}
// Handle case where a literal is thrown...
if ( typeof error === 'object' ) {
return new Error( JSON.stringify( error ) );
}
return new Error( error.toString() );
}
}
// EXPORTS //
module.exports = tryRequire;
},{"@stdlib/assert/is-error":96}],470:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var RE = require( './fixtures/re.js' );
var nodeList = require( './fixtures/nodelist.js' );
var typedarray = require( './fixtures/typedarray.js' );
// MAIN //
/**
* Checks whether a polyfill is needed when using the `typeof` operator.
*
* @private
* @returns {boolean} boolean indicating whether a polyfill is needed
*/
function check() {
if (
// Chrome 1-12 returns 'function' for regular expression instances (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof):
typeof RE === 'function' ||
// Safari 8 returns 'object' for typed array and weak map constructors (underscore #1929):
typeof typedarray === 'object' ||
// PhantomJS 1.9 returns 'function' for `NodeList` instances (underscore #2236):
typeof nodeList === 'function'
) {
return true;
}
return false;
}
// EXPORTS //
module.exports = check;
},{"./fixtures/nodelist.js":471,"./fixtures/re.js":472,"./fixtures/typedarray.js":473}],471:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var getGlobal = require( '@stdlib/utils/global' );
// MAIN //
var root = getGlobal();
var nodeList = root.document && root.document.childNodes;
// EXPORTS //
module.exports = nodeList;
},{"@stdlib/utils/global":417}],472:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
var RE = /./;
// EXPORTS //
module.exports = RE;
},{}],473:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
var typedarray = Int8Array; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = typedarray;
},{}],474:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Determine a value's type.
*
* @module @stdlib/utils/type-of
*
* @example
* var typeOf = require( '@stdlib/utils/type-of' );
*
* var str = typeOf( 'a' );
* // returns 'string'
*
* str = typeOf( 5 );
* // returns 'number'
*/
// MODULES //
var usePolyfill = require( './check.js' );
var typeOf = require( './typeof.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var main = ( usePolyfill() ) ? polyfill : typeOf;
// EXPORTS //
module.exports = main;
},{"./check.js":470,"./polyfill.js":475,"./typeof.js":476}],475:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var ctorName = require( '@stdlib/utils/constructor-name' );
// MAIN //
/**
* Determines a value's type.
*
* @param {*} v - input value
* @returns {string} string indicating the value's type
*/
function typeOf( v ) {
return ctorName( v ).toLowerCase();
}
// EXPORTS //
module.exports = typeOf;
},{"@stdlib/utils/constructor-name":388}],476:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var ctorName = require( '@stdlib/utils/constructor-name' );
// NOTES //
/*
* Built-in `typeof` operator behavior:
*
* ```text
* typeof null => 'object'
* typeof undefined => 'undefined'
* typeof 'a' => 'string'
* typeof 5 => 'number'
* typeof NaN => 'number'
* typeof true => 'boolean'
* typeof false => 'boolean'
* typeof {} => 'object'
* typeof [] => 'object'
* typeof function foo(){} => 'function'
* typeof function* foo(){} => 'object'
* typeof Symbol() => 'symbol'
* ```
*
*/
// MAIN //
/**
* Determines a value's type.
*
* @param {*} v - input value
* @returns {string} string indicating the value's type
*/
function typeOf( v ) {
var type;
// Address `typeof null` => `object` (see http://wiki.ecmascript.org/doku.php?id=harmony:typeof_null):
if ( v === null ) {
return 'null';
}
type = typeof v;
// If the `typeof` operator returned something other than `object`, we are done. Otherwise, we need to check for an internal class name or search for a constructor.
if ( type === 'object' ) {
return ctorName( v ).toLowerCase();
}
return type;
}
// EXPORTS //
module.exports = typeOf;
},{"@stdlib/utils/constructor-name":388}],477:[function(require,module,exports){
'use strict'
exports.byteLength = byteLength
exports.toByteArray = toByteArray
exports.fromByteArray = fromByteArray
var lookup = []
var revLookup = []
var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
for (var i = 0, len = code.length; i < len; ++i) {
lookup[i] = code[i]
revLookup[code.charCodeAt(i)] = i
}
// Support decoding URL-safe base64 strings, as Node.js does.
// See: https://en.wikipedia.org/wiki/Base64#URL_applications
revLookup['-'.charCodeAt(0)] = 62
revLookup['_'.charCodeAt(0)] = 63
function getLens (b64) {
var len = b64.length
if (len % 4 > 0) {
throw new Error('Invalid string. Length must be a multiple of 4')
}
// Trim off extra bytes after placeholder bytes are found
// See: https://github.com/beatgammit/base64-js/issues/42
var validLen = b64.indexOf('=')
if (validLen === -1) validLen = len
var placeHoldersLen = validLen === len
? 0
: 4 - (validLen % 4)
return [validLen, placeHoldersLen]
}
// base64 is 4/3 + up to two characters of the original data
function byteLength (b64) {
var lens = getLens(b64)
var validLen = lens[0]
var placeHoldersLen = lens[1]
return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
}
function _byteLength (b64, validLen, placeHoldersLen) {
return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
}
function toByteArray (b64) {
var tmp
var lens = getLens(b64)
var validLen = lens[0]
var placeHoldersLen = lens[1]
var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
var curByte = 0
// if there are placeholders, only get up to the last complete 4 chars
var len = placeHoldersLen > 0
? validLen - 4
: validLen
var i
for (i = 0; i < len; i += 4) {
tmp =
(revLookup[b64.charCodeAt(i)] << 18) |
(revLookup[b64.charCodeAt(i + 1)] << 12) |
(revLookup[b64.charCodeAt(i + 2)] << 6) |
revLookup[b64.charCodeAt(i + 3)]
arr[curByte++] = (tmp >> 16) & 0xFF
arr[curByte++] = (tmp >> 8) & 0xFF
arr[curByte++] = tmp & 0xFF
}
if (placeHoldersLen === 2) {
tmp =
(revLookup[b64.charCodeAt(i)] << 2) |
(revLookup[b64.charCodeAt(i + 1)] >> 4)
arr[curByte++] = tmp & 0xFF
}
if (placeHoldersLen === 1) {
tmp =
(revLookup[b64.charCodeAt(i)] << 10) |
(revLookup[b64.charCodeAt(i + 1)] << 4) |
(revLookup[b64.charCodeAt(i + 2)] >> 2)
arr[curByte++] = (tmp >> 8) & 0xFF
arr[curByte++] = tmp & 0xFF
}
return arr
}
function tripletToBase64 (num) {
return lookup[num >> 18 & 0x3F] +
lookup[num >> 12 & 0x3F] +
lookup[num >> 6 & 0x3F] +
lookup[num & 0x3F]
}
function encodeChunk (uint8, start, end) {
var tmp
var output = []
for (var i = start; i < end; i += 3) {
tmp =
((uint8[i] << 16) & 0xFF0000) +
((uint8[i + 1] << 8) & 0xFF00) +
(uint8[i + 2] & 0xFF)
output.push(tripletToBase64(tmp))
}
return output.join('')
}
function fromByteArray (uint8) {
var tmp
var len = uint8.length
var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
var parts = []
var maxChunkLength = 16383 // must be multiple of 3
// go through the array every three bytes, we'll deal with trailing stuff later
for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
}
// pad the end with zeros, but make sure to not forget the extra bytes
if (extraBytes === 1) {
tmp = uint8[len - 1]
parts.push(
lookup[tmp >> 2] +
lookup[(tmp << 4) & 0x3F] +
'=='
)
} else if (extraBytes === 2) {
tmp = (uint8[len - 2] << 8) + uint8[len - 1]
parts.push(
lookup[tmp >> 10] +
lookup[(tmp >> 4) & 0x3F] +
lookup[(tmp << 2) & 0x3F] +
'='
)
}
return parts.join('')
}
},{}],478:[function(require,module,exports){
},{}],479:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
'use strict';
var R = typeof Reflect === 'object' ? Reflect : null
var ReflectApply = R && typeof R.apply === 'function'
? R.apply
: function ReflectApply(target, receiver, args) {
return Function.prototype.apply.call(target, receiver, args);
}
var ReflectOwnKeys
if (R && typeof R.ownKeys === 'function') {
ReflectOwnKeys = R.ownKeys
} else if (Object.getOwnPropertySymbols) {
ReflectOwnKeys = function ReflectOwnKeys(target) {
return Object.getOwnPropertyNames(target)
.concat(Object.getOwnPropertySymbols(target));
};
} else {
ReflectOwnKeys = function ReflectOwnKeys(target) {
return Object.getOwnPropertyNames(target);
};
}
function ProcessEmitWarning(warning) {
if (console && console.warn) console.warn(warning);
}
var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {
return value !== value;
}
function EventEmitter() {
EventEmitter.init.call(this);
}
module.exports = EventEmitter;
module.exports.once = once;
// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._eventsCount = 0;
EventEmitter.prototype._maxListeners = undefined;
// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
var defaultMaxListeners = 10;
function checkListener(listener) {
if (typeof listener !== 'function') {
throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
}
}
Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
enumerable: true,
get: function() {
return defaultMaxListeners;
},
set: function(arg) {
if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {
throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.');
}
defaultMaxListeners = arg;
}
});
EventEmitter.init = function() {
if (this._events === undefined ||
this._events === Object.getPrototypeOf(this)._events) {
this._events = Object.create(null);
this._eventsCount = 0;
}
this._maxListeners = this._maxListeners || undefined;
};
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {
throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.');
}
this._maxListeners = n;
return this;
};
function _getMaxListeners(that) {
if (that._maxListeners === undefined)
return EventEmitter.defaultMaxListeners;
return that._maxListeners;
}
EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
return _getMaxListeners(this);
};
EventEmitter.prototype.emit = function emit(type) {
var args = [];
for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);
var doError = (type === 'error');
var events = this._events;
if (events !== undefined)
doError = (doError && events.error === undefined);
else if (!doError)
return false;
// If there is no 'error' event listener then throw.
if (doError) {
var er;
if (args.length > 0)
er = args[0];
if (er instanceof Error) {
// Note: The comments on the `throw` lines are intentional, they show
// up in Node's output if this results in an unhandled exception.
throw er; // Unhandled 'error' event
}
// At least give some kind of context to the user
var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));
err.context = er;
throw err; // Unhandled 'error' event
}
var handler = events[type];
if (handler === undefined)
return false;
if (typeof handler === 'function') {
ReflectApply(handler, this, args);
} else {
var len = handler.length;
var listeners = arrayClone(handler, len);
for (var i = 0; i < len; ++i)
ReflectApply(listeners[i], this, args);
}
return true;
};
function _addListener(target, type, listener, prepend) {
var m;
var events;
var existing;
checkListener(listener);
events = target._events;
if (events === undefined) {
events = target._events = Object.create(null);
target._eventsCount = 0;
} else {
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (events.newListener !== undefined) {
target.emit('newListener', type,
listener.listener ? listener.listener : listener);
// Re-assign `events` because a newListener handler could have caused the
// this._events to be assigned to a new object
events = target._events;
}
existing = events[type];
}
if (existing === undefined) {
// Optimize the case of one listener. Don't need the extra array object.
existing = events[type] = listener;
++target._eventsCount;
} else {
if (typeof existing === 'function') {
// Adding the second element, need to change to array.
existing = events[type] =
prepend ? [listener, existing] : [existing, listener];
// If we've already got an array, just append.
} else if (prepend) {
existing.unshift(listener);
} else {
existing.push(listener);
}
// Check for listener leak
m = _getMaxListeners(target);
if (m > 0 && existing.length > m && !existing.warned) {
existing.warned = true;
// No error code for this since it is a Warning
// eslint-disable-next-line no-restricted-syntax
var w = new Error('Possible EventEmitter memory leak detected. ' +
existing.length + ' ' + String(type) + ' listeners ' +
'added. Use emitter.setMaxListeners() to ' +
'increase limit');
w.name = 'MaxListenersExceededWarning';
w.emitter = target;
w.type = type;
w.count = existing.length;
ProcessEmitWarning(w);
}
}
return target;
}
EventEmitter.prototype.addListener = function addListener(type, listener) {
return _addListener(this, type, listener, false);
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.prependListener =
function prependListener(type, listener) {
return _addListener(this, type, listener, true);
};
function onceWrapper() {
if (!this.fired) {
this.target.removeListener(this.type, this.wrapFn);
this.fired = true;
if (arguments.length === 0)
return this.listener.call(this.target);
return this.listener.apply(this.target, arguments);
}
}
function _onceWrap(target, type, listener) {
var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
var wrapped = onceWrapper.bind(state);
wrapped.listener = listener;
state.wrapFn = wrapped;
return wrapped;
}
EventEmitter.prototype.once = function once(type, listener) {
checkListener(listener);
this.on(type, _onceWrap(this, type, listener));
return this;
};
EventEmitter.prototype.prependOnceListener =
function prependOnceListener(type, listener) {
checkListener(listener);
this.prependListener(type, _onceWrap(this, type, listener));
return this;
};
// Emits a 'removeListener' event if and only if the listener was removed.
EventEmitter.prototype.removeListener =
function removeListener(type, listener) {
var list, events, position, i, originalListener;
checkListener(listener);
events = this._events;
if (events === undefined)
return this;
list = events[type];
if (list === undefined)
return this;
if (list === listener || list.listener === listener) {
if (--this._eventsCount === 0)
this._events = Object.create(null);
else {
delete events[type];
if (events.removeListener)
this.emit('removeListener', type, list.listener || listener);
}
} else if (typeof list !== 'function') {
position = -1;
for (i = list.length - 1; i >= 0; i--) {
if (list[i] === listener || list[i].listener === listener) {
originalListener = list[i].listener;
position = i;
break;
}
}
if (position < 0)
return this;
if (position === 0)
list.shift();
else {
spliceOne(list, position);
}
if (list.length === 1)
events[type] = list[0];
if (events.removeListener !== undefined)
this.emit('removeListener', type, originalListener || listener);
}
return this;
};
EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
EventEmitter.prototype.removeAllListeners =
function removeAllListeners(type) {
var listeners, events, i;
events = this._events;
if (events === undefined)
return this;
// not listening for removeListener, no need to emit
if (events.removeListener === undefined) {
if (arguments.length === 0) {
this._events = Object.create(null);
this._eventsCount = 0;
} else if (events[type] !== undefined) {
if (--this._eventsCount === 0)
this._events = Object.create(null);
else
delete events[type];
}
return this;
}
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
var keys = Object.keys(events);
var key;
for (i = 0; i < keys.length; ++i) {
key = keys[i];
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = Object.create(null);
this._eventsCount = 0;
return this;
}
listeners = events[type];
if (typeof listeners === 'function') {
this.removeListener(type, listeners);
} else if (listeners !== undefined) {
// LIFO order
for (i = listeners.length - 1; i >= 0; i--) {
this.removeListener(type, listeners[i]);
}
}
return this;
};
function _listeners(target, type, unwrap) {
var events = target._events;
if (events === undefined)
return [];
var evlistener = events[type];
if (evlistener === undefined)
return [];
if (typeof evlistener === 'function')
return unwrap ? [evlistener.listener || evlistener] : [evlistener];
return unwrap ?
unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
}
EventEmitter.prototype.listeners = function listeners(type) {
return _listeners(this, type, true);
};
EventEmitter.prototype.rawListeners = function rawListeners(type) {
return _listeners(this, type, false);
};
EventEmitter.listenerCount = function(emitter, type) {
if (typeof emitter.listenerCount === 'function') {
return emitter.listenerCount(type);
} else {
return listenerCount.call(emitter, type);
}
};
EventEmitter.prototype.listenerCount = listenerCount;
function listenerCount(type) {
var events = this._events;
if (events !== undefined) {
var evlistener = events[type];
if (typeof evlistener === 'function') {
return 1;
} else if (evlistener !== undefined) {
return evlistener.length;
}
}
return 0;
}
EventEmitter.prototype.eventNames = function eventNames() {
return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];
};
function arrayClone(arr, n) {
var copy = new Array(n);
for (var i = 0; i < n; ++i)
copy[i] = arr[i];
return copy;
}
function spliceOne(list, index) {
for (; index + 1 < list.length; index++)
list[index] = list[index + 1];
list.pop();
}
function unwrapListeners(arr) {
var ret = new Array(arr.length);
for (var i = 0; i < ret.length; ++i) {
ret[i] = arr[i].listener || arr[i];
}
return ret;
}
function once(emitter, name) {
return new Promise(function (resolve, reject) {
function errorListener(err) {
emitter.removeListener(name, resolver);
reject(err);
}
function resolver() {
if (typeof emitter.removeListener === 'function') {
emitter.removeListener('error', errorListener);
}
resolve([].slice.call(arguments));
};
eventTargetAgnosticAddListener(emitter, name, resolver, { once: true });
if (name !== 'error') {
addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true });
}
});
}
function addErrorHandlerIfEventEmitter(emitter, handler, flags) {
if (typeof emitter.on === 'function') {
eventTargetAgnosticAddListener(emitter, 'error', handler, flags);
}
}
function eventTargetAgnosticAddListener(emitter, name, listener, flags) {
if (typeof emitter.on === 'function') {
if (flags.once) {
emitter.once(name, listener);
} else {
emitter.on(name, listener);
}
} else if (typeof emitter.addEventListener === 'function') {
// EventTarget does not have `error` event semantics like Node
// EventEmitters, we do not listen for `error` events here.
emitter.addEventListener(name, function wrapListener(arg) {
// IE does not have builtin `{ once: true }` support so we
// have to do it manually.
if (flags.once) {
emitter.removeEventListener(name, wrapListener);
}
listener(arg);
});
} else {
throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter);
}
}
},{}],480:[function(require,module,exports){
(function (process){(function (){
// 'path' module extracted from Node.js v8.11.1 (only the posix part)
// transplited with Babel
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
'use strict';
function assertPath(path) {
if (typeof path !== 'string') {
throw new TypeError('Path must be a string. Received ' + JSON.stringify(path));
}
}
// Resolves . and .. elements in a path with directory names
function normalizeStringPosix(path, allowAboveRoot) {
var res = '';
var lastSegmentLength = 0;
var lastSlash = -1;
var dots = 0;
var code;
for (var i = 0; i <= path.length; ++i) {
if (i < path.length)
code = path.charCodeAt(i);
else if (code === 47 /*/*/)
break;
else
code = 47 /*/*/;
if (code === 47 /*/*/) {
if (lastSlash === i - 1 || dots === 1) {
// NOOP
} else if (lastSlash !== i - 1 && dots === 2) {
if (res.length < 2 || lastSegmentLength !== 2 || res.charCodeAt(res.length - 1) !== 46 /*.*/ || res.charCodeAt(res.length - 2) !== 46 /*.*/) {
if (res.length > 2) {
var lastSlashIndex = res.lastIndexOf('/');
if (lastSlashIndex !== res.length - 1) {
if (lastSlashIndex === -1) {
res = '';
lastSegmentLength = 0;
} else {
res = res.slice(0, lastSlashIndex);
lastSegmentLength = res.length - 1 - res.lastIndexOf('/');
}
lastSlash = i;
dots = 0;
continue;
}
} else if (res.length === 2 || res.length === 1) {
res = '';
lastSegmentLength = 0;
lastSlash = i;
dots = 0;
continue;
}
}
if (allowAboveRoot) {
if (res.length > 0)
res += '/..';
else
res = '..';
lastSegmentLength = 2;
}
} else {
if (res.length > 0)
res += '/' + path.slice(lastSlash + 1, i);
else
res = path.slice(lastSlash + 1, i);
lastSegmentLength = i - lastSlash - 1;
}
lastSlash = i;
dots = 0;
} else if (code === 46 /*.*/ && dots !== -1) {
++dots;
} else {
dots = -1;
}
}
return res;
}
function _format(sep, pathObject) {
var dir = pathObject.dir || pathObject.root;
var base = pathObject.base || (pathObject.name || '') + (pathObject.ext || '');
if (!dir) {
return base;
}
if (dir === pathObject.root) {
return dir + base;
}
return dir + sep + base;
}
var posix = {
// path.resolve([from ...], to)
resolve: function resolve() {
var resolvedPath = '';
var resolvedAbsolute = false;
var cwd;
for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
var path;
if (i >= 0)
path = arguments[i];
else {
if (cwd === undefined)
cwd = process.cwd();
path = cwd;
}
assertPath(path);
// Skip empty entries
if (path.length === 0) {
continue;
}
resolvedPath = path + '/' + resolvedPath;
resolvedAbsolute = path.charCodeAt(0) === 47 /*/*/;
}
// At this point the path should be resolved to a full absolute path, but
// handle relative paths to be safe (might happen when process.cwd() fails)
// Normalize the path
resolvedPath = normalizeStringPosix(resolvedPath, !resolvedAbsolute);
if (resolvedAbsolute) {
if (resolvedPath.length > 0)
return '/' + resolvedPath;
else
return '/';
} else if (resolvedPath.length > 0) {
return resolvedPath;
} else {
return '.';
}
},
normalize: function normalize(path) {
assertPath(path);
if (path.length === 0) return '.';
var isAbsolute = path.charCodeAt(0) === 47 /*/*/;
var trailingSeparator = path.charCodeAt(path.length - 1) === 47 /*/*/;
// Normalize the path
path = normalizeStringPosix(path, !isAbsolute);
if (path.length === 0 && !isAbsolute) path = '.';
if (path.length > 0 && trailingSeparator) path += '/';
if (isAbsolute) return '/' + path;
return path;
},
isAbsolute: function isAbsolute(path) {
assertPath(path);
return path.length > 0 && path.charCodeAt(0) === 47 /*/*/;
},
join: function join() {
if (arguments.length === 0)
return '.';
var joined;
for (var i = 0; i < arguments.length; ++i) {
var arg = arguments[i];
assertPath(arg);
if (arg.length > 0) {
if (joined === undefined)
joined = arg;
else
joined += '/' + arg;
}
}
if (joined === undefined)
return '.';
return posix.normalize(joined);
},
relative: function relative(from, to) {
assertPath(from);
assertPath(to);
if (from === to) return '';
from = posix.resolve(from);
to = posix.resolve(to);
if (from === to) return '';
// Trim any leading backslashes
var fromStart = 1;
for (; fromStart < from.length; ++fromStart) {
if (from.charCodeAt(fromStart) !== 47 /*/*/)
break;
}
var fromEnd = from.length;
var fromLen = fromEnd - fromStart;
// Trim any leading backslashes
var toStart = 1;
for (; toStart < to.length; ++toStart) {
if (to.charCodeAt(toStart) !== 47 /*/*/)
break;
}
var toEnd = to.length;
var toLen = toEnd - toStart;
// Compare paths to find the longest common path from root
var length = fromLen < toLen ? fromLen : toLen;
var lastCommonSep = -1;
var i = 0;
for (; i <= length; ++i) {
if (i === length) {
if (toLen > length) {
if (to.charCodeAt(toStart + i) === 47 /*/*/) {
// We get here if `from` is the exact base path for `to`.
// For example: from='/foo/bar'; to='/foo/bar/baz'
return to.slice(toStart + i + 1);
} else if (i === 0) {
// We get here if `from` is the root
// For example: from='/'; to='/foo'
return to.slice(toStart + i);
}
} else if (fromLen > length) {
if (from.charCodeAt(fromStart + i) === 47 /*/*/) {
// We get here if `to` is the exact base path for `from`.
// For example: from='/foo/bar/baz'; to='/foo/bar'
lastCommonSep = i;
} else if (i === 0) {
// We get here if `to` is the root.
// For example: from='/foo'; to='/'
lastCommonSep = 0;
}
}
break;
}
var fromCode = from.charCodeAt(fromStart + i);
var toCode = to.charCodeAt(toStart + i);
if (fromCode !== toCode)
break;
else if (fromCode === 47 /*/*/)
lastCommonSep = i;
}
var out = '';
// Generate the relative path based on the path difference between `to`
// and `from`
for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
if (i === fromEnd || from.charCodeAt(i) === 47 /*/*/) {
if (out.length === 0)
out += '..';
else
out += '/..';
}
}
// Lastly, append the rest of the destination (`to`) path that comes after
// the common path parts
if (out.length > 0)
return out + to.slice(toStart + lastCommonSep);
else {
toStart += lastCommonSep;
if (to.charCodeAt(toStart) === 47 /*/*/)
++toStart;
return to.slice(toStart);
}
},
_makeLong: function _makeLong(path) {
return path;
},
dirname: function dirname(path) {
assertPath(path);
if (path.length === 0) return '.';
var code = path.charCodeAt(0);
var hasRoot = code === 47 /*/*/;
var end = -1;
var matchedSlash = true;
for (var i = path.length - 1; i >= 1; --i) {
code = path.charCodeAt(i);
if (code === 47 /*/*/) {
if (!matchedSlash) {
end = i;
break;
}
} else {
// We saw the first non-path separator
matchedSlash = false;
}
}
if (end === -1) return hasRoot ? '/' : '.';
if (hasRoot && end === 1) return '//';
return path.slice(0, end);
},
basename: function basename(path, ext) {
if (ext !== undefined && typeof ext !== 'string') throw new TypeError('"ext" argument must be a string');
assertPath(path);
var start = 0;
var end = -1;
var matchedSlash = true;
var i;
if (ext !== undefined && ext.length > 0 && ext.length <= path.length) {
if (ext.length === path.length && ext === path) return '';
var extIdx = ext.length - 1;
var firstNonSlashEnd = -1;
for (i = path.length - 1; i >= 0; --i) {
var code = path.charCodeAt(i);
if (code === 47 /*/*/) {
// If we reached a path separator that was not part of a set of path
// separators at the end of the string, stop now
if (!matchedSlash) {
start = i + 1;
break;
}
} else {
if (firstNonSlashEnd === -1) {
// We saw the first non-path separator, remember this index in case
// we need it if the extension ends up not matching
matchedSlash = false;
firstNonSlashEnd = i + 1;
}
if (extIdx >= 0) {
// Try to match the explicit extension
if (code === ext.charCodeAt(extIdx)) {
if (--extIdx === -1) {
// We matched the extension, so mark this as the end of our path
// component
end = i;
}
} else {
// Extension does not match, so our result is the entire path
// component
extIdx = -1;
end = firstNonSlashEnd;
}
}
}
}
if (start === end) end = firstNonSlashEnd;else if (end === -1) end = path.length;
return path.slice(start, end);
} else {
for (i = path.length - 1; i >= 0; --i) {
if (path.charCodeAt(i) === 47 /*/*/) {
// If we reached a path separator that was not part of a set of path
// separators at the end of the string, stop now
if (!matchedSlash) {
start = i + 1;
break;
}
} else if (end === -1) {
// We saw the first non-path separator, mark this as the end of our
// path component
matchedSlash = false;
end = i + 1;
}
}
if (end === -1) return '';
return path.slice(start, end);
}
},
extname: function extname(path) {
assertPath(path);
var startDot = -1;
var startPart = 0;
var end = -1;
var matchedSlash = true;
// Track the state of characters (if any) we see before our first dot and
// after any path separator we find
var preDotState = 0;
for (var i = path.length - 1; i >= 0; --i) {
var code = path.charCodeAt(i);
if (code === 47 /*/*/) {
// If we reached a path separator that was not part of a set of path
// separators at the end of the string, stop now
if (!matchedSlash) {
startPart = i + 1;
break;
}
continue;
}
if (end === -1) {
// We saw the first non-path separator, mark this as the end of our
// extension
matchedSlash = false;
end = i + 1;
}
if (code === 46 /*.*/) {
// If this is our first dot, mark it as the start of our extension
if (startDot === -1)
startDot = i;
else if (preDotState !== 1)
preDotState = 1;
} else if (startDot !== -1) {
// We saw a non-dot and non-path separator before our dot, so we should
// have a good chance at having a non-empty extension
preDotState = -1;
}
}
if (startDot === -1 || end === -1 ||
// We saw a non-dot character immediately before the dot
preDotState === 0 ||
// The (right-most) trimmed path component is exactly '..'
preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
return '';
}
return path.slice(startDot, end);
},
format: function format(pathObject) {
if (pathObject === null || typeof pathObject !== 'object') {
throw new TypeError('The "pathObject" argument must be of type Object. Received type ' + typeof pathObject);
}
return _format('/', pathObject);
},
parse: function parse(path) {
assertPath(path);
var ret = { root: '', dir: '', base: '', ext: '', name: '' };
if (path.length === 0) return ret;
var code = path.charCodeAt(0);
var isAbsolute = code === 47 /*/*/;
var start;
if (isAbsolute) {
ret.root = '/';
start = 1;
} else {
start = 0;
}
var startDot = -1;
var startPart = 0;
var end = -1;
var matchedSlash = true;
var i = path.length - 1;
// Track the state of characters (if any) we see before our first dot and
// after any path separator we find
var preDotState = 0;
// Get non-dir info
for (; i >= start; --i) {
code = path.charCodeAt(i);
if (code === 47 /*/*/) {
// If we reached a path separator that was not part of a set of path
// separators at the end of the string, stop now
if (!matchedSlash) {
startPart = i + 1;
break;
}
continue;
}
if (end === -1) {
// We saw the first non-path separator, mark this as the end of our
// extension
matchedSlash = false;
end = i + 1;
}
if (code === 46 /*.*/) {
// If this is our first dot, mark it as the start of our extension
if (startDot === -1) startDot = i;else if (preDotState !== 1) preDotState = 1;
} else if (startDot !== -1) {
// We saw a non-dot and non-path separator before our dot, so we should
// have a good chance at having a non-empty extension
preDotState = -1;
}
}
if (startDot === -1 || end === -1 ||
// We saw a non-dot character immediately before the dot
preDotState === 0 ||
// The (right-most) trimmed path component is exactly '..'
preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
if (end !== -1) {
if (startPart === 0 && isAbsolute) ret.base = ret.name = path.slice(1, end);else ret.base = ret.name = path.slice(startPart, end);
}
} else {
if (startPart === 0 && isAbsolute) {
ret.name = path.slice(1, startDot);
ret.base = path.slice(1, end);
} else {
ret.name = path.slice(startPart, startDot);
ret.base = path.slice(startPart, end);
}
ret.ext = path.slice(startDot, end);
}
if (startPart > 0) ret.dir = path.slice(0, startPart - 1);else if (isAbsolute) ret.dir = '/';
return ret;
},
sep: '/',
delimiter: ':',
win32: null,
posix: null
};
posix.posix = posix;
module.exports = posix;
}).call(this)}).call(this,require('_process'))
},{"_process":491}],481:[function(require,module,exports){
(function (Buffer){(function (){
/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <https://feross.org>
* @license MIT
*/
/* eslint-disable no-proto */
'use strict'
var base64 = require('base64-js')
var ieee754 = require('ieee754')
exports.Buffer = Buffer
exports.SlowBuffer = SlowBuffer
exports.INSPECT_MAX_BYTES = 50
var K_MAX_LENGTH = 0x7fffffff
exports.kMaxLength = K_MAX_LENGTH
/**
* If `Buffer.TYPED_ARRAY_SUPPORT`:
* === true Use Uint8Array implementation (fastest)
* === false Print warning and recommend using `buffer` v4.x which has an Object
* implementation (most compatible, even IE6)
*
* Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
* Opera 11.6+, iOS 4.2+.
*
* We report that the browser does not support typed arrays if the are not subclassable
* using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
* (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
* for __proto__ and has a buggy typed array implementation.
*/
Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
typeof console.error === 'function') {
console.error(
'This browser lacks typed array (Uint8Array) support which is required by ' +
'`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
)
}
function typedArraySupport () {
// Can typed array instances can be augmented?
try {
var arr = new Uint8Array(1)
arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } }
return arr.foo() === 42
} catch (e) {
return false
}
}
Object.defineProperty(Buffer.prototype, 'parent', {
enumerable: true,
get: function () {
if (!Buffer.isBuffer(this)) return undefined
return this.buffer
}
})
Object.defineProperty(Buffer.prototype, 'offset', {
enumerable: true,
get: function () {
if (!Buffer.isBuffer(this)) return undefined
return this.byteOffset
}
})
function createBuffer (length) {
if (length > K_MAX_LENGTH) {
throw new RangeError('The value "' + length + '" is invalid for option "size"')
}
// Return an augmented `Uint8Array` instance
var buf = new Uint8Array(length)
buf.__proto__ = Buffer.prototype
return buf
}
/**
* The Buffer constructor returns instances of `Uint8Array` that have their
* prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
* `Uint8Array`, so the returned instances will have all the node `Buffer` methods
* and the `Uint8Array` methods. Square bracket notation works as expected -- it
* returns a single octet.
*
* The `Uint8Array` prototype remains unmodified.
*/
function Buffer (arg, encodingOrOffset, length) {
// Common case.
if (typeof arg === 'number') {
if (typeof encodingOrOffset === 'string') {
throw new TypeError(
'The "string" argument must be of type string. Received type number'
)
}
return allocUnsafe(arg)
}
return from(arg, encodingOrOffset, length)
}
// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
if (typeof Symbol !== 'undefined' && Symbol.species != null &&
Buffer[Symbol.species] === Buffer) {
Object.defineProperty(Buffer, Symbol.species, {
value: null,
configurable: true,
enumerable: false,
writable: false
})
}
Buffer.poolSize = 8192 // not used by this implementation
function from (value, encodingOrOffset, length) {
if (typeof value === 'string') {
return fromString(value, encodingOrOffset)
}
if (ArrayBuffer.isView(value)) {
return fromArrayLike(value)
}
if (value == null) {
throw TypeError(
'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
'or Array-like Object. Received type ' + (typeof value)
)
}
if (isInstance(value, ArrayBuffer) ||
(value && isInstance(value.buffer, ArrayBuffer))) {
return fromArrayBuffer(value, encodingOrOffset, length)
}
if (typeof value === 'number') {
throw new TypeError(
'The "value" argument must not be of type number. Received type number'
)
}
var valueOf = value.valueOf && value.valueOf()
if (valueOf != null && valueOf !== value) {
return Buffer.from(valueOf, encodingOrOffset, length)
}
var b = fromObject(value)
if (b) return b
if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
typeof value[Symbol.toPrimitive] === 'function') {
return Buffer.from(
value[Symbol.toPrimitive]('string'), encodingOrOffset, length
)
}
throw new TypeError(
'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
'or Array-like Object. Received type ' + (typeof value)
)
}
/**
* Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
* if value is a number.
* Buffer.from(str[, encoding])
* Buffer.from(array)
* Buffer.from(buffer)
* Buffer.from(arrayBuffer[, byteOffset[, length]])
**/
Buffer.from = function (value, encodingOrOffset, length) {
return from(value, encodingOrOffset, length)
}
// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
// https://github.com/feross/buffer/pull/148
Buffer.prototype.__proto__ = Uint8Array.prototype
Buffer.__proto__ = Uint8Array
function assertSize (size) {
if (typeof size !== 'number') {
throw new TypeError('"size" argument must be of type number')
} else if (size < 0) {
throw new RangeError('The value "' + size + '" is invalid for option "size"')
}
}
function alloc (size, fill, encoding) {
assertSize(size)
if (size <= 0) {
return createBuffer(size)
}
if (fill !== undefined) {
// Only pay attention to encoding if it's a string. This
// prevents accidentally sending in a number that would
// be interpretted as a start offset.
return typeof encoding === 'string'
? createBuffer(size).fill(fill, encoding)
: createBuffer(size).fill(fill)
}
return createBuffer(size)
}
/**
* Creates a new filled Buffer instance.
* alloc(size[, fill[, encoding]])
**/
Buffer.alloc = function (size, fill, encoding) {
return alloc(size, fill, encoding)
}
function allocUnsafe (size) {
assertSize(size)
return createBuffer(size < 0 ? 0 : checked(size) | 0)
}
/**
* Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
* */
Buffer.allocUnsafe = function (size) {
return allocUnsafe(size)
}
/**
* Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
*/
Buffer.allocUnsafeSlow = function (size) {
return allocUnsafe(size)
}
function fromString (string, encoding) {
if (typeof encoding !== 'string' || encoding === '') {
encoding = 'utf8'
}
if (!Buffer.isEncoding(encoding)) {
throw new TypeError('Unknown encoding: ' + encoding)
}
var length = byteLength(string, encoding) | 0
var buf = createBuffer(length)
var actual = buf.write(string, encoding)
if (actual !== length) {
// Writing a hex string, for example, that contains invalid characters will
// cause everything after the first invalid character to be ignored. (e.g.
// 'abxxcd' will be treated as 'ab')
buf = buf.slice(0, actual)
}
return buf
}
function fromArrayLike (array) {
var length = array.length < 0 ? 0 : checked(array.length) | 0
var buf = createBuffer(length)
for (var i = 0; i < length; i += 1) {
buf[i] = array[i] & 255
}
return buf
}
function fromArrayBuffer (array, byteOffset, length) {
if (byteOffset < 0 || array.byteLength < byteOffset) {
throw new RangeError('"offset" is outside of buffer bounds')
}
if (array.byteLength < byteOffset + (length || 0)) {
throw new RangeError('"length" is outside of buffer bounds')
}
var buf
if (byteOffset === undefined && length === undefined) {
buf = new Uint8Array(array)
} else if (length === undefined) {
buf = new Uint8Array(array, byteOffset)
} else {
buf = new Uint8Array(array, byteOffset, length)
}
// Return an augmented `Uint8Array` instance
buf.__proto__ = Buffer.prototype
return buf
}
function fromObject (obj) {
if (Buffer.isBuffer(obj)) {
var len = checked(obj.length) | 0
var buf = createBuffer(len)
if (buf.length === 0) {
return buf
}
obj.copy(buf, 0, 0, len)
return buf
}
if (obj.length !== undefined) {
if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
return createBuffer(0)
}
return fromArrayLike(obj)
}
if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
return fromArrayLike(obj.data)
}
}
function checked (length) {
// Note: cannot use `length < K_MAX_LENGTH` here because that fails when
// length is NaN (which is otherwise coerced to zero.)
if (length >= K_MAX_LENGTH) {
throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
}
return length | 0
}
function SlowBuffer (length) {
if (+length != length) { // eslint-disable-line eqeqeq
length = 0
}
return Buffer.alloc(+length)
}
Buffer.isBuffer = function isBuffer (b) {
return b != null && b._isBuffer === true &&
b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
}
Buffer.compare = function compare (a, b) {
if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)
if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)
if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
throw new TypeError(
'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
)
}
if (a === b) return 0
var x = a.length
var y = b.length
for (var i = 0, len = Math.min(x, y); i < len; ++i) {
if (a[i] !== b[i]) {
x = a[i]
y = b[i]
break
}
}
if (x < y) return -1
if (y < x) return 1
return 0
}
Buffer.isEncoding = function isEncoding (encoding) {
switch (String(encoding).toLowerCase()) {
case 'hex':
case 'utf8':
case 'utf-8':
case 'ascii':
case 'latin1':
case 'binary':
case 'base64':
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return true
default:
return false
}
}
Buffer.concat = function concat (list, length) {
if (!Array.isArray(list)) {
throw new TypeError('"list" argument must be an Array of Buffers')
}
if (list.length === 0) {
return Buffer.alloc(0)
}
var i
if (length === undefined) {
length = 0
for (i = 0; i < list.length; ++i) {
length += list[i].length
}
}
var buffer = Buffer.allocUnsafe(length)
var pos = 0
for (i = 0; i < list.length; ++i) {
var buf = list[i]
if (isInstance(buf, Uint8Array)) {
buf = Buffer.from(buf)
}
if (!Buffer.isBuffer(buf)) {
throw new TypeError('"list" argument must be an Array of Buffers')
}
buf.copy(buffer, pos)
pos += buf.length
}
return buffer
}
function byteLength (string, encoding) {
if (Buffer.isBuffer(string)) {
return string.length
}
if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
return string.byteLength
}
if (typeof string !== 'string') {
throw new TypeError(
'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
'Received type ' + typeof string
)
}
var len = string.length
var mustMatch = (arguments.length > 2 && arguments[2] === true)
if (!mustMatch && len === 0) return 0
// Use a for loop to avoid recursion
var loweredCase = false
for (;;) {
switch (encoding) {
case 'ascii':
case 'latin1':
case 'binary':
return len
case 'utf8':
case 'utf-8':
return utf8ToBytes(string).length
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return len * 2
case 'hex':
return len >>> 1
case 'base64':
return base64ToBytes(string).length
default:
if (loweredCase) {
return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
}
encoding = ('' + encoding).toLowerCase()
loweredCase = true
}
}
}
Buffer.byteLength = byteLength
function slowToString (encoding, start, end) {
var loweredCase = false
// No need to verify that "this.length <= MAX_UINT32" since it's a read-only
// property of a typed array.
// This behaves neither like String nor Uint8Array in that we set start/end
// to their upper/lower bounds if the value passed is out of range.
// undefined is handled specially as per ECMA-262 6th Edition,
// Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
if (start === undefined || start < 0) {
start = 0
}
// Return early if start > this.length. Done here to prevent potential uint32
// coercion fail below.
if (start > this.length) {
return ''
}
if (end === undefined || end > this.length) {
end = this.length
}
if (end <= 0) {
return ''
}
// Force coersion to uint32. This will also coerce falsey/NaN values to 0.
end >>>= 0
start >>>= 0
if (end <= start) {
return ''
}
if (!encoding) encoding = 'utf8'
while (true) {
switch (encoding) {
case 'hex':
return hexSlice(this, start, end)
case 'utf8':
case 'utf-8':
return utf8Slice(this, start, end)
case 'ascii':
return asciiSlice(this, start, end)
case 'latin1':
case 'binary':
return latin1Slice(this, start, end)
case 'base64':
return base64Slice(this, start, end)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return utf16leSlice(this, start, end)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = (encoding + '').toLowerCase()
loweredCase = true
}
}
}
// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
// reliably in a browserify context because there could be multiple different
// copies of the 'buffer' package in use. This method works even for Buffer
// instances that were created from another copy of the `buffer` package.
// See: https://github.com/feross/buffer/issues/154
Buffer.prototype._isBuffer = true
function swap (b, n, m) {
var i = b[n]
b[n] = b[m]
b[m] = i
}
Buffer.prototype.swap16 = function swap16 () {
var len = this.length
if (len % 2 !== 0) {
throw new RangeError('Buffer size must be a multiple of 16-bits')
}
for (var i = 0; i < len; i += 2) {
swap(this, i, i + 1)
}
return this
}
Buffer.prototype.swap32 = function swap32 () {
var len = this.length
if (len % 4 !== 0) {
throw new RangeError('Buffer size must be a multiple of 32-bits')
}
for (var i = 0; i < len; i += 4) {
swap(this, i, i + 3)
swap(this, i + 1, i + 2)
}
return this
}
Buffer.prototype.swap64 = function swap64 () {
var len = this.length
if (len % 8 !== 0) {
throw new RangeError('Buffer size must be a multiple of 64-bits')
}
for (var i = 0; i < len; i += 8) {
swap(this, i, i + 7)
swap(this, i + 1, i + 6)
swap(this, i + 2, i + 5)
swap(this, i + 3, i + 4)
}
return this
}
Buffer.prototype.toString = function toString () {
var length = this.length
if (length === 0) return ''
if (arguments.length === 0) return utf8Slice(this, 0, length)
return slowToString.apply(this, arguments)
}
Buffer.prototype.toLocaleString = Buffer.prototype.toString
Buffer.prototype.equals = function equals (b) {
if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
if (this === b) return true
return Buffer.compare(this, b) === 0
}
Buffer.prototype.inspect = function inspect () {
var str = ''
var max = exports.INSPECT_MAX_BYTES
str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()
if (this.length > max) str += ' ... '
return '<Buffer ' + str + '>'
}
Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
if (isInstance(target, Uint8Array)) {
target = Buffer.from(target, target.offset, target.byteLength)
}
if (!Buffer.isBuffer(target)) {
throw new TypeError(
'The "target" argument must be one of type Buffer or Uint8Array. ' +
'Received type ' + (typeof target)
)
}
if (start === undefined) {
start = 0
}
if (end === undefined) {
end = target ? target.length : 0
}
if (thisStart === undefined) {
thisStart = 0
}
if (thisEnd === undefined) {
thisEnd = this.length
}
if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
throw new RangeError('out of range index')
}
if (thisStart >= thisEnd && start >= end) {
return 0
}
if (thisStart >= thisEnd) {
return -1
}
if (start >= end) {
return 1
}
start >>>= 0
end >>>= 0
thisStart >>>= 0
thisEnd >>>= 0
if (this === target) return 0
var x = thisEnd - thisStart
var y = end - start
var len = Math.min(x, y)
var thisCopy = this.slice(thisStart, thisEnd)
var targetCopy = target.slice(start, end)
for (var i = 0; i < len; ++i) {
if (thisCopy[i] !== targetCopy[i]) {
x = thisCopy[i]
y = targetCopy[i]
break
}
}
if (x < y) return -1
if (y < x) return 1
return 0
}
// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
//
// Arguments:
// - buffer - a Buffer to search
// - val - a string, Buffer, or number
// - byteOffset - an index into `buffer`; will be clamped to an int32
// - encoding - an optional encoding, relevant is val is a string
// - dir - true for indexOf, false for lastIndexOf
function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
// Empty buffer means no match
if (buffer.length === 0) return -1
// Normalize byteOffset
if (typeof byteOffset === 'string') {
encoding = byteOffset
byteOffset = 0
} else if (byteOffset > 0x7fffffff) {
byteOffset = 0x7fffffff
} else if (byteOffset < -0x80000000) {
byteOffset = -0x80000000
}
byteOffset = +byteOffset // Coerce to Number.
if (numberIsNaN(byteOffset)) {
// byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
byteOffset = dir ? 0 : (buffer.length - 1)
}
// Normalize byteOffset: negative offsets start from the end of the buffer
if (byteOffset < 0) byteOffset = buffer.length + byteOffset
if (byteOffset >= buffer.length) {
if (dir) return -1
else byteOffset = buffer.length - 1
} else if (byteOffset < 0) {
if (dir) byteOffset = 0
else return -1
}
// Normalize val
if (typeof val === 'string') {
val = Buffer.from(val, encoding)
}
// Finally, search either indexOf (if dir is true) or lastIndexOf
if (Buffer.isBuffer(val)) {
// Special case: looking for empty string/buffer always fails
if (val.length === 0) {
return -1
}
return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
} else if (typeof val === 'number') {
val = val & 0xFF // Search for a byte value [0-255]
if (typeof Uint8Array.prototype.indexOf === 'function') {
if (dir) {
return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
} else {
return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
}
}
return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
}
throw new TypeError('val must be string, number or Buffer')
}
function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
var indexSize = 1
var arrLength = arr.length
var valLength = val.length
if (encoding !== undefined) {
encoding = String(encoding).toLowerCase()
if (encoding === 'ucs2' || encoding === 'ucs-2' ||
encoding === 'utf16le' || encoding === 'utf-16le') {
if (arr.length < 2 || val.length < 2) {
return -1
}
indexSize = 2
arrLength /= 2
valLength /= 2
byteOffset /= 2
}
}
function read (buf, i) {
if (indexSize === 1) {
return buf[i]
} else {
return buf.readUInt16BE(i * indexSize)
}
}
var i
if (dir) {
var foundIndex = -1
for (i = byteOffset; i < arrLength; i++) {
if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
if (foundIndex === -1) foundIndex = i
if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
} else {
if (foundIndex !== -1) i -= i - foundIndex
foundIndex = -1
}
}
} else {
if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
for (i = byteOffset; i >= 0; i--) {
var found = true
for (var j = 0; j < valLength; j++) {
if (read(arr, i + j) !== read(val, j)) {
found = false
break
}
}
if (found) return i
}
}
return -1
}
Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
return this.indexOf(val, byteOffset, encoding) !== -1
}
Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
}
Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
}
function hexWrite (buf, string, offset, length) {
offset = Number(offset) || 0
var remaining = buf.length - offset
if (!length) {
length = remaining
} else {
length = Number(length)
if (length > remaining) {
length = remaining
}
}
var strLen = string.length
if (length > strLen / 2) {
length = strLen / 2
}
for (var i = 0; i < length; ++i) {
var parsed = parseInt(string.substr(i * 2, 2), 16)
if (numberIsNaN(parsed)) return i
buf[offset + i] = parsed
}
return i
}
function utf8Write (buf, string, offset, length) {
return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
}
function asciiWrite (buf, string, offset, length) {
return blitBuffer(asciiToBytes(string), buf, offset, length)
}
function latin1Write (buf, string, offset, length) {
return asciiWrite(buf, string, offset, length)
}
function base64Write (buf, string, offset, length) {
return blitBuffer(base64ToBytes(string), buf, offset, length)
}
function ucs2Write (buf, string, offset, length) {
return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
}
Buffer.prototype.write = function write (string, offset, length, encoding) {
// Buffer#write(string)
if (offset === undefined) {
encoding = 'utf8'
length = this.length
offset = 0
// Buffer#write(string, encoding)
} else if (length === undefined && typeof offset === 'string') {
encoding = offset
length = this.length
offset = 0
// Buffer#write(string, offset[, length][, encoding])
} else if (isFinite(offset)) {
offset = offset >>> 0
if (isFinite(length)) {
length = length >>> 0
if (encoding === undefined) encoding = 'utf8'
} else {
encoding = length
length = undefined
}
} else {
throw new Error(
'Buffer.write(string, encoding, offset[, length]) is no longer supported'
)
}
var remaining = this.length - offset
if (length === undefined || length > remaining) length = remaining
if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
throw new RangeError('Attempt to write outside buffer bounds')
}
if (!encoding) encoding = 'utf8'
var loweredCase = false
for (;;) {
switch (encoding) {
case 'hex':
return hexWrite(this, string, offset, length)
case 'utf8':
case 'utf-8':
return utf8Write(this, string, offset, length)
case 'ascii':
return asciiWrite(this, string, offset, length)
case 'latin1':
case 'binary':
return latin1Write(this, string, offset, length)
case 'base64':
// Warning: maxLength not taken into account in base64Write
return base64Write(this, string, offset, length)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return ucs2Write(this, string, offset, length)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = ('' + encoding).toLowerCase()
loweredCase = true
}
}
}
Buffer.prototype.toJSON = function toJSON () {
return {
type: 'Buffer',
data: Array.prototype.slice.call(this._arr || this, 0)
}
}
function base64Slice (buf, start, end) {
if (start === 0 && end === buf.length) {
return base64.fromByteArray(buf)
} else {
return base64.fromByteArray(buf.slice(start, end))
}
}
function utf8Slice (buf, start, end) {
end = Math.min(buf.length, end)
var res = []
var i = start
while (i < end) {
var firstByte = buf[i]
var codePoint = null
var bytesPerSequence = (firstByte > 0xEF) ? 4
: (firstByte > 0xDF) ? 3
: (firstByte > 0xBF) ? 2
: 1
if (i + bytesPerSequence <= end) {
var secondByte, thirdByte, fourthByte, tempCodePoint
switch (bytesPerSequence) {
case 1:
if (firstByte < 0x80) {
codePoint = firstByte
}
break
case 2:
secondByte = buf[i + 1]
if ((secondByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
if (tempCodePoint > 0x7F) {
codePoint = tempCodePoint
}
}
break
case 3:
secondByte = buf[i + 1]
thirdByte = buf[i + 2]
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
codePoint = tempCodePoint
}
}
break
case 4:
secondByte = buf[i + 1]
thirdByte = buf[i + 2]
fourthByte = buf[i + 3]
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
codePoint = tempCodePoint
}
}
}
}
if (codePoint === null) {
// we did not generate a valid codePoint so insert a
// replacement char (U+FFFD) and advance only 1 byte
codePoint = 0xFFFD
bytesPerSequence = 1
} else if (codePoint > 0xFFFF) {
// encode to utf16 (surrogate pair dance)
codePoint -= 0x10000
res.push(codePoint >>> 10 & 0x3FF | 0xD800)
codePoint = 0xDC00 | codePoint & 0x3FF
}
res.push(codePoint)
i += bytesPerSequence
}
return decodeCodePointsArray(res)
}
// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
var MAX_ARGUMENTS_LENGTH = 0x1000
function decodeCodePointsArray (codePoints) {
var len = codePoints.length
if (len <= MAX_ARGUMENTS_LENGTH) {
return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
}
// Decode in chunks to avoid "call stack size exceeded".
var res = ''
var i = 0
while (i < len) {
res += String.fromCharCode.apply(
String,
codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
)
}
return res
}
function asciiSlice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i] & 0x7F)
}
return ret
}
function latin1Slice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i])
}
return ret
}
function hexSlice (buf, start, end) {
var len = buf.length
if (!start || start < 0) start = 0
if (!end || end < 0 || end > len) end = len
var out = ''
for (var i = start; i < end; ++i) {
out += toHex(buf[i])
}
return out
}
function utf16leSlice (buf, start, end) {
var bytes = buf.slice(start, end)
var res = ''
for (var i = 0; i < bytes.length; i += 2) {
res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
}
return res
}
Buffer.prototype.slice = function slice (start, end) {
var len = this.length
start = ~~start
end = end === undefined ? len : ~~end
if (start < 0) {
start += len
if (start < 0) start = 0
} else if (start > len) {
start = len
}
if (end < 0) {
end += len
if (end < 0) end = 0
} else if (end > len) {
end = len
}
if (end < start) end = start
var newBuf = this.subarray(start, end)
// Return an augmented `Uint8Array` instance
newBuf.__proto__ = Buffer.prototype
return newBuf
}
/*
* Need to make sure that buffer isn't trying to write out of bounds.
*/
function checkOffset (offset, ext, length) {
if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
}
Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var val = this[offset]
var mul = 1
var i = 0
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul
}
return val
}
Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) {
checkOffset(offset, byteLength, this.length)
}
var val = this[offset + --byteLength]
var mul = 1
while (byteLength > 0 && (mul *= 0x100)) {
val += this[offset + --byteLength] * mul
}
return val
}
Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 1, this.length)
return this[offset]
}
Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
return this[offset] | (this[offset + 1] << 8)
}
Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
return (this[offset] << 8) | this[offset + 1]
}
Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return ((this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16)) +
(this[offset + 3] * 0x1000000)
}
Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] * 0x1000000) +
((this[offset + 1] << 16) |
(this[offset + 2] << 8) |
this[offset + 3])
}
Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var val = this[offset]
var mul = 1
var i = 0
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul
}
mul *= 0x80
if (val >= mul) val -= Math.pow(2, 8 * byteLength)
return val
}
Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var i = byteLength
var mul = 1
var val = this[offset + --i]
while (i > 0 && (mul *= 0x100)) {
val += this[offset + --i] * mul
}
mul *= 0x80
if (val >= mul) val -= Math.pow(2, 8 * byteLength)
return val
}
Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 1, this.length)
if (!(this[offset] & 0x80)) return (this[offset])
return ((0xff - this[offset] + 1) * -1)
}
Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset] | (this[offset + 1] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset + 1] | (this[offset] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16) |
(this[offset + 3] << 24)
}
Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] << 24) |
(this[offset + 1] << 16) |
(this[offset + 2] << 8) |
(this[offset + 3])
}
Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, true, 23, 4)
}
Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, false, 23, 4)
}
Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, true, 52, 8)
}
Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, false, 52, 8)
}
function checkInt (buf, value, offset, ext, max, min) {
if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
if (offset + ext > buf.length) throw new RangeError('Index out of range')
}
Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) {
var maxBytes = Math.pow(2, 8 * byteLength) - 1
checkInt(this, value, offset, byteLength, maxBytes, 0)
}
var mul = 1
var i = 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
this[offset + i] = (value / mul) & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) {
var maxBytes = Math.pow(2, 8 * byteLength) - 1
checkInt(this, value, offset, byteLength, maxBytes, 0)
}
var i = byteLength - 1
var mul = 1
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
this[offset + i] = (value / mul) & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
this[offset] = (value & 0xff)
return offset + 1
}
Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
return offset + 2
}
Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
this[offset] = (value >>> 8)
this[offset + 1] = (value & 0xff)
return offset + 2
}
Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
this[offset + 3] = (value >>> 24)
this[offset + 2] = (value >>> 16)
this[offset + 1] = (value >>> 8)
this[offset] = (value & 0xff)
return offset + 4
}
Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = (value & 0xff)
return offset + 4
}
Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
var limit = Math.pow(2, (8 * byteLength) - 1)
checkInt(this, value, offset, byteLength, limit - 1, -limit)
}
var i = 0
var mul = 1
var sub = 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
sub = 1
}
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
var limit = Math.pow(2, (8 * byteLength) - 1)
checkInt(this, value, offset, byteLength, limit - 1, -limit)
}
var i = byteLength - 1
var mul = 1
var sub = 0
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
sub = 1
}
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
if (value < 0) value = 0xff + value + 1
this[offset] = (value & 0xff)
return offset + 1
}
Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
return offset + 2
}
Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
this[offset] = (value >>> 8)
this[offset + 1] = (value & 0xff)
return offset + 2
}
Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
this[offset + 2] = (value >>> 16)
this[offset + 3] = (value >>> 24)
return offset + 4
}
Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
if (value < 0) value = 0xffffffff + value + 1
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = (value & 0xff)
return offset + 4
}
function checkIEEE754 (buf, value, offset, ext, max, min) {
if (offset + ext > buf.length) throw new RangeError('Index out of range')
if (offset < 0) throw new RangeError('Index out of range')
}
function writeFloat (buf, value, offset, littleEndian, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
}
ieee754.write(buf, value, offset, littleEndian, 23, 4)
return offset + 4
}
Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
return writeFloat(this, value, offset, true, noAssert)
}
Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
return writeFloat(this, value, offset, false, noAssert)
}
function writeDouble (buf, value, offset, littleEndian, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
}
ieee754.write(buf, value, offset, littleEndian, 52, 8)
return offset + 8
}
Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
return writeDouble(this, value, offset, true, noAssert)
}
Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
return writeDouble(this, value, offset, false, noAssert)
}
// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
Buffer.prototype.copy = function copy (target, targetStart, start, end) {
if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
if (!start) start = 0
if (!end && end !== 0) end = this.length
if (targetStart >= target.length) targetStart = target.length
if (!targetStart) targetStart = 0
if (end > 0 && end < start) end = start
// Copy 0 bytes; we're done
if (end === start) return 0
if (target.length === 0 || this.length === 0) return 0
// Fatal error conditions
if (targetStart < 0) {
throw new RangeError('targetStart out of bounds')
}
if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
if (end < 0) throw new RangeError('sourceEnd out of bounds')
// Are we oob?
if (end > this.length) end = this.length
if (target.length - targetStart < end - start) {
end = target.length - targetStart + start
}
var len = end - start
if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
// Use built-in when available, missing from IE11
this.copyWithin(targetStart, start, end)
} else if (this === target && start < targetStart && targetStart < end) {
// descending copy from end
for (var i = len - 1; i >= 0; --i) {
target[i + targetStart] = this[i + start]
}
} else {
Uint8Array.prototype.set.call(
target,
this.subarray(start, end),
targetStart
)
}
return len
}
// Usage:
// buffer.fill(number[, offset[, end]])
// buffer.fill(buffer[, offset[, end]])
// buffer.fill(string[, offset[, end]][, encoding])
Buffer.prototype.fill = function fill (val, start, end, encoding) {
// Handle string cases:
if (typeof val === 'string') {
if (typeof start === 'string') {
encoding = start
start = 0
end = this.length
} else if (typeof end === 'string') {
encoding = end
end = this.length
}
if (encoding !== undefined && typeof encoding !== 'string') {
throw new TypeError('encoding must be a string')
}
if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
throw new TypeError('Unknown encoding: ' + encoding)
}
if (val.length === 1) {
var code = val.charCodeAt(0)
if ((encoding === 'utf8' && code < 128) ||
encoding === 'latin1') {
// Fast path: If `val` fits into a single byte, use that numeric value.
val = code
}
}
} else if (typeof val === 'number') {
val = val & 255
}
// Invalid ranges are not set to a default, so can range check early.
if (start < 0 || this.length < start || this.length < end) {
throw new RangeError('Out of range index')
}
if (end <= start) {
return this
}
start = start >>> 0
end = end === undefined ? this.length : end >>> 0
if (!val) val = 0
var i
if (typeof val === 'number') {
for (i = start; i < end; ++i) {
this[i] = val
}
} else {
var bytes = Buffer.isBuffer(val)
? val
: Buffer.from(val, encoding)
var len = bytes.length
if (len === 0) {
throw new TypeError('The value "' + val +
'" is invalid for argument "value"')
}
for (i = 0; i < end - start; ++i) {
this[i + start] = bytes[i % len]
}
}
return this
}
// HELPER FUNCTIONS
// ================
var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
function base64clean (str) {
// Node takes equal signs as end of the Base64 encoding
str = str.split('=')[0]
// Node strips out invalid characters like \n and \t from the string, base64-js does not
str = str.trim().replace(INVALID_BASE64_RE, '')
// Node converts strings with length < 2 to ''
if (str.length < 2) return ''
// Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
while (str.length % 4 !== 0) {
str = str + '='
}
return str
}
function toHex (n) {
if (n < 16) return '0' + n.toString(16)
return n.toString(16)
}
function utf8ToBytes (string, units) {
units = units || Infinity
var codePoint
var length = string.length
var leadSurrogate = null
var bytes = []
for (var i = 0; i < length; ++i) {
codePoint = string.charCodeAt(i)
// is surrogate component
if (codePoint > 0xD7FF && codePoint < 0xE000) {
// last char was a lead
if (!leadSurrogate) {
// no lead yet
if (codePoint > 0xDBFF) {
// unexpected trail
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
} else if (i + 1 === length) {
// unpaired lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
}
// valid lead
leadSurrogate = codePoint
continue
}
// 2 leads in a row
if (codePoint < 0xDC00) {
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
leadSurrogate = codePoint
continue
}
// valid surrogate pair
codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
} else if (leadSurrogate) {
// valid bmp char, but last char was a lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
}
leadSurrogate = null
// encode utf8
if (codePoint < 0x80) {
if ((units -= 1) < 0) break
bytes.push(codePoint)
} else if (codePoint < 0x800) {
if ((units -= 2) < 0) break
bytes.push(
codePoint >> 0x6 | 0xC0,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x10000) {
if ((units -= 3) < 0) break
bytes.push(
codePoint >> 0xC | 0xE0,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x110000) {
if ((units -= 4) < 0) break
bytes.push(
codePoint >> 0x12 | 0xF0,
codePoint >> 0xC & 0x3F | 0x80,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else {
throw new Error('Invalid code point')
}
}
return bytes
}
function asciiToBytes (str) {
var byteArray = []
for (var i = 0; i < str.length; ++i) {
// Node's code seems to be doing this and not & 0x7F..
byteArray.push(str.charCodeAt(i) & 0xFF)
}
return byteArray
}
function utf16leToBytes (str, units) {
var c, hi, lo
var byteArray = []
for (var i = 0; i < str.length; ++i) {
if ((units -= 2) < 0) break
c = str.charCodeAt(i)
hi = c >> 8
lo = c % 256
byteArray.push(lo)
byteArray.push(hi)
}
return byteArray
}
function base64ToBytes (str) {
return base64.toByteArray(base64clean(str))
}
function blitBuffer (src, dst, offset, length) {
for (var i = 0; i < length; ++i) {
if ((i + offset >= dst.length) || (i >= src.length)) break
dst[i + offset] = src[i]
}
return i
}
// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
// the `instanceof` check but they should be treated as of that type.
// See: https://github.com/feross/buffer/issues/166
function isInstance (obj, type) {
return obj instanceof type ||
(obj != null && obj.constructor != null && obj.constructor.name != null &&
obj.constructor.name === type.name)
}
function numberIsNaN (obj) {
// For IE11 support
return obj !== obj // eslint-disable-line no-self-compare
}
}).call(this)}).call(this,require("buffer").Buffer)
},{"base64-js":477,"buffer":481,"ieee754":485}],482:[function(require,module,exports){
(function (Buffer){(function (){
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(arg) {
if (Array.isArray) {
return Array.isArray(arg);
}
return objectToString(arg) === '[object Array]';
}
exports.isArray = isArray;
function isBoolean(arg) {
return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;
function isNull(arg) {
return arg === null;
}
exports.isNull = isNull;
function isNullOrUndefined(arg) {
return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;
function isNumber(arg) {
return typeof arg === 'number';
}
exports.isNumber = isNumber;
function isString(arg) {
return typeof arg === 'string';
}
exports.isString = isString;
function isSymbol(arg) {
return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;
function isUndefined(arg) {
return arg === void 0;
}
exports.isUndefined = isUndefined;
function isRegExp(re) {
return objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;
function isDate(d) {
return objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
function isError(e) {
return (objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;
function isFunction(arg) {
return typeof arg === 'function';
}
exports.isFunction = isFunction;
function isPrimitive(arg) {
return arg === null ||
typeof arg === 'boolean' ||
typeof arg === 'number' ||
typeof arg === 'string' ||
typeof arg === 'symbol' || // ES6 symbol
typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;
exports.isBuffer = Buffer.isBuffer;
function objectToString(o) {
return Object.prototype.toString.call(o);
}
}).call(this)}).call(this,{"isBuffer":require("../../is-buffer/index.js")})
},{"../../is-buffer/index.js":487}],483:[function(require,module,exports){
(function (process){(function (){
/**
* This is the web browser implementation of `debug()`.
*
* Expose `debug()` as the module.
*/
exports = module.exports = require('./debug');
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.storage = 'undefined' != typeof chrome
&& 'undefined' != typeof chrome.storage
? chrome.storage.local
: localstorage();
/**
* Colors.
*/
exports.colors = [
'lightseagreen',
'forestgreen',
'goldenrod',
'dodgerblue',
'darkorchid',
'crimson'
];
/**
* Currently only WebKit-based Web Inspectors, Firefox >= v31,
* and the Firebug extension (any Firefox version) are known
* to support "%c" CSS customizations.
*
* TODO: add a `localStorage` variable to explicitly enable/disable colors
*/
function useColors() {
// NB: In an Electron preload script, document will be defined but not fully
// initialized. Since we know we're in Chrome, we'll just detect this case
// explicitly
if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') {
return true;
}
// is webkit? http://stackoverflow.com/a/16459606/376773
// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
// is firebug? http://stackoverflow.com/a/398120/376773
(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
// is firefox >= v31?
// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
// double check webkit in userAgent just in case we are in a worker
(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
}
/**
* Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
*/
exports.formatters.j = function(v) {
try {
return JSON.stringify(v);
} catch (err) {
return '[UnexpectedJSONParseError]: ' + err.message;
}
};
/**
* Colorize log arguments if enabled.
*
* @api public
*/
function formatArgs(args) {
var useColors = this.useColors;
args[0] = (useColors ? '%c' : '')
+ this.namespace
+ (useColors ? ' %c' : ' ')
+ args[0]
+ (useColors ? '%c ' : ' ')
+ '+' + exports.humanize(this.diff);
if (!useColors) return;
var c = 'color: ' + this.color;
args.splice(1, 0, c, 'color: inherit')
// the final "%c" is somewhat tricky, because there could be other
// arguments passed either before or after the %c, so we need to
// figure out the correct index to insert the CSS into
var index = 0;
var lastC = 0;
args[0].replace(/%[a-zA-Z%]/g, function(match) {
if ('%%' === match) return;
index++;
if ('%c' === match) {
// we only are interested in the *last* %c
// (the user may have provided their own)
lastC = index;
}
});
args.splice(lastC, 0, c);
}
/**
* Invokes `console.log()` when available.
* No-op when `console.log` is not a "function".
*
* @api public
*/
function log() {
// this hackery is required for IE8/9, where
// the `console.log` function doesn't have 'apply'
return 'object' === typeof console
&& console.log
&& Function.prototype.apply.call(console.log, console, arguments);
}
/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
try {
if (null == namespaces) {
exports.storage.removeItem('debug');
} else {
exports.storage.debug = namespaces;
}
} catch(e) {}
}
/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/
function load() {
var r;
try {
r = exports.storage.debug;
} catch(e) {}
// If debug isn't set in LS, and we're in Electron, try to load $DEBUG
if (!r && typeof process !== 'undefined' && 'env' in process) {
r = process.env.DEBUG;
}
return r;
}
/**
* Enable namespaces listed in `localStorage.debug` initially.
*/
exports.enable(load());
/**
* Localstorage attempts to return the localstorage.
*
* This is necessary because safari throws
* when a user disables cookies/localstorage
* and you attempt to access it.
*
* @return {LocalStorage}
* @api private
*/
function localstorage() {
try {
return window.localStorage;
} catch (e) {}
}
}).call(this)}).call(this,require('_process'))
},{"./debug":484,"_process":491}],484:[function(require,module,exports){
/**
* This is the common logic for both the Node.js and web browser
* implementations of `debug()`.
*
* Expose `debug()` as the module.
*/
exports = module.exports = createDebug.debug = createDebug['default'] = createDebug;
exports.coerce = coerce;
exports.disable = disable;
exports.enable = enable;
exports.enabled = enabled;
exports.humanize = require('ms');
/**
* The currently active debug mode names, and names to skip.
*/
exports.names = [];
exports.skips = [];
/**
* Map of special "%n" handling functions, for the debug "format" argument.
*
* Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
*/
exports.formatters = {};
/**
* Previous log timestamp.
*/
var prevTime;
/**
* Select a color.
* @param {String} namespace
* @return {Number}
* @api private
*/
function selectColor(namespace) {
var hash = 0, i;
for (i in namespace) {
hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
hash |= 0; // Convert to 32bit integer
}
return exports.colors[Math.abs(hash) % exports.colors.length];
}
/**
* Create a debugger with the given `namespace`.
*
* @param {String} namespace
* @return {Function}
* @api public
*/
function createDebug(namespace) {
function debug() {
// disabled?
if (!debug.enabled) return;
var self = debug;
// set `diff` timestamp
var curr = +new Date();
var ms = curr - (prevTime || curr);
self.diff = ms;
self.prev = prevTime;
self.curr = curr;
prevTime = curr;
// turn the `arguments` into a proper Array
var args = new Array(arguments.length);
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i];
}
args[0] = exports.coerce(args[0]);
if ('string' !== typeof args[0]) {
// anything else let's inspect with %O
args.unshift('%O');
}
// apply any `formatters` transformations
var index = 0;
args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) {
// if we encounter an escaped % then don't increase the array index
if (match === '%%') return match;
index++;
var formatter = exports.formatters[format];
if ('function' === typeof formatter) {
var val = args[index];
match = formatter.call(self, val);
// now we need to remove `args[index]` since it's inlined in the `format`
args.splice(index, 1);
index--;
}
return match;
});
// apply env-specific formatting (colors, etc.)
exports.formatArgs.call(self, args);
var logFn = debug.log || exports.log || console.log.bind(console);
logFn.apply(self, args);
}
debug.namespace = namespace;
debug.enabled = exports.enabled(namespace);
debug.useColors = exports.useColors();
debug.color = selectColor(namespace);
// env-specific initialization logic for debug instances
if ('function' === typeof exports.init) {
exports.init(debug);
}
return debug;
}
/**
* Enables a debug mode by namespaces. This can include modes
* separated by a colon and wildcards.
*
* @param {String} namespaces
* @api public
*/
function enable(namespaces) {
exports.save(namespaces);
exports.names = [];
exports.skips = [];
var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
var len = split.length;
for (var i = 0; i < len; i++) {
if (!split[i]) continue; // ignore empty strings
namespaces = split[i].replace(/\*/g, '.*?');
if (namespaces[0] === '-') {
exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
} else {
exports.names.push(new RegExp('^' + namespaces + '$'));
}
}
}
/**
* Disable debug output.
*
* @api public
*/
function disable() {
exports.enable('');
}
/**
* Returns true if the given mode name is enabled, false otherwise.
*
* @param {String} name
* @return {Boolean}
* @api public
*/
function enabled(name) {
var i, len;
for (i = 0, len = exports.skips.length; i < len; i++) {
if (exports.skips[i].test(name)) {
return false;
}
}
for (i = 0, len = exports.names.length; i < len; i++) {
if (exports.names[i].test(name)) {
return true;
}
}
return false;
}
/**
* Coerce `val`.
*
* @param {Mixed} val
* @return {Mixed}
* @api private
*/
function coerce(val) {
if (val instanceof Error) return val.stack || val.message;
return val;
}
},{"ms":489}],485:[function(require,module,exports){
/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
exports.read = function (buffer, offset, isLE, mLen, nBytes) {
var e, m
var eLen = (nBytes * 8) - mLen - 1
var eMax = (1 << eLen) - 1
var eBias = eMax >> 1
var nBits = -7
var i = isLE ? (nBytes - 1) : 0
var d = isLE ? -1 : 1
var s = buffer[offset + i]
i += d
e = s & ((1 << (-nBits)) - 1)
s >>= (-nBits)
nBits += eLen
for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
m = e & ((1 << (-nBits)) - 1)
e >>= (-nBits)
nBits += mLen
for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
if (e === 0) {
e = 1 - eBias
} else if (e === eMax) {
return m ? NaN : ((s ? -1 : 1) * Infinity)
} else {
m = m + Math.pow(2, mLen)
e = e - eBias
}
return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
}
exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
var e, m, c
var eLen = (nBytes * 8) - mLen - 1
var eMax = (1 << eLen) - 1
var eBias = eMax >> 1
var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
var i = isLE ? 0 : (nBytes - 1)
var d = isLE ? 1 : -1
var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
value = Math.abs(value)
if (isNaN(value) || value === Infinity) {
m = isNaN(value) ? 1 : 0
e = eMax
} else {
e = Math.floor(Math.log(value) / Math.LN2)
if (value * (c = Math.pow(2, -e)) < 1) {
e--
c *= 2
}
if (e + eBias >= 1) {
value += rt / c
} else {
value += rt * Math.pow(2, 1 - eBias)
}
if (value * c >= 2) {
e++
c /= 2
}
if (e + eBias >= eMax) {
m = 0
e = eMax
} else if (e + eBias >= 1) {
m = ((value * c) - 1) * Math.pow(2, mLen)
e = e + eBias
} else {
m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
e = 0
}
}
for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
e = (e << mLen) | m
eLen += mLen
for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
buffer[offset + i - d] |= s * 128
}
},{}],486:[function(require,module,exports){
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
if (superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
})
}
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
if (superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
}
},{}],487:[function(require,module,exports){
/*!
* Determine if an object is a Buffer
*
* @author Feross Aboukhadijeh <https://feross.org>
* @license MIT
*/
// The _isBuffer check is for Safari 5-7 support, because it's missing
// Object.prototype.constructor. Remove this eventually
module.exports = function (obj) {
return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
}
function isBuffer (obj) {
return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
}
// For Node v0.10 support. Remove this eventually.
function isSlowBuffer (obj) {
return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
}
},{}],488:[function(require,module,exports){
var toString = {}.toString;
module.exports = Array.isArray || function (arr) {
return toString.call(arr) == '[object Array]';
};
},{}],489:[function(require,module,exports){
/**
* Helpers.
*/
var s = 1000;
var m = s * 60;
var h = m * 60;
var d = h * 24;
var y = d * 365.25;
/**
* Parse or format the given `val`.
*
* Options:
*
* - `long` verbose formatting [false]
*
* @param {String|Number} val
* @param {Object} [options]
* @throws {Error} throw an error if val is not a non-empty string or a number
* @return {String|Number}
* @api public
*/
module.exports = function(val, options) {
options = options || {};
var type = typeof val;
if (type === 'string' && val.length > 0) {
return parse(val);
} else if (type === 'number' && isNaN(val) === false) {
return options.long ? fmtLong(val) : fmtShort(val);
}
throw new Error(
'val is not a non-empty string or a valid number. val=' +
JSON.stringify(val)
);
};
/**
* Parse the given `str` and return milliseconds.
*
* @param {String} str
* @return {Number}
* @api private
*/
function parse(str) {
str = String(str);
if (str.length > 100) {
return;
}
var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(
str
);
if (!match) {
return;
}
var n = parseFloat(match[1]);
var type = (match[2] || 'ms').toLowerCase();
switch (type) {
case 'years':
case 'year':
case 'yrs':
case 'yr':
case 'y':
return n * y;
case 'days':
case 'day':
case 'd':
return n * d;
case 'hours':
case 'hour':
case 'hrs':
case 'hr':
case 'h':
return n * h;
case 'minutes':
case 'minute':
case 'mins':
case 'min':
case 'm':
return n * m;
case 'seconds':
case 'second':
case 'secs':
case 'sec':
case 's':
return n * s;
case 'milliseconds':
case 'millisecond':
case 'msecs':
case 'msec':
case 'ms':
return n;
default:
return undefined;
}
}
/**
* Short format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtShort(ms) {
if (ms >= d) {
return Math.round(ms / d) + 'd';
}
if (ms >= h) {
return Math.round(ms / h) + 'h';
}
if (ms >= m) {
return Math.round(ms / m) + 'm';
}
if (ms >= s) {
return Math.round(ms / s) + 's';
}
return ms + 'ms';
}
/**
* Long format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtLong(ms) {
return plural(ms, d, 'day') ||
plural(ms, h, 'hour') ||
plural(ms, m, 'minute') ||
plural(ms, s, 'second') ||
ms + ' ms';
}
/**
* Pluralization helper.
*/
function plural(ms, n, name) {
if (ms < n) {
return;
}
if (ms < n * 1.5) {
return Math.floor(ms / n) + ' ' + name;
}
return Math.ceil(ms / n) + ' ' + name + 's';
}
},{}],490:[function(require,module,exports){
(function (process){(function (){
'use strict';
if (typeof process === 'undefined' ||
!process.version ||
process.version.indexOf('v0.') === 0 ||
process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
module.exports = { nextTick: nextTick };
} else {
module.exports = process
}
function nextTick(fn, arg1, arg2, arg3) {
if (typeof fn !== 'function') {
throw new TypeError('"callback" argument must be a function');
}
var len = arguments.length;
var args, i;
switch (len) {
case 0:
case 1:
return process.nextTick(fn);
case 2:
return process.nextTick(function afterTickOne() {
fn.call(null, arg1);
});
case 3:
return process.nextTick(function afterTickTwo() {
fn.call(null, arg1, arg2);
});
case 4:
return process.nextTick(function afterTickThree() {
fn.call(null, arg1, arg2, arg3);
});
default:
args = new Array(len - 1);
i = 0;
while (i < args.length) {
args[i++] = arguments[i];
}
return process.nextTick(function afterTick() {
fn.apply(null, args);
});
}
}
}).call(this)}).call(this,require('_process'))
},{"_process":491}],491:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
function defaultSetTimout() {
throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
throw new Error('clearTimeout has not been defined');
}
(function () {
try {
if (typeof setTimeout === 'function') {
cachedSetTimeout = setTimeout;
} else {
cachedSetTimeout = defaultSetTimout;
}
} catch (e) {
cachedSetTimeout = defaultSetTimout;
}
try {
if (typeof clearTimeout === 'function') {
cachedClearTimeout = clearTimeout;
} else {
cachedClearTimeout = defaultClearTimeout;
}
} catch (e) {
cachedClearTimeout = defaultClearTimeout;
}
} ())
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
}
// if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch(e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch(e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
}
// if clearTimeout wasn't available but was latter defined
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
runTimeout(drainQueue);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.prependListener = noop;
process.prependOnceListener = noop;
process.listeners = function (name) { return [] }
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
},{}],492:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
// a duplex stream is just a stream that is both readable and writable.
// Since JS doesn't have multiple prototypal inheritance, this class
// prototypally inherits from Readable, and then parasitically from
// Writable.
'use strict';
/*<replacement>*/
var pna = require('process-nextick-args');
/*</replacement>*/
/*<replacement>*/
var objectKeys = Object.keys || function (obj) {
var keys = [];
for (var key in obj) {
keys.push(key);
}return keys;
};
/*</replacement>*/
module.exports = Duplex;
/*<replacement>*/
var util = Object.create(require('core-util-is'));
util.inherits = require('inherits');
/*</replacement>*/
var Readable = require('./_stream_readable');
var Writable = require('./_stream_writable');
util.inherits(Duplex, Readable);
{
// avoid scope creep, the keys array can then be collected
var keys = objectKeys(Writable.prototype);
for (var v = 0; v < keys.length; v++) {
var method = keys[v];
if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
}
}
function Duplex(options) {
if (!(this instanceof Duplex)) return new Duplex(options);
Readable.call(this, options);
Writable.call(this, options);
if (options && options.readable === false) this.readable = false;
if (options && options.writable === false) this.writable = false;
this.allowHalfOpen = true;
if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
this.once('end', onend);
}
Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
// making it explicit this property is not enumerable
// because otherwise some prototype manipulation in
// userland will fail
enumerable: false,
get: function () {
return this._writableState.highWaterMark;
}
});
// the no-half-open enforcer
function onend() {
// if we allow half-open state, or if the writable side ended,
// then we're ok.
if (this.allowHalfOpen || this._writableState.ended) return;
// no more data can be written.
// But allow more writes to happen in this tick.
pna.nextTick(onEndNT, this);
}
function onEndNT(self) {
self.end();
}
Object.defineProperty(Duplex.prototype, 'destroyed', {
get: function () {
if (this._readableState === undefined || this._writableState === undefined) {
return false;
}
return this._readableState.destroyed && this._writableState.destroyed;
},
set: function (value) {
// we ignore the value if the stream
// has not been initialized yet
if (this._readableState === undefined || this._writableState === undefined) {
return;
}
// backward compatibility, the user is explicitly
// managing destroyed
this._readableState.destroyed = value;
this._writableState.destroyed = value;
}
});
Duplex.prototype._destroy = function (err, cb) {
this.push(null);
this.end();
pna.nextTick(cb, err);
};
},{"./_stream_readable":494,"./_stream_writable":496,"core-util-is":482,"inherits":486,"process-nextick-args":490}],493:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
// a passthrough stream.
// basically just the most minimal sort of Transform stream.
// Every written chunk gets output as-is.
'use strict';
module.exports = PassThrough;
var Transform = require('./_stream_transform');
/*<replacement>*/
var util = Object.create(require('core-util-is'));
util.inherits = require('inherits');
/*</replacement>*/
util.inherits(PassThrough, Transform);
function PassThrough(options) {
if (!(this instanceof PassThrough)) return new PassThrough(options);
Transform.call(this, options);
}
PassThrough.prototype._transform = function (chunk, encoding, cb) {
cb(null, chunk);
};
},{"./_stream_transform":495,"core-util-is":482,"inherits":486}],494:[function(require,module,exports){
(function (process,global){(function (){
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
'use strict';
/*<replacement>*/
var pna = require('process-nextick-args');
/*</replacement>*/
module.exports = Readable;
/*<replacement>*/
var isArray = require('isarray');
/*</replacement>*/
/*<replacement>*/
var Duplex;
/*</replacement>*/
Readable.ReadableState = ReadableState;
/*<replacement>*/
var EE = require('events').EventEmitter;
var EElistenerCount = function (emitter, type) {
return emitter.listeners(type).length;
};
/*</replacement>*/
/*<replacement>*/
var Stream = require('./internal/streams/stream');
/*</replacement>*/
/*<replacement>*/
var Buffer = require('safe-buffer').Buffer;
var OurUint8Array = global.Uint8Array || function () {};
function _uint8ArrayToBuffer(chunk) {
return Buffer.from(chunk);
}
function _isUint8Array(obj) {
return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
}
/*</replacement>*/
/*<replacement>*/
var util = Object.create(require('core-util-is'));
util.inherits = require('inherits');
/*</replacement>*/
/*<replacement>*/
var debugUtil = require('util');
var debug = void 0;
if (debugUtil && debugUtil.debuglog) {
debug = debugUtil.debuglog('stream');
} else {
debug = function () {};
}
/*</replacement>*/
var BufferList = require('./internal/streams/BufferList');
var destroyImpl = require('./internal/streams/destroy');
var StringDecoder;
util.inherits(Readable, Stream);
var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
function prependListener(emitter, event, fn) {
// Sadly this is not cacheable as some libraries bundle their own
// event emitter implementation with them.
if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);
// This is a hack to make sure that our error handler is attached before any
// userland ones. NEVER DO THIS. This is here only because this code needs
// to continue to work with older versions of Node.js that do not include
// the prependListener() method. The goal is to eventually remove this hack.
if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
}
function ReadableState(options, stream) {
Duplex = Duplex || require('./_stream_duplex');
options = options || {};
// Duplex streams are both readable and writable, but share
// the same options object.
// However, some cases require setting options to different
// values for the readable and the writable sides of the duplex stream.
// These options can be provided separately as readableXXX and writableXXX.
var isDuplex = stream instanceof Duplex;
// object stream flag. Used to make read(n) ignore n and to
// make all the buffer merging and length checks go away
this.objectMode = !!options.objectMode;
if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
// the point at which it stops calling _read() to fill the buffer
// Note: 0 is a valid value, means "don't call _read preemptively ever"
var hwm = options.highWaterMark;
var readableHwm = options.readableHighWaterMark;
var defaultHwm = this.objectMode ? 16 : 16 * 1024;
if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm;
// cast to ints.
this.highWaterMark = Math.floor(this.highWaterMark);
// A linked list is used to store data chunks instead of an array because the
// linked list can remove elements from the beginning faster than
// array.shift()
this.buffer = new BufferList();
this.length = 0;
this.pipes = null;
this.pipesCount = 0;
this.flowing = null;
this.ended = false;
this.endEmitted = false;
this.reading = false;
// a flag to be able to tell if the event 'readable'/'data' is emitted
// immediately, or on a later tick. We set this to true at first, because
// any actions that shouldn't happen until "later" should generally also
// not happen before the first read call.
this.sync = true;
// whenever we return null, then we set a flag to say
// that we're awaiting a 'readable' event emission.
this.needReadable = false;
this.emittedReadable = false;
this.readableListening = false;
this.resumeScheduled = false;
// has it been destroyed
this.destroyed = false;
// Crypto is kind of old and crusty. Historically, its default string
// encoding is 'binary' so we have to make this configurable.
// Everything else in the universe uses 'utf8', though.
this.defaultEncoding = options.defaultEncoding || 'utf8';
// the number of writers that are awaiting a drain event in .pipe()s
this.awaitDrain = 0;
// if true, a maybeReadMore has been scheduled
this.readingMore = false;
this.decoder = null;
this.encoding = null;
if (options.encoding) {
if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
this.decoder = new StringDecoder(options.encoding);
this.encoding = options.encoding;
}
}
function Readable(options) {
Duplex = Duplex || require('./_stream_duplex');
if (!(this instanceof Readable)) return new Readable(options);
this._readableState = new ReadableState(options, this);
// legacy
this.readable = true;
if (options) {
if (typeof options.read === 'function') this._read = options.read;
if (typeof options.destroy === 'function') this._destroy = options.destroy;
}
Stream.call(this);
}
Object.defineProperty(Readable.prototype, 'destroyed', {
get: function () {
if (this._readableState === undefined) {
return false;
}
return this._readableState.destroyed;
},
set: function (value) {
// we ignore the value if the stream
// has not been initialized yet
if (!this._readableState) {
return;
}
// backward compatibility, the user is explicitly
// managing destroyed
this._readableState.destroyed = value;
}
});
Readable.prototype.destroy = destroyImpl.destroy;
Readable.prototype._undestroy = destroyImpl.undestroy;
Readable.prototype._destroy = function (err, cb) {
this.push(null);
cb(err);
};
// Manually shove something into the read() buffer.
// This returns true if the highWaterMark has not been hit yet,
// similar to how Writable.write() returns true if you should
// write() some more.
Readable.prototype.push = function (chunk, encoding) {
var state = this._readableState;
var skipChunkCheck;
if (!state.objectMode) {
if (typeof chunk === 'string') {
encoding = encoding || state.defaultEncoding;
if (encoding !== state.encoding) {
chunk = Buffer.from(chunk, encoding);
encoding = '';
}
skipChunkCheck = true;
}
} else {
skipChunkCheck = true;
}
return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
};
// Unshift should *always* be something directly out of read()
Readable.prototype.unshift = function (chunk) {
return readableAddChunk(this, chunk, null, true, false);
};
function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
var state = stream._readableState;
if (chunk === null) {
state.reading = false;
onEofChunk(stream, state);
} else {
var er;
if (!skipChunkCheck) er = chunkInvalid(state, chunk);
if (er) {
stream.emit('error', er);
} else if (state.objectMode || chunk && chunk.length > 0) {
if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
chunk = _uint8ArrayToBuffer(chunk);
}
if (addToFront) {
if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);
} else if (state.ended) {
stream.emit('error', new Error('stream.push() after EOF'));
} else {
state.reading = false;
if (state.decoder && !encoding) {
chunk = state.decoder.write(chunk);
if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
} else {
addChunk(stream, state, chunk, false);
}
}
} else if (!addToFront) {
state.reading = false;
}
}
return needMoreData(state);
}
function addChunk(stream, state, chunk, addToFront) {
if (state.flowing && state.length === 0 && !state.sync) {
stream.emit('data', chunk);
stream.read(0);
} else {
// update the buffer info.
state.length += state.objectMode ? 1 : chunk.length;
if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
if (state.needReadable) emitReadable(stream);
}
maybeReadMore(stream, state);
}
function chunkInvalid(state, chunk) {
var er;
if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
er = new TypeError('Invalid non-string/buffer chunk');
}
return er;
}
// if it's past the high water mark, we can push in some more.
// Also, if we have no data yet, we can stand some
// more bytes. This is to work around cases where hwm=0,
// such as the repl. Also, if the push() triggered a
// readable event, and the user called read(largeNumber) such that
// needReadable was set, then we ought to push more, so that another
// 'readable' event will be triggered.
function needMoreData(state) {
return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
}
Readable.prototype.isPaused = function () {
return this._readableState.flowing === false;
};
// backwards compatibility.
Readable.prototype.setEncoding = function (enc) {
if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
this._readableState.decoder = new StringDecoder(enc);
this._readableState.encoding = enc;
return this;
};
// Don't raise the hwm > 8MB
var MAX_HWM = 0x800000;
function computeNewHighWaterMark(n) {
if (n >= MAX_HWM) {
n = MAX_HWM;
} else {
// Get the next highest power of 2 to prevent increasing hwm excessively in
// tiny amounts
n--;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
n++;
}
return n;
}
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function howMuchToRead(n, state) {
if (n <= 0 || state.length === 0 && state.ended) return 0;
if (state.objectMode) return 1;
if (n !== n) {
// Only flow one buffer at a time
if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
}
// If we're asking for more than the current hwm, then raise the hwm.
if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
if (n <= state.length) return n;
// Don't have enough
if (!state.ended) {
state.needReadable = true;
return 0;
}
return state.length;
}
// you can override either this method, or the async _read(n) below.
Readable.prototype.read = function (n) {
debug('read', n);
n = parseInt(n, 10);
var state = this._readableState;
var nOrig = n;
if (n !== 0) state.emittedReadable = false;
// if we're doing read(0) to trigger a readable event, but we
// already have a bunch of data in the buffer, then just trigger
// the 'readable' event and move on.
if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
debug('read: emitReadable', state.length, state.ended);
if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
return null;
}
n = howMuchToRead(n, state);
// if we've ended, and we're now clear, then finish it up.
if (n === 0 && state.ended) {
if (state.length === 0) endReadable(this);
return null;
}
// All the actual chunk generation logic needs to be
// *below* the call to _read. The reason is that in certain
// synthetic stream cases, such as passthrough streams, _read
// may be a completely synchronous operation which may change
// the state of the read buffer, providing enough data when
// before there was *not* enough.
//
// So, the steps are:
// 1. Figure out what the state of things will be after we do
// a read from the buffer.
//
// 2. If that resulting state will trigger a _read, then call _read.
// Note that this may be asynchronous, or synchronous. Yes, it is
// deeply ugly to write APIs this way, but that still doesn't mean
// that the Readable class should behave improperly, as streams are
// designed to be sync/async agnostic.
// Take note if the _read call is sync or async (ie, if the read call
// has returned yet), so that we know whether or not it's safe to emit
// 'readable' etc.
//
// 3. Actually pull the requested chunks out of the buffer and return.
// if we need a readable event, then we need to do some reading.
var doRead = state.needReadable;
debug('need readable', doRead);
// if we currently have less than the highWaterMark, then also read some
if (state.length === 0 || state.length - n < state.highWaterMark) {
doRead = true;
debug('length less than watermark', doRead);
}
// however, if we've ended, then there's no point, and if we're already
// reading, then it's unnecessary.
if (state.ended || state.reading) {
doRead = false;
debug('reading or ended', doRead);
} else if (doRead) {
debug('do read');
state.reading = true;
state.sync = true;
// if the length is currently zero, then we *need* a readable event.
if (state.length === 0) state.needReadable = true;
// call internal read method
this._read(state.highWaterMark);
state.sync = false;
// If _read pushed data synchronously, then `reading` will be false,
// and we need to re-evaluate how much data we can return to the user.
if (!state.reading) n = howMuchToRead(nOrig, state);
}
var ret;
if (n > 0) ret = fromList(n, state);else ret = null;
if (ret === null) {
state.needReadable = true;
n = 0;
} else {
state.length -= n;
}
if (state.length === 0) {
// If we have nothing in the buffer, then we want to know
// as soon as we *do* get something into the buffer.
if (!state.ended) state.needReadable = true;
// If we tried to read() past the EOF, then emit end on the next tick.
if (nOrig !== n && state.ended) endReadable(this);
}
if (ret !== null) this.emit('data', ret);
return ret;
};
function onEofChunk(stream, state) {
if (state.ended) return;
if (state.decoder) {
var chunk = state.decoder.end();
if (chunk && chunk.length) {
state.buffer.push(chunk);
state.length += state.objectMode ? 1 : chunk.length;
}
}
state.ended = true;
// emit 'readable' now to make sure it gets picked up.
emitReadable(stream);
}
// Don't emit readable right away in sync mode, because this can trigger
// another read() call => stack overflow. This way, it might trigger
// a nextTick recursion warning, but that's not so bad.
function emitReadable(stream) {
var state = stream._readableState;
state.needReadable = false;
if (!state.emittedReadable) {
debug('emitReadable', state.flowing);
state.emittedReadable = true;
if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream);
}
}
function emitReadable_(stream) {
debug('emit readable');
stream.emit('readable');
flow(stream);
}
// at this point, the user has presumably seen the 'readable' event,
// and called read() to consume some data. that may have triggered
// in turn another _read(n) call, in which case reading = true if
// it's in progress.
// However, if we're not ended, or reading, and the length < hwm,
// then go ahead and try to read some more preemptively.
function maybeReadMore(stream, state) {
if (!state.readingMore) {
state.readingMore = true;
pna.nextTick(maybeReadMore_, stream, state);
}
}
function maybeReadMore_(stream, state) {
var len = state.length;
while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
debug('maybeReadMore read 0');
stream.read(0);
if (len === state.length)
// didn't get any data, stop spinning.
break;else len = state.length;
}
state.readingMore = false;
}
// abstract method. to be overridden in specific implementation classes.
// call cb(er, data) where data is <= n in length.
// for virtual (non-string, non-buffer) streams, "length" is somewhat
// arbitrary, and perhaps not very meaningful.
Readable.prototype._read = function (n) {
this.emit('error', new Error('_read() is not implemented'));
};
Readable.prototype.pipe = function (dest, pipeOpts) {
var src = this;
var state = this._readableState;
switch (state.pipesCount) {
case 0:
state.pipes = dest;
break;
case 1:
state.pipes = [state.pipes, dest];
break;
default:
state.pipes.push(dest);
break;
}
state.pipesCount += 1;
debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
var endFn = doEnd ? onend : unpipe;
if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn);
dest.on('unpipe', onunpipe);
function onunpipe(readable, unpipeInfo) {
debug('onunpipe');
if (readable === src) {
if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
unpipeInfo.hasUnpiped = true;
cleanup();
}
}
}
function onend() {
debug('onend');
dest.end();
}
// when the dest drains, it reduces the awaitDrain counter
// on the source. This would be more elegant with a .once()
// handler in flow(), but adding and removing repeatedly is
// too slow.
var ondrain = pipeOnDrain(src);
dest.on('drain', ondrain);
var cleanedUp = false;
function cleanup() {
debug('cleanup');
// cleanup event handlers once the pipe is broken
dest.removeListener('close', onclose);
dest.removeListener('finish', onfinish);
dest.removeListener('drain', ondrain);
dest.removeListener('error', onerror);
dest.removeListener('unpipe', onunpipe);
src.removeListener('end', onend);
src.removeListener('end', unpipe);
src.removeListener('data', ondata);
cleanedUp = true;
// if the reader is waiting for a drain event from this
// specific writer, then it would cause it to never start
// flowing again.
// So, if this is awaiting a drain, then we just call it now.
// If we don't know, then assume that we are waiting for one.
if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
}
// If the user pushes more data while we're writing to dest then we'll end up
// in ondata again. However, we only want to increase awaitDrain once because
// dest will only emit one 'drain' event for the multiple writes.
// => Introduce a guard on increasing awaitDrain.
var increasedAwaitDrain = false;
src.on('data', ondata);
function ondata(chunk) {
debug('ondata');
increasedAwaitDrain = false;
var ret = dest.write(chunk);
if (false === ret && !increasedAwaitDrain) {
// If the user unpiped during `dest.write()`, it is possible
// to get stuck in a permanently paused state if that write
// also returned false.
// => Check whether `dest` is still a piping destination.
if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
debug('false write response, pause', src._readableState.awaitDrain);
src._readableState.awaitDrain++;
increasedAwaitDrain = true;
}
src.pause();
}
}
// if the dest has an error, then stop piping into it.
// however, don't suppress the throwing behavior for this.
function onerror(er) {
debug('onerror', er);
unpipe();
dest.removeListener('error', onerror);
if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
}
// Make sure our error handler is attached before userland ones.
prependListener(dest, 'error', onerror);
// Both close and finish should trigger unpipe, but only once.
function onclose() {
dest.removeListener('finish', onfinish);
unpipe();
}
dest.once('close', onclose);
function onfinish() {
debug('onfinish');
dest.removeListener('close', onclose);
unpipe();
}
dest.once('finish', onfinish);
function unpipe() {
debug('unpipe');
src.unpipe(dest);
}
// tell the dest that it's being piped to
dest.emit('pipe', src);
// start the flow if it hasn't been started already.
if (!state.flowing) {
debug('pipe resume');
src.resume();
}
return dest;
};
function pipeOnDrain(src) {
return function () {
var state = src._readableState;
debug('pipeOnDrain', state.awaitDrain);
if (state.awaitDrain) state.awaitDrain--;
if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
state.flowing = true;
flow(src);
}
};
}
Readable.prototype.unpipe = function (dest) {
var state = this._readableState;
var unpipeInfo = { hasUnpiped: false };
// if we're not piping anywhere, then do nothing.
if (state.pipesCount === 0) return this;
// just one destination. most common case.
if (state.pipesCount === 1) {
// passed in one, but it's not the right one.
if (dest && dest !== state.pipes) return this;
if (!dest) dest = state.pipes;
// got a match.
state.pipes = null;
state.pipesCount = 0;
state.flowing = false;
if (dest) dest.emit('unpipe', this, unpipeInfo);
return this;
}
// slow case. multiple pipe destinations.
if (!dest) {
// remove all.
var dests = state.pipes;
var len = state.pipesCount;
state.pipes = null;
state.pipesCount = 0;
state.flowing = false;
for (var i = 0; i < len; i++) {
dests[i].emit('unpipe', this, unpipeInfo);
}return this;
}
// try to find the right one.
var index = indexOf(state.pipes, dest);
if (index === -1) return this;
state.pipes.splice(index, 1);
state.pipesCount -= 1;
if (state.pipesCount === 1) state.pipes = state.pipes[0];
dest.emit('unpipe', this, unpipeInfo);
return this;
};
// set up data events if they are asked for
// Ensure readable listeners eventually get something
Readable.prototype.on = function (ev, fn) {
var res = Stream.prototype.on.call(this, ev, fn);
if (ev === 'data') {
// Start flowing on next tick if stream isn't explicitly paused
if (this._readableState.flowing !== false) this.resume();
} else if (ev === 'readable') {
var state = this._readableState;
if (!state.endEmitted && !state.readableListening) {
state.readableListening = state.needReadable = true;
state.emittedReadable = false;
if (!state.reading) {
pna.nextTick(nReadingNextTick, this);
} else if (state.length) {
emitReadable(this);
}
}
}
return res;
};
Readable.prototype.addListener = Readable.prototype.on;
function nReadingNextTick(self) {
debug('readable nexttick read 0');
self.read(0);
}
// pause() and resume() are remnants of the legacy readable stream API
// If the user uses them, then switch into old mode.
Readable.prototype.resume = function () {
var state = this._readableState;
if (!state.flowing) {
debug('resume');
state.flowing = true;
resume(this, state);
}
return this;
};
function resume(stream, state) {
if (!state.resumeScheduled) {
state.resumeScheduled = true;
pna.nextTick(resume_, stream, state);
}
}
function resume_(stream, state) {
if (!state.reading) {
debug('resume read 0');
stream.read(0);
}
state.resumeScheduled = false;
state.awaitDrain = 0;
stream.emit('resume');
flow(stream);
if (state.flowing && !state.reading) stream.read(0);
}
Readable.prototype.pause = function () {
debug('call pause flowing=%j', this._readableState.flowing);
if (false !== this._readableState.flowing) {
debug('pause');
this._readableState.flowing = false;
this.emit('pause');
}
return this;
};
function flow(stream) {
var state = stream._readableState;
debug('flow', state.flowing);
while (state.flowing && stream.read() !== null) {}
}
// wrap an old-style stream as the async data source.
// This is *not* part of the readable stream interface.
// It is an ugly unfortunate mess of history.
Readable.prototype.wrap = function (stream) {
var _this = this;
var state = this._readableState;
var paused = false;
stream.on('end', function () {
debug('wrapped end');
if (state.decoder && !state.ended) {
var chunk = state.decoder.end();
if (chunk && chunk.length) _this.push(chunk);
}
_this.push(null);
});
stream.on('data', function (chunk) {
debug('wrapped data');
if (state.decoder) chunk = state.decoder.write(chunk);
// don't skip over falsy values in objectMode
if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
var ret = _this.push(chunk);
if (!ret) {
paused = true;
stream.pause();
}
});
// proxy all the other methods.
// important when wrapping filters and duplexes.
for (var i in stream) {
if (this[i] === undefined && typeof stream[i] === 'function') {
this[i] = function (method) {
return function () {
return stream[method].apply(stream, arguments);
};
}(i);
}
}
// proxy certain important events.
for (var n = 0; n < kProxyEvents.length; n++) {
stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
}
// when we try to consume some more bytes, simply unpause the
// underlying stream.
this._read = function (n) {
debug('wrapped _read', n);
if (paused) {
paused = false;
stream.resume();
}
};
return this;
};
Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
// making it explicit this property is not enumerable
// because otherwise some prototype manipulation in
// userland will fail
enumerable: false,
get: function () {
return this._readableState.highWaterMark;
}
});
// exposed for testing purposes only.
Readable._fromList = fromList;
// Pluck off n bytes from an array of buffers.
// Length is the combined lengths of all the buffers in the list.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function fromList(n, state) {
// nothing buffered
if (state.length === 0) return null;
var ret;
if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
// read it all, truncate the list
if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length);
state.buffer.clear();
} else {
// read part of list
ret = fromListPartial(n, state.buffer, state.decoder);
}
return ret;
}
// Extracts only enough buffered data to satisfy the amount requested.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function fromListPartial(n, list, hasStrings) {
var ret;
if (n < list.head.data.length) {
// slice is the same for buffers and strings
ret = list.head.data.slice(0, n);
list.head.data = list.head.data.slice(n);
} else if (n === list.head.data.length) {
// first chunk is a perfect match
ret = list.shift();
} else {
// result spans more than one buffer
ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
}
return ret;
}
// Copies a specified amount of characters from the list of buffered data
// chunks.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function copyFromBufferString(n, list) {
var p = list.head;
var c = 1;
var ret = p.data;
n -= ret.length;
while (p = p.next) {
var str = p.data;
var nb = n > str.length ? str.length : n;
if (nb === str.length) ret += str;else ret += str.slice(0, n);
n -= nb;
if (n === 0) {
if (nb === str.length) {
++c;
if (p.next) list.head = p.next;else list.head = list.tail = null;
} else {
list.head = p;
p.data = str.slice(nb);
}
break;
}
++c;
}
list.length -= c;
return ret;
}
// Copies a specified amount of bytes from the list of buffered data chunks.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function copyFromBuffer(n, list) {
var ret = Buffer.allocUnsafe(n);
var p = list.head;
var c = 1;
p.data.copy(ret);
n -= p.data.length;
while (p = p.next) {
var buf = p.data;
var nb = n > buf.length ? buf.length : n;
buf.copy(ret, ret.length - n, 0, nb);
n -= nb;
if (n === 0) {
if (nb === buf.length) {
++c;
if (p.next) list.head = p.next;else list.head = list.tail = null;
} else {
list.head = p;
p.data = buf.slice(nb);
}
break;
}
++c;
}
list.length -= c;
return ret;
}
function endReadable(stream) {
var state = stream._readableState;
// If we get here before consuming all the bytes, then that is a
// bug in node. Should never happen.
if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
if (!state.endEmitted) {
state.ended = true;
pna.nextTick(endReadableNT, state, stream);
}
}
function endReadableNT(state, stream) {
// Check that we didn't get one last unshift.
if (!state.endEmitted && state.length === 0) {
state.endEmitted = true;
stream.readable = false;
stream.emit('end');
}
}
function indexOf(xs, x) {
for (var i = 0, l = xs.length; i < l; i++) {
if (xs[i] === x) return i;
}
return -1;
}
}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./_stream_duplex":492,"./internal/streams/BufferList":497,"./internal/streams/destroy":498,"./internal/streams/stream":499,"_process":491,"core-util-is":482,"events":479,"inherits":486,"isarray":488,"process-nextick-args":490,"safe-buffer":501,"string_decoder/":502,"util":478}],495:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
// a transform stream is a readable/writable stream where you do
// something with the data. Sometimes it's called a "filter",
// but that's not a great name for it, since that implies a thing where
// some bits pass through, and others are simply ignored. (That would
// be a valid example of a transform, of course.)
//
// While the output is causally related to the input, it's not a
// necessarily symmetric or synchronous transformation. For example,
// a zlib stream might take multiple plain-text writes(), and then
// emit a single compressed chunk some time in the future.
//
// Here's how this works:
//
// The Transform stream has all the aspects of the readable and writable
// stream classes. When you write(chunk), that calls _write(chunk,cb)
// internally, and returns false if there's a lot of pending writes
// buffered up. When you call read(), that calls _read(n) until
// there's enough pending readable data buffered up.
//
// In a transform stream, the written data is placed in a buffer. When
// _read(n) is called, it transforms the queued up data, calling the
// buffered _write cb's as it consumes chunks. If consuming a single
// written chunk would result in multiple output chunks, then the first
// outputted bit calls the readcb, and subsequent chunks just go into
// the read buffer, and will cause it to emit 'readable' if necessary.
//
// This way, back-pressure is actually determined by the reading side,
// since _read has to be called to start processing a new chunk. However,
// a pathological inflate type of transform can cause excessive buffering
// here. For example, imagine a stream where every byte of input is
// interpreted as an integer from 0-255, and then results in that many
// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
// 1kb of data being output. In this case, you could write a very small
// amount of input, and end up with a very large amount of output. In
// such a pathological inflating mechanism, there'd be no way to tell
// the system to stop doing the transform. A single 4MB write could
// cause the system to run out of memory.
//
// However, even in such a pathological case, only a single written chunk
// would be consumed, and then the rest would wait (un-transformed) until
// the results of the previous transformed chunk were consumed.
'use strict';
module.exports = Transform;
var Duplex = require('./_stream_duplex');
/*<replacement>*/
var util = Object.create(require('core-util-is'));
util.inherits = require('inherits');
/*</replacement>*/
util.inherits(Transform, Duplex);
function afterTransform(er, data) {
var ts = this._transformState;
ts.transforming = false;
var cb = ts.writecb;
if (!cb) {
return this.emit('error', new Error('write callback called multiple times'));
}
ts.writechunk = null;
ts.writecb = null;
if (data != null) // single equals check for both `null` and `undefined`
this.push(data);
cb(er);
var rs = this._readableState;
rs.reading = false;
if (rs.needReadable || rs.length < rs.highWaterMark) {
this._read(rs.highWaterMark);
}
}
function Transform(options) {
if (!(this instanceof Transform)) return new Transform(options);
Duplex.call(this, options);
this._transformState = {
afterTransform: afterTransform.bind(this),
needTransform: false,
transforming: false,
writecb: null,
writechunk: null,
writeencoding: null
};
// start out asking for a readable event once data is transformed.
this._readableState.needReadable = true;
// we have implemented the _read method, and done the other things
// that Readable wants before the first _read call, so unset the
// sync guard flag.
this._readableState.sync = false;
if (options) {
if (typeof options.transform === 'function') this._transform = options.transform;
if (typeof options.flush === 'function') this._flush = options.flush;
}
// When the writable side finishes, then flush out anything remaining.
this.on('prefinish', prefinish);
}
function prefinish() {
var _this = this;
if (typeof this._flush === 'function') {
this._flush(function (er, data) {
done(_this, er, data);
});
} else {
done(this, null, null);
}
}
Transform.prototype.push = function (chunk, encoding) {
this._transformState.needTransform = false;
return Duplex.prototype.push.call(this, chunk, encoding);
};
// This is the part where you do stuff!
// override this function in implementation classes.
// 'chunk' is an input chunk.
//
// Call `push(newChunk)` to pass along transformed output
// to the readable side. You may call 'push' zero or more times.
//
// Call `cb(err)` when you are done with this chunk. If you pass
// an error, then that'll put the hurt on the whole operation. If you
// never call cb(), then you'll never get another chunk.
Transform.prototype._transform = function (chunk, encoding, cb) {
throw new Error('_transform() is not implemented');
};
Transform.prototype._write = function (chunk, encoding, cb) {
var ts = this._transformState;
ts.writecb = cb;
ts.writechunk = chunk;
ts.writeencoding = encoding;
if (!ts.transforming) {
var rs = this._readableState;
if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
}
};
// Doesn't matter what the args are here.
// _transform does all the work.
// That we got here means that the readable side wants more data.
Transform.prototype._read = function (n) {
var ts = this._transformState;
if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
ts.transforming = true;
this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
} else {
// mark that we need a transform, so that any data that comes in
// will get processed, now that we've asked for it.
ts.needTransform = true;
}
};
Transform.prototype._destroy = function (err, cb) {
var _this2 = this;
Duplex.prototype._destroy.call(this, err, function (err2) {
cb(err2);
_this2.emit('close');
});
};
function done(stream, er, data) {
if (er) return stream.emit('error', er);
if (data != null) // single equals check for both `null` and `undefined`
stream.push(data);
// if there's nothing in the write buffer, then that means
// that nothing more will ever be provided
if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0');
if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming');
return stream.push(null);
}
},{"./_stream_duplex":492,"core-util-is":482,"inherits":486}],496:[function(require,module,exports){
(function (process,global,setImmediate){(function (){
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
// A bit simpler than readable streams.
// Implement an async ._write(chunk, encoding, cb), and it'll handle all
// the drain event emission and buffering.
'use strict';
/*<replacement>*/
var pna = require('process-nextick-args');
/*</replacement>*/
module.exports = Writable;
/* <replacement> */
function WriteReq(chunk, encoding, cb) {
this.chunk = chunk;
this.encoding = encoding;
this.callback = cb;
this.next = null;
}
// It seems a linked list but it is not
// there will be only 2 of these for each stream
function CorkedRequest(state) {
var _this = this;
this.next = null;
this.entry = null;
this.finish = function () {
onCorkedFinish(_this, state);
};
}
/* </replacement> */
/*<replacement>*/
var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick;
/*</replacement>*/
/*<replacement>*/
var Duplex;
/*</replacement>*/
Writable.WritableState = WritableState;
/*<replacement>*/
var util = Object.create(require('core-util-is'));
util.inherits = require('inherits');
/*</replacement>*/
/*<replacement>*/
var internalUtil = {
deprecate: require('util-deprecate')
};
/*</replacement>*/
/*<replacement>*/
var Stream = require('./internal/streams/stream');
/*</replacement>*/
/*<replacement>*/
var Buffer = require('safe-buffer').Buffer;
var OurUint8Array = global.Uint8Array || function () {};
function _uint8ArrayToBuffer(chunk) {
return Buffer.from(chunk);
}
function _isUint8Array(obj) {
return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
}
/*</replacement>*/
var destroyImpl = require('./internal/streams/destroy');
util.inherits(Writable, Stream);
function nop() {}
function WritableState(options, stream) {
Duplex = Duplex || require('./_stream_duplex');
options = options || {};
// Duplex streams are both readable and writable, but share
// the same options object.
// However, some cases require setting options to different
// values for the readable and the writable sides of the duplex stream.
// These options can be provided separately as readableXXX and writableXXX.
var isDuplex = stream instanceof Duplex;
// object stream flag to indicate whether or not this stream
// contains buffers or objects.
this.objectMode = !!options.objectMode;
if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
// the point at which write() starts returning false
// Note: 0 is a valid value, means that we always return false if
// the entire buffer is not flushed immediately on write()
var hwm = options.highWaterMark;
var writableHwm = options.writableHighWaterMark;
var defaultHwm = this.objectMode ? 16 : 16 * 1024;
if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm;
// cast to ints.
this.highWaterMark = Math.floor(this.highWaterMark);
// if _final has been called
this.finalCalled = false;
// drain event flag.
this.needDrain = false;
// at the start of calling end()
this.ending = false;
// when end() has been called, and returned
this.ended = false;
// when 'finish' is emitted
this.finished = false;
// has it been destroyed
this.destroyed = false;
// should we decode strings into buffers before passing to _write?
// this is here so that some node-core streams can optimize string
// handling at a lower level.
var noDecode = options.decodeStrings === false;
this.decodeStrings = !noDecode;
// Crypto is kind of old and crusty. Historically, its default string
// encoding is 'binary' so we have to make this configurable.
// Everything else in the universe uses 'utf8', though.
this.defaultEncoding = options.defaultEncoding || 'utf8';
// not an actual buffer we keep track of, but a measurement
// of how much we're waiting to get pushed to some underlying
// socket or file.
this.length = 0;
// a flag to see when we're in the middle of a write.
this.writing = false;
// when true all writes will be buffered until .uncork() call
this.corked = 0;
// a flag to be able to tell if the onwrite cb is called immediately,
// or on a later tick. We set this to true at first, because any
// actions that shouldn't happen until "later" should generally also
// not happen before the first write call.
this.sync = true;
// a flag to know if we're processing previously buffered items, which
// may call the _write() callback in the same tick, so that we don't
// end up in an overlapped onwrite situation.
this.bufferProcessing = false;
// the callback that's passed to _write(chunk,cb)
this.onwrite = function (er) {
onwrite(stream, er);
};
// the callback that the user supplies to write(chunk,encoding,cb)
this.writecb = null;
// the amount that is being written when _write is called.
this.writelen = 0;
this.bufferedRequest = null;
this.lastBufferedRequest = null;
// number of pending user-supplied write callbacks
// this must be 0 before 'finish' can be emitted
this.pendingcb = 0;
// emit prefinish if the only thing we're waiting for is _write cbs
// This is relevant for synchronous Transform streams
this.prefinished = false;
// True if the error was already emitted and should not be thrown again
this.errorEmitted = false;
// count buffered requests
this.bufferedRequestCount = 0;
// allocate the first CorkedRequest, there is always
// one allocated and free to use, and we maintain at most two
this.corkedRequestsFree = new CorkedRequest(this);
}
WritableState.prototype.getBuffer = function getBuffer() {
var current = this.bufferedRequest;
var out = [];
while (current) {
out.push(current);
current = current.next;
}
return out;
};
(function () {
try {
Object.defineProperty(WritableState.prototype, 'buffer', {
get: internalUtil.deprecate(function () {
return this.getBuffer();
}, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
});
} catch (_) {}
})();
// Test _writableState for inheritance to account for Duplex streams,
// whose prototype chain only points to Readable.
var realHasInstance;
if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
realHasInstance = Function.prototype[Symbol.hasInstance];
Object.defineProperty(Writable, Symbol.hasInstance, {
value: function (object) {
if (realHasInstance.call(this, object)) return true;
if (this !== Writable) return false;
return object && object._writableState instanceof WritableState;
}
});
} else {
realHasInstance = function (object) {
return object instanceof this;
};
}
function Writable(options) {
Duplex = Duplex || require('./_stream_duplex');
// Writable ctor is applied to Duplexes, too.
// `realHasInstance` is necessary because using plain `instanceof`
// would return false, as no `_writableState` property is attached.
// Trying to use the custom `instanceof` for Writable here will also break the
// Node.js LazyTransform implementation, which has a non-trivial getter for
// `_writableState` that would lead to infinite recursion.
if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
return new Writable(options);
}
this._writableState = new WritableState(options, this);
// legacy.
this.writable = true;
if (options) {
if (typeof options.write === 'function') this._write = options.write;
if (typeof options.writev === 'function') this._writev = options.writev;
if (typeof options.destroy === 'function') this._destroy = options.destroy;
if (typeof options.final === 'function') this._final = options.final;
}
Stream.call(this);
}
// Otherwise people can pipe Writable streams, which is just wrong.
Writable.prototype.pipe = function () {
this.emit('error', new Error('Cannot pipe, not readable'));
};
function writeAfterEnd(stream, cb) {
var er = new Error('write after end');
// TODO: defer error events consistently everywhere, not just the cb
stream.emit('error', er);
pna.nextTick(cb, er);
}
// Checks that a user-supplied chunk is valid, especially for the particular
// mode the stream is in. Currently this means that `null` is never accepted
// and undefined/non-string values are only allowed in object mode.
function validChunk(stream, state, chunk, cb) {
var valid = true;
var er = false;
if (chunk === null) {
er = new TypeError('May not write null values to stream');
} else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
er = new TypeError('Invalid non-string/buffer chunk');
}
if (er) {
stream.emit('error', er);
pna.nextTick(cb, er);
valid = false;
}
return valid;
}
Writable.prototype.write = function (chunk, encoding, cb) {
var state = this._writableState;
var ret = false;
var isBuf = !state.objectMode && _isUint8Array(chunk);
if (isBuf && !Buffer.isBuffer(chunk)) {
chunk = _uint8ArrayToBuffer(chunk);
}
if (typeof encoding === 'function') {
cb = encoding;
encoding = null;
}
if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
if (typeof cb !== 'function') cb = nop;
if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
state.pendingcb++;
ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
}
return ret;
};
Writable.prototype.cork = function () {
var state = this._writableState;
state.corked++;
};
Writable.prototype.uncork = function () {
var state = this._writableState;
if (state.corked) {
state.corked--;
if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
}
};
Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
// node::ParseEncoding() requires lower case.
if (typeof encoding === 'string') encoding = encoding.toLowerCase();
if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding);
this._writableState.defaultEncoding = encoding;
return this;
};
function decodeChunk(state, chunk, encoding) {
if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
chunk = Buffer.from(chunk, encoding);
}
return chunk;
}
Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
// making it explicit this property is not enumerable
// because otherwise some prototype manipulation in
// userland will fail
enumerable: false,
get: function () {
return this._writableState.highWaterMark;
}
});
// if we're already writing something, then just put this
// in the queue, and wait our turn. Otherwise, call _write
// If we return false, then we need a drain event, so set that flag.
function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
if (!isBuf) {
var newChunk = decodeChunk(state, chunk, encoding);
if (chunk !== newChunk) {
isBuf = true;
encoding = 'buffer';
chunk = newChunk;
}
}
var len = state.objectMode ? 1 : chunk.length;
state.length += len;
var ret = state.length < state.highWaterMark;
// we must ensure that previous needDrain will not be reset to false.
if (!ret) state.needDrain = true;
if (state.writing || state.corked) {
var last = state.lastBufferedRequest;
state.lastBufferedRequest = {
chunk: chunk,
encoding: encoding,
isBuf: isBuf,
callback: cb,
next: null
};
if (last) {
last.next = state.lastBufferedRequest;
} else {
state.bufferedRequest = state.lastBufferedRequest;
}
state.bufferedRequestCount += 1;
} else {
doWrite(stream, state, false, len, chunk, encoding, cb);
}
return ret;
}
function doWrite(stream, state, writev, len, chunk, encoding, cb) {
state.writelen = len;
state.writecb = cb;
state.writing = true;
state.sync = true;
if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
state.sync = false;
}
function onwriteError(stream, state, sync, er, cb) {
--state.pendingcb;
if (sync) {
// defer the callback if we are being called synchronously
// to avoid piling up things on the stack
pna.nextTick(cb, er);
// this can emit finish, and it will always happen
// after error
pna.nextTick(finishMaybe, stream, state);
stream._writableState.errorEmitted = true;
stream.emit('error', er);
} else {
// the caller expect this to happen before if
// it is async
cb(er);
stream._writableState.errorEmitted = true;
stream.emit('error', er);
// this can emit finish, but finish must
// always follow error
finishMaybe(stream, state);
}
}
function onwriteStateUpdate(state) {
state.writing = false;
state.writecb = null;
state.length -= state.writelen;
state.writelen = 0;
}
function onwrite(stream, er) {
var state = stream._writableState;
var sync = state.sync;
var cb = state.writecb;
onwriteStateUpdate(state);
if (er) onwriteError(stream, state, sync, er, cb);else {
// Check if we're actually ready to finish, but don't emit yet
var finished = needFinish(state);
if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
clearBuffer(stream, state);
}
if (sync) {
/*<replacement>*/
asyncWrite(afterWrite, stream, state, finished, cb);
/*</replacement>*/
} else {
afterWrite(stream, state, finished, cb);
}
}
}
function afterWrite(stream, state, finished, cb) {
if (!finished) onwriteDrain(stream, state);
state.pendingcb--;
cb();
finishMaybe(stream, state);
}
// Must force callback to be called on nextTick, so that we don't
// emit 'drain' before the write() consumer gets the 'false' return
// value, and has a chance to attach a 'drain' listener.
function onwriteDrain(stream, state) {
if (state.length === 0 && state.needDrain) {
state.needDrain = false;
stream.emit('drain');
}
}
// if there's something in the buffer waiting, then process it
function clearBuffer(stream, state) {
state.bufferProcessing = true;
var entry = state.bufferedRequest;
if (stream._writev && entry && entry.next) {
// Fast case, write everything using _writev()
var l = state.bufferedRequestCount;
var buffer = new Array(l);
var holder = state.corkedRequestsFree;
holder.entry = entry;
var count = 0;
var allBuffers = true;
while (entry) {
buffer[count] = entry;
if (!entry.isBuf) allBuffers = false;
entry = entry.next;
count += 1;
}
buffer.allBuffers = allBuffers;
doWrite(stream, state, true, state.length, buffer, '', holder.finish);
// doWrite is almost always async, defer these to save a bit of time
// as the hot path ends with doWrite
state.pendingcb++;
state.lastBufferedRequest = null;
if (holder.next) {
state.corkedRequestsFree = holder.next;
holder.next = null;
} else {
state.corkedRequestsFree = new CorkedRequest(state);
}
state.bufferedRequestCount = 0;
} else {
// Slow case, write chunks one-by-one
while (entry) {
var chunk = entry.chunk;
var encoding = entry.encoding;
var cb = entry.callback;
var len = state.objectMode ? 1 : chunk.length;
doWrite(stream, state, false, len, chunk, encoding, cb);
entry = entry.next;
state.bufferedRequestCount--;
// if we didn't call the onwrite immediately, then
// it means that we need to wait until it does.
// also, that means that the chunk and cb are currently
// being processed, so move the buffer counter past them.
if (state.writing) {
break;
}
}
if (entry === null) state.lastBufferedRequest = null;
}
state.bufferedRequest = entry;
state.bufferProcessing = false;
}
Writable.prototype._write = function (chunk, encoding, cb) {
cb(new Error('_write() is not implemented'));
};
Writable.prototype._writev = null;
Writable.prototype.end = function (chunk, encoding, cb) {
var state = this._writableState;
if (typeof chunk === 'function') {
cb = chunk;
chunk = null;
encoding = null;
} else if (typeof encoding === 'function') {
cb = encoding;
encoding = null;
}
if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
// .end() fully uncorks
if (state.corked) {
state.corked = 1;
this.uncork();
}
// ignore unnecessary end() calls.
if (!state.ending && !state.finished) endWritable(this, state, cb);
};
function needFinish(state) {
return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
}
function callFinal(stream, state) {
stream._final(function (err) {
state.pendingcb--;
if (err) {
stream.emit('error', err);
}
state.prefinished = true;
stream.emit('prefinish');
finishMaybe(stream, state);
});
}
function prefinish(stream, state) {
if (!state.prefinished && !state.finalCalled) {
if (typeof stream._final === 'function') {
state.pendingcb++;
state.finalCalled = true;
pna.nextTick(callFinal, stream, state);
} else {
state.prefinished = true;
stream.emit('prefinish');
}
}
}
function finishMaybe(stream, state) {
var need = needFinish(state);
if (need) {
prefinish(stream, state);
if (state.pendingcb === 0) {
state.finished = true;
stream.emit('finish');
}
}
return need;
}
function endWritable(stream, state, cb) {
state.ending = true;
finishMaybe(stream, state);
if (cb) {
if (state.finished) pna.nextTick(cb);else stream.once('finish', cb);
}
state.ended = true;
stream.writable = false;
}
function onCorkedFinish(corkReq, state, err) {
var entry = corkReq.entry;
corkReq.entry = null;
while (entry) {
var cb = entry.callback;
state.pendingcb--;
cb(err);
entry = entry.next;
}
if (state.corkedRequestsFree) {
state.corkedRequestsFree.next = corkReq;
} else {
state.corkedRequestsFree = corkReq;
}
}
Object.defineProperty(Writable.prototype, 'destroyed', {
get: function () {
if (this._writableState === undefined) {
return false;
}
return this._writableState.destroyed;
},
set: function (value) {
// we ignore the value if the stream
// has not been initialized yet
if (!this._writableState) {
return;
}
// backward compatibility, the user is explicitly
// managing destroyed
this._writableState.destroyed = value;
}
});
Writable.prototype.destroy = destroyImpl.destroy;
Writable.prototype._undestroy = destroyImpl.undestroy;
Writable.prototype._destroy = function (err, cb) {
this.end();
cb(err);
};
}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("timers").setImmediate)
},{"./_stream_duplex":492,"./internal/streams/destroy":498,"./internal/streams/stream":499,"_process":491,"core-util-is":482,"inherits":486,"process-nextick-args":490,"safe-buffer":501,"timers":503,"util-deprecate":504}],497:[function(require,module,exports){
'use strict';
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Buffer = require('safe-buffer').Buffer;
var util = require('util');
function copyBuffer(src, target, offset) {
src.copy(target, offset);
}
module.exports = function () {
function BufferList() {
_classCallCheck(this, BufferList);
this.head = null;
this.tail = null;
this.length = 0;
}
BufferList.prototype.push = function push(v) {
var entry = { data: v, next: null };
if (this.length > 0) this.tail.next = entry;else this.head = entry;
this.tail = entry;
++this.length;
};
BufferList.prototype.unshift = function unshift(v) {
var entry = { data: v, next: this.head };
if (this.length === 0) this.tail = entry;
this.head = entry;
++this.length;
};
BufferList.prototype.shift = function shift() {
if (this.length === 0) return;
var ret = this.head.data;
if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
--this.length;
return ret;
};
BufferList.prototype.clear = function clear() {
this.head = this.tail = null;
this.length = 0;
};
BufferList.prototype.join = function join(s) {
if (this.length === 0) return '';
var p = this.head;
var ret = '' + p.data;
while (p = p.next) {
ret += s + p.data;
}return ret;
};
BufferList.prototype.concat = function concat(n) {
if (this.length === 0) return Buffer.alloc(0);
if (this.length === 1) return this.head.data;
var ret = Buffer.allocUnsafe(n >>> 0);
var p = this.head;
var i = 0;
while (p) {
copyBuffer(p.data, ret, i);
i += p.data.length;
p = p.next;
}
return ret;
};
return BufferList;
}();
if (util && util.inspect && util.inspect.custom) {
module.exports.prototype[util.inspect.custom] = function () {
var obj = util.inspect({ length: this.length });
return this.constructor.name + ' ' + obj;
};
}
},{"safe-buffer":501,"util":478}],498:[function(require,module,exports){
'use strict';
/*<replacement>*/
var pna = require('process-nextick-args');
/*</replacement>*/
// undocumented cb() API, needed for core, not for public API
function destroy(err, cb) {
var _this = this;
var readableDestroyed = this._readableState && this._readableState.destroyed;
var writableDestroyed = this._writableState && this._writableState.destroyed;
if (readableDestroyed || writableDestroyed) {
if (cb) {
cb(err);
} else if (err && (!this._writableState || !this._writableState.errorEmitted)) {
pna.nextTick(emitErrorNT, this, err);
}
return this;
}
// we set destroyed to true before firing error callbacks in order
// to make it re-entrance safe in case destroy() is called within callbacks
if (this._readableState) {
this._readableState.destroyed = true;
}
// if this is a duplex stream mark the writable part as destroyed as well
if (this._writableState) {
this._writableState.destroyed = true;
}
this._destroy(err || null, function (err) {
if (!cb && err) {
pna.nextTick(emitErrorNT, _this, err);
if (_this._writableState) {
_this._writableState.errorEmitted = true;
}
} else if (cb) {
cb(err);
}
});
return this;
}
function undestroy() {
if (this._readableState) {
this._readableState.destroyed = false;
this._readableState.reading = false;
this._readableState.ended = false;
this._readableState.endEmitted = false;
}
if (this._writableState) {
this._writableState.destroyed = false;
this._writableState.ended = false;
this._writableState.ending = false;
this._writableState.finished = false;
this._writableState.errorEmitted = false;
}
}
function emitErrorNT(self, err) {
self.emit('error', err);
}
module.exports = {
destroy: destroy,
undestroy: undestroy
};
},{"process-nextick-args":490}],499:[function(require,module,exports){
module.exports = require('events').EventEmitter;
},{"events":479}],500:[function(require,module,exports){
exports = module.exports = require('./lib/_stream_readable.js');
exports.Stream = exports;
exports.Readable = exports;
exports.Writable = require('./lib/_stream_writable.js');
exports.Duplex = require('./lib/_stream_duplex.js');
exports.Transform = require('./lib/_stream_transform.js');
exports.PassThrough = require('./lib/_stream_passthrough.js');
},{"./lib/_stream_duplex.js":492,"./lib/_stream_passthrough.js":493,"./lib/_stream_readable.js":494,"./lib/_stream_transform.js":495,"./lib/_stream_writable.js":496}],501:[function(require,module,exports){
/* eslint-disable node/no-deprecated-api */
var buffer = require('buffer')
var Buffer = buffer.Buffer
// alternative to using Object.keys for old browsers
function copyProps (src, dst) {
for (var key in src) {
dst[key] = src[key]
}
}
if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
module.exports = buffer
} else {
// Copy properties from require('buffer')
copyProps(buffer, exports)
exports.Buffer = SafeBuffer
}
function SafeBuffer (arg, encodingOrOffset, length) {
return Buffer(arg, encodingOrOffset, length)
}
// Copy static methods from Buffer
copyProps(Buffer, SafeBuffer)
SafeBuffer.from = function (arg, encodingOrOffset, length) {
if (typeof arg === 'number') {
throw new TypeError('Argument must not be a number')
}
return Buffer(arg, encodingOrOffset, length)
}
SafeBuffer.alloc = function (size, fill, encoding) {
if (typeof size !== 'number') {
throw new TypeError('Argument must be a number')
}
var buf = Buffer(size)
if (fill !== undefined) {
if (typeof encoding === 'string') {
buf.fill(fill, encoding)
} else {
buf.fill(fill)
}
} else {
buf.fill(0)
}
return buf
}
SafeBuffer.allocUnsafe = function (size) {
if (typeof size !== 'number') {
throw new TypeError('Argument must be a number')
}
return Buffer(size)
}
SafeBuffer.allocUnsafeSlow = function (size) {
if (typeof size !== 'number') {
throw new TypeError('Argument must be a number')
}
return buffer.SlowBuffer(size)
}
},{"buffer":481}],502:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
'use strict';
/*<replacement>*/
var Buffer = require('safe-buffer').Buffer;
/*</replacement>*/
var isEncoding = Buffer.isEncoding || function (encoding) {
encoding = '' + encoding;
switch (encoding && encoding.toLowerCase()) {
case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw':
return true;
default:
return false;
}
};
function _normalizeEncoding(enc) {
if (!enc) return 'utf8';
var retried;
while (true) {
switch (enc) {
case 'utf8':
case 'utf-8':
return 'utf8';
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return 'utf16le';
case 'latin1':
case 'binary':
return 'latin1';
case 'base64':
case 'ascii':
case 'hex':
return enc;
default:
if (retried) return; // undefined
enc = ('' + enc).toLowerCase();
retried = true;
}
}
};
// Do not cache `Buffer.isEncoding` when checking encoding names as some
// modules monkey-patch it to support additional encodings
function normalizeEncoding(enc) {
var nenc = _normalizeEncoding(enc);
if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
return nenc || enc;
}
// StringDecoder provides an interface for efficiently splitting a series of
// buffers into a series of JS strings without breaking apart multi-byte
// characters.
exports.StringDecoder = StringDecoder;
function StringDecoder(encoding) {
this.encoding = normalizeEncoding(encoding);
var nb;
switch (this.encoding) {
case 'utf16le':
this.text = utf16Text;
this.end = utf16End;
nb = 4;
break;
case 'utf8':
this.fillLast = utf8FillLast;
nb = 4;
break;
case 'base64':
this.text = base64Text;
this.end = base64End;
nb = 3;
break;
default:
this.write = simpleWrite;
this.end = simpleEnd;
return;
}
this.lastNeed = 0;
this.lastTotal = 0;
this.lastChar = Buffer.allocUnsafe(nb);
}
StringDecoder.prototype.write = function (buf) {
if (buf.length === 0) return '';
var r;
var i;
if (this.lastNeed) {
r = this.fillLast(buf);
if (r === undefined) return '';
i = this.lastNeed;
this.lastNeed = 0;
} else {
i = 0;
}
if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
return r || '';
};
StringDecoder.prototype.end = utf8End;
// Returns only complete characters in a Buffer
StringDecoder.prototype.text = utf8Text;
// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
StringDecoder.prototype.fillLast = function (buf) {
if (this.lastNeed <= buf.length) {
buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
return this.lastChar.toString(this.encoding, 0, this.lastTotal);
}
buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
this.lastNeed -= buf.length;
};
// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
// continuation byte. If an invalid byte is detected, -2 is returned.
function utf8CheckByte(byte) {
if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;
return byte >> 6 === 0x02 ? -1 : -2;
}
// Checks at most 3 bytes at the end of a Buffer in order to detect an
// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
// needed to complete the UTF-8 character (if applicable) are returned.
function utf8CheckIncomplete(self, buf, i) {
var j = buf.length - 1;
if (j < i) return 0;
var nb = utf8CheckByte(buf[j]);
if (nb >= 0) {
if (nb > 0) self.lastNeed = nb - 1;
return nb;
}
if (--j < i || nb === -2) return 0;
nb = utf8CheckByte(buf[j]);
if (nb >= 0) {
if (nb > 0) self.lastNeed = nb - 2;
return nb;
}
if (--j < i || nb === -2) return 0;
nb = utf8CheckByte(buf[j]);
if (nb >= 0) {
if (nb > 0) {
if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
}
return nb;
}
return 0;
}
// Validates as many continuation bytes for a multi-byte UTF-8 character as
// needed or are available. If we see a non-continuation byte where we expect
// one, we "replace" the validated continuation bytes we've seen so far with
// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding
// behavior. The continuation byte check is included three times in the case
// where all of the continuation bytes for a character exist in the same buffer.
// It is also done this way as a slight performance increase instead of using a
// loop.
function utf8CheckExtraBytes(self, buf, p) {
if ((buf[0] & 0xC0) !== 0x80) {
self.lastNeed = 0;
return '\ufffd';
}
if (self.lastNeed > 1 && buf.length > 1) {
if ((buf[1] & 0xC0) !== 0x80) {
self.lastNeed = 1;
return '\ufffd';
}
if (self.lastNeed > 2 && buf.length > 2) {
if ((buf[2] & 0xC0) !== 0x80) {
self.lastNeed = 2;
return '\ufffd';
}
}
}
}
// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
function utf8FillLast(buf) {
var p = this.lastTotal - this.lastNeed;
var r = utf8CheckExtraBytes(this, buf, p);
if (r !== undefined) return r;
if (this.lastNeed <= buf.length) {
buf.copy(this.lastChar, p, 0, this.lastNeed);
return this.lastChar.toString(this.encoding, 0, this.lastTotal);
}
buf.copy(this.lastChar, p, 0, buf.length);
this.lastNeed -= buf.length;
}
// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
// partial character, the character's bytes are buffered until the required
// number of bytes are available.
function utf8Text(buf, i) {
var total = utf8CheckIncomplete(this, buf, i);
if (!this.lastNeed) return buf.toString('utf8', i);
this.lastTotal = total;
var end = buf.length - (total - this.lastNeed);
buf.copy(this.lastChar, 0, end);
return buf.toString('utf8', i, end);
}
// For UTF-8, a replacement character is added when ending on a partial
// character.
function utf8End(buf) {
var r = buf && buf.length ? this.write(buf) : '';
if (this.lastNeed) return r + '\ufffd';
return r;
}
// UTF-16LE typically needs two bytes per character, but even if we have an even
// number of bytes available, we need to check if we end on a leading/high
// surrogate. In that case, we need to wait for the next two bytes in order to
// decode the last character properly.
function utf16Text(buf, i) {
if ((buf.length - i) % 2 === 0) {
var r = buf.toString('utf16le', i);
if (r) {
var c = r.charCodeAt(r.length - 1);
if (c >= 0xD800 && c <= 0xDBFF) {
this.lastNeed = 2;
this.lastTotal = 4;
this.lastChar[0] = buf[buf.length - 2];
this.lastChar[1] = buf[buf.length - 1];
return r.slice(0, -1);
}
}
return r;
}
this.lastNeed = 1;
this.lastTotal = 2;
this.lastChar[0] = buf[buf.length - 1];
return buf.toString('utf16le', i, buf.length - 1);
}
// For UTF-16LE we do not explicitly append special replacement characters if we
// end on a partial character, we simply let v8 handle that.
function utf16End(buf) {
var r = buf && buf.length ? this.write(buf) : '';
if (this.lastNeed) {
var end = this.lastTotal - this.lastNeed;
return r + this.lastChar.toString('utf16le', 0, end);
}
return r;
}
function base64Text(buf, i) {
var n = (buf.length - i) % 3;
if (n === 0) return buf.toString('base64', i);
this.lastNeed = 3 - n;
this.lastTotal = 3;
if (n === 1) {
this.lastChar[0] = buf[buf.length - 1];
} else {
this.lastChar[0] = buf[buf.length - 2];
this.lastChar[1] = buf[buf.length - 1];
}
return buf.toString('base64', i, buf.length - n);
}
function base64End(buf) {
var r = buf && buf.length ? this.write(buf) : '';
if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
return r;
}
// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
function simpleWrite(buf) {
return buf.toString(this.encoding);
}
function simpleEnd(buf) {
return buf && buf.length ? this.write(buf) : '';
}
},{"safe-buffer":501}],503:[function(require,module,exports){
(function (setImmediate,clearImmediate){(function (){
var nextTick = require('process/browser.js').nextTick;
var apply = Function.prototype.apply;
var slice = Array.prototype.slice;
var immediateIds = {};
var nextImmediateId = 0;
// DOM APIs, for completeness
exports.setTimeout = function() {
return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
};
exports.setInterval = function() {
return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
};
exports.clearTimeout =
exports.clearInterval = function(timeout) { timeout.close(); };
function Timeout(id, clearFn) {
this._id = id;
this._clearFn = clearFn;
}
Timeout.prototype.unref = Timeout.prototype.ref = function() {};
Timeout.prototype.close = function() {
this._clearFn.call(window, this._id);
};
// Does not start the time, just sets up the members needed.
exports.enroll = function(item, msecs) {
clearTimeout(item._idleTimeoutId);
item._idleTimeout = msecs;
};
exports.unenroll = function(item) {
clearTimeout(item._idleTimeoutId);
item._idleTimeout = -1;
};
exports._unrefActive = exports.active = function(item) {
clearTimeout(item._idleTimeoutId);
var msecs = item._idleTimeout;
if (msecs >= 0) {
item._idleTimeoutId = setTimeout(function onTimeout() {
if (item._onTimeout)
item._onTimeout();
}, msecs);
}
};
// That's not how node.js implements it but the exposed api is the same.
exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) {
var id = nextImmediateId++;
var args = arguments.length < 2 ? false : slice.call(arguments, 1);
immediateIds[id] = true;
nextTick(function onNextTick() {
if (immediateIds[id]) {
// fn.call() is faster so we optimize for the common use-case
// @see http://jsperf.com/call-apply-segu
if (args) {
fn.apply(null, args);
} else {
fn.call(null);
}
// Prevent ids from leaking
exports.clearImmediate(id);
}
});
return id;
};
exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) {
delete immediateIds[id];
};
}).call(this)}).call(this,require("timers").setImmediate,require("timers").clearImmediate)
},{"process/browser.js":491,"timers":503}],504:[function(require,module,exports){
(function (global){(function (){
/**
* Module exports.
*/
module.exports = deprecate;
/**
* Mark that a method should not be used.
* Returns a modified function which warns once by default.
*
* If `localStorage.noDeprecation = true` is set, then it is a no-op.
*
* If `localStorage.throwDeprecation = true` is set, then deprecated functions
* will throw an Error when invoked.
*
* If `localStorage.traceDeprecation = true` is set, then deprecated functions
* will invoke `console.trace()` instead of `console.error()`.
*
* @param {Function} fn - the function to deprecate
* @param {String} msg - the string to print to the console when `fn` is invoked
* @returns {Function} a new "deprecated" version of `fn`
* @api public
*/
function deprecate (fn, msg) {
if (config('noDeprecation')) {
return fn;
}
var warned = false;
function deprecated() {
if (!warned) {
if (config('throwDeprecation')) {
throw new Error(msg);
} else if (config('traceDeprecation')) {
console.trace(msg);
} else {
console.warn(msg);
}
warned = true;
}
return fn.apply(this, arguments);
}
return deprecated;
}
/**
* Checks `localStorage` for boolean values for the given `name`.
*
* @param {String} name
* @returns {Boolean}
* @api private
*/
function config (name) {
// accessing global.localStorage can trigger a DOMException in sandboxed iframes
try {
if (!global.localStorage) return false;
} catch (_) {
return false;
}
var val = global.localStorage[name];
if (null == val) return false;
return String(val).toLowerCase() === 'true';
}
}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}]},{},[360,361,362,363]);
| stdlib-js/www | public/docs/api/latest/@stdlib/stats/base/snanvarianceyc/benchmark_bundle.js | JavaScript | apache-2.0 | 1,011,466 |
/*
* This file is part of the \BlueLaTeX project.
*
* 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 module = angular.module("bluelatex");
module.factory("Permission", [
"$resource",
"ServerService",
function ($resource, ServerService) {
"use strict";
return $resource(ServerService.urlServer + "/papers/:paperId/permissions", null, {
"save": {
method: "PATCH"
},
"getCustomPermission": {
url: ServerService.urlServer + "/users/:userId/permissions"
},
"saveCustomPermission": {
method: "PATCH",
url: ServerService.urlServer + "/users/:userId/permissions"
}
});
}
]);
| bluelatex/bluelatex-web | app/shared/entities/PermissionFacotry.js | JavaScript | apache-2.0 | 1,260 |
"use strict";
const getPaths = require("enhanced-resolve/lib/getPaths");
const forEachBail = require("enhanced-resolve/lib/forEachBail");
module.exports = class RailsEnginesPlugin {
constructor(source, target, engines, root) {
this.source = source;
this.target = target;
this.engines = engines;
this.root = root;
}
// match path to engine, even if it's under another engine's vendor (longest match)
pathToEngine(path) {
const pathLength = (path) => (path.match(/\//g) || []).length;
const candidates = (path, field) => Object.keys(this.engines)
.filter((engine) => path.startsWith(this.engines[engine][field]))
.sort((a, b) => {
const aLen = pathLength(this.engines[a][field]);
const bLen = pathLength(this.engines[b][field]);
return bLen - aLen;
});
const rootCandidates = candidates(path, 'root');
const moduleCandidates = candidates(path, 'node_modules');
if (moduleCandidates[0]) {
return { engine: moduleCandidates[0], inNodeModules: true };
} else if (rootCandidates[0]) {
return { engine: rootCandidates[0], inNodeModules: false };
} else {
// yarn linked package requiring further stuff - limited to shared packages or nested node_modules
return { engine: 'manageiq-ui-classic', inNodeModules: true, fallback: true };
}
}
apply(resolver) {
const target = resolver.ensureHook(this.target);
resolver.getHook(this.source).tapAsync("RailsEnginesPlugin", (request, resolveContext, callback) => {
const engine = this.pathToEngine(request.path);
const engineModules = !engine.fallback ?
this.engines[engine.engine].node_modules :
`${request.descriptionFileRoot}/node_modules`;
const inNodeModules = engine.inNodeModules;
const packageName = request.request.split('/')[0];
let targetEngineModules = engineModules;
if (engine.fallback) {
console.warn(`RailsEnginesPlugin: no engine found for ${request.path} asking for ${request.request} (only a problem if you're *not* using yarn link)`);
targetEngineModules = this.root;
}
if (! inNodeModules) {
const obj = {
...request,
path: targetEngineModules,
request: `./${request.request}`,
};
resolver.doResolve(target, obj, `engine ${engine.engine}`, resolveContext, callback);
return;
}
// only look in paths under the plugin's node_modules
const paths = getPaths(request.path).paths;
const engineBoundary = paths.indexOf(engineModules); // not targetEngineModules
const cutPaths = paths.slice(0, engineBoundary);
let joinedPaths = cutPaths.map((p) => resolver.join(p, 'node_modules'));
// include the engine modules dir itself
joinedPaths.push(targetEngineModules);
const fs = resolver.fileSystem;
forEachBail(joinedPaths, (addr, callback) => {
fs.stat(resolver.join(addr, packageName), (err, stat) => {
if (err || !stat || !stat.isDirectory()) {
return callback();
}
const obj = {
...request,
path: addr,
request: `./${request.request}`,
};
return resolver.doResolve(target, obj, `modules in ${addr}`, resolveContext, callback);
});
}, callback);
});
}
};
| ManageIQ/manageiq-ui-classic | config/webpack/RailsEnginesPlugin.js | JavaScript | apache-2.0 | 3,384 |
/* @flow */
import { Component } from 'react';
import Pagination from '../../../../../../library/Pagination';
import Table from '../../../../../../library/Table';
import { ThemeProvider } from '../../../../../../library/themes';
import DemoLayout from '../../../common/DemoLayout';
export const columns = [
{ content: 'معدني', key: 'اسم' },
{ content: 'اللون', key: 'اللون' },
{ content: 'بريق', key: 'بريق' },
{ content: 'نظام الكريستال', key: 'النظام' },
{ content: 'الكريستال العادة', key: 'عادة' }
];
export const data = [
{
اسم: 'الملكيت',
اللون: 'الخضر المختلفة',
بريق: 'الأسمنت المسلح',
النظام: 'أحادي الميلان',
عادة: 'إبري'
},
{
اسم: 'الفلوريت معدن متبلور',
اللون: 'عديم اللون',
بريق: 'زجاجي',
النظام: 'متساوي القياس',
عادة: 'عقدي'
},
{
اسم: 'المغنتيت',
اللون: 'أسود',
بريق: 'معدني',
النظام: 'متساوي القياس',
عادة: 'ثماني السطوح'
},
{
اسم: 'كوارتز',
اللون: 'عديم اللون',
بريق: 'زجاجي',
النظام: 'ثلاثي الزوايا أو سداسية',
عادة: 'المنشور ذو الوجهين'
},
{
اسم: 'اللازورد معدن أزرق',
اللون: 'الأزرق السماوي',
بريق: 'زجاجي',
النظام: 'أحادي الميلان',
عادة: 'المنشورية ، الرواسب'
},
{
اسم: 'الهيماتيت حجر الدم',
اللون: 'رمادى معدنى',
بريق: 'معدني لرائع',
النظام: 'ثلاثي الزوايا',
عادة: 'ميكائي أو بلاثي ، وريدات ، أووليت'
},
{
اسم: 'البيريت معدن',
اللون: 'شاحب أصفر عاكس',
بريق: 'لامع ، لامعة',
النظام: 'متساوي القياس',
عادة: 'مكعب ، بين المشترك ، مشع ، هابط'
},
{
اسم: 'الزوسيت',
اللون: 'أبيض ، مختلف',
بريق: 'زجاجي, لؤلؤي على أسطح الانقسام',
النظام: 'معيني متعامد المحاور',
عادة: 'المنشورية مع الانشقاقات'
},
{
اسم: 'زيلونيت',
اللون: 'بني أخضر ، مختلف',
بريق: 'لؤلؤي',
النظام: 'أحادي الميلان',
عادة: 'ترابي ، لا تقابلات بلورية واضحة'
},
{
اسم: 'Howlite',
اللون: 'أبيض, عديم اللون',
بريق: 'زجاجي, بريق',
النظام: 'أحادي الميلان',
عادة: 'هائل للعقيدة'
},
{
اسم: 'التورمالين',
اللون: 'أسود ، مختلف',
بريق: 'زجاجي, أحيانا راتنجي',
النظام: 'ثلاثي الزوايا',
عادة: 'متوازي وممدود'
},
{
اسم: 'Celestite',
اللون: 'عديم اللون، مختلف',
بريق: 'زجاجي، لؤلؤي على الانشقاقات',
النظام: 'معيني متعامد المحاور',
عادة: 'ليفي ، لاميلار'
},
{
اسم: 'فانادينيت',
اللون: 'أحمر مشرق ، مختلف',
بريق: 'راتينجي',
النظام: 'مسدس الشكل',
عادة: 'المنشورية ، ليفية'
},
{
اسم: 'الأراغونيت',
اللون: 'أبيض ، مختلف',
بريق: 'زجاجي، راتنجات على أسطح الكسر',
النظام: 'معيني متعامد المحاور',
عادة: 'عينية ، عمودي'
}
];
export default {
id: 'rtl',
title: 'Bidirectionality',
description: `When the \`direction\` theme variable is set to \`rtl\`
(right-to-left), alignment and page order are reversed for Pagination. The
\`messages\` prop allows customization of various messages — both those that are
displayed, and those that are announced by assistive technologies.`,
scope: {
Component,
columns,
data,
DemoLayout,
Pagination,
Table,
ThemeProvider
},
source: `
() => {
const pageSizes = [2, 3, 4];
const itemText = (pageSize) => pageSize + ' لكل صفحة';
const status = (category, first, last, total) =>
first + '–' + last + ' من ' + total + ' ' + category;
const pageLabel = (isCurrentPage, isLastPage, page) =>
page + (isCurrentPage ? ', الصفحه الحاليه' : '') + (isLastPage ? ', آخر صفحة' : '');
const messages = {
category: 'المعادن',
label: 'ترقيم الصفحات',
pages: { pageLabel, next: 'التالى', previous: 'سابق' },
pageJumper: { label: 'اذهب الى الصفحة', placeholder: 'صفحة #' },
pageSizer: { status, itemText }
};
class PaginatedTable extends Component {
constructor(props) {
super(props);
this.state = {
currentPage: 1,
pageSize: pageSizes[1]
};
this.handlePageChange = this.handlePageChange.bind(this);
this.handlePageSizeChange = this.handlePageSizeChange.bind(this);
}
handlePageChange(currentPage) {
this.setState({ currentPage });
}
handlePageSizeChange(pageSize) {
this.setState({ pageSize });
}
render() {
const { currentPage, pageSize } = this.state;
const firstRow = (currentPage - 1) * pageSize;
const lastRow = (currentPage - 1) * pageSize + pageSize;
const slicedData = this.props.data.slice(firstRow, lastRow);
return (
<div dir="rtl">
<ThemeProvider theme={{ direction: 'rtl' }}>
<DemoLayout>
<Table
data={slicedData}
rowKey="اسم"
columns={columns}
title="المعادن"
hideTitle
/>
<Pagination
rtl
messages={messages}
currentPage={currentPage}
onPageSizeChange={this.handlePageSizeChange}
onPageChange={this.handlePageChange}
showPageJumper
showPageSizer
pageSize={pageSize}
pageSizes={pageSizes}
totalCount={data.length}
/>
</DemoLayout>
</ThemeProvider>
</div>
);
}
}
return <PaginatedTable data={data} />;
}
`
};
| mineral-ui/mineral-ui | src/website/app/demos/Pagination/Pagination/examples/rtl.js | JavaScript | apache-2.0 | 6,890 |
const express = require('express');
const http = require('http');
const path = require('path');
const errorHandler = require('./error-handler');
let app = express();
app.server = http.createServer(app);
app.use(errorHandler.logError);
app.use(errorHandler.sendError);
app.use(express.static(path.join(__dirname, '/../dist')));
app.get('*', (req, res, next) => {
res.sendFile(path.join(__dirname, '/../dist/index.html'));
});
app.server.listen(process.env.PORT || 3002);
console.log(`Express server listening on port ${app.server.address().port}`);
module.exports = app;
| elklein96/spotify-dl | client/static/server.js | JavaScript | apache-2.0 | 581 |
// modules are defined as an array
// [ module function, map of requireuires ]
//
// map of requireuires is short require name -> numeric require
//
// anything defined in a previous bundle is accessed via the
// orig method which is the requireuire for previous bundles
(function outer (modules, cache, entry) {
// Save the require from previous bundle to this closure if any
var previousRequire = typeof require == "function" && require;
function findProxyquireifyName() {
var deps = Object.keys(modules)
.map(function (k) { return modules[k][1]; });
for (var i = 0; i < deps.length; i++) {
var pq = deps[i]['proxyquireify'];
if (pq) return pq;
}
}
var proxyquireifyName = findProxyquireifyName();
function newRequire(name, jumped){
// Find the proxyquireify module, if present
var pqify = (proxyquireifyName != null) && cache[proxyquireifyName];
// Proxyquireify provides a separate cache that is used when inside
// a proxyquire call, and is set to null outside a proxyquire call.
// This allows the regular caching semantics to work correctly both
// inside and outside proxyquire calls while keeping the cached
// modules isolated.
// When switching from one proxyquire call to another, it clears
// the cache to prevent contamination between different sets
// of stubs.
var currentCache = (pqify && pqify.exports._cache) || cache;
if(!currentCache[name]) {
if(!modules[name]) {
// if we cannot find the the module within our internal map or
// cache jump to the current global require ie. the last bundle
// that was added to the page.
var currentRequire = typeof require == "function" && require;
if (!jumped && currentRequire) return currentRequire(name, true);
// If there are other bundles on this page the require from the
// previous one is saved to 'previousRequire'. Repeat this as
// many times as there are bundles until the module is found or
// we exhaust the require chain.
if (previousRequire) return previousRequire(name, true);
var err = new Error('Cannot find module \'' + name + '\'');
err.code = 'MODULE_NOT_FOUND';
throw err;
}
var m = currentCache[name] = {exports:{}};
// The normal browserify require function
var req = function(x){
var id = modules[name][1][x];
return newRequire(id ? id : x);
};
// The require function substituted for proxyquireify
var moduleRequire = function(x){
var pqify = (proxyquireifyName != null) && cache[proxyquireifyName];
// Only try to use the proxyquireify version if it has been `require`d
if (pqify && pqify.exports._proxy) {
return pqify.exports._proxy(req, x);
} else {
return req(x);
}
};
modules[name][0].call(m.exports,moduleRequire,m,m.exports,outer,modules,currentCache,entry);
}
return currentCache[name].exports;
}
for(var i=0;i<entry.length;i++) newRequire(entry[i]);
// Override the current require with this new one
return newRequire;
})
({1:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var ctor = ( typeof Float32Array === 'function' ) ? Float32Array : void 0; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = ctor;
},{}],2:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Typed array constructor which returns a typed array representing an array of single-precision floating-point numbers in the platform byte order.
*
* @module @stdlib/array/float32
*
* @example
* var ctor = require( '@stdlib/array/float32' );
*
* var arr = new ctor( 10 );
* // returns <Float32Array>
*/
// MODULES //
var hasFloat32ArraySupport = require( '@stdlib/assert/has-float32array-support' );
var builtin = require( './float32array.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var ctor;
if ( hasFloat32ArraySupport() ) {
ctor = builtin;
} else {
ctor = polyfill;
}
// EXPORTS //
module.exports = ctor;
},{"./float32array.js":1,"./polyfill.js":3,"@stdlib/assert/has-float32array-support":33}],3:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// TODO: write polyfill
// MAIN //
/**
* Typed array which represents an array of single-precision floating-point numbers in the platform byte order.
*
* @throws {Error} not implemented
*/
function polyfill() {
throw new Error( 'not implemented' );
}
// EXPORTS //
module.exports = polyfill;
},{}],4:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var ctor = ( typeof Float64Array === 'function' ) ? Float64Array : void 0; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = ctor;
},{}],5:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Typed array constructor which returns a typed array representing an array of double-precision floating-point numbers in the platform byte order.
*
* @module @stdlib/array/float64
*
* @example
* var ctor = require( '@stdlib/array/float64' );
*
* var arr = new ctor( 10 );
* // returns <Float64Array>
*/
// MODULES //
var hasFloat64ArraySupport = require( '@stdlib/assert/has-float64array-support' );
var builtin = require( './float64array.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var ctor;
if ( hasFloat64ArraySupport() ) {
ctor = builtin;
} else {
ctor = polyfill;
}
// EXPORTS //
module.exports = ctor;
},{"./float64array.js":4,"./polyfill.js":6,"@stdlib/assert/has-float64array-support":36}],6:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// TODO: write polyfill
// MAIN //
/**
* Typed array which represents an array of double-precision floating-point numbers in the platform byte order.
*
* @throws {Error} not implemented
*/
function polyfill() {
throw new Error( 'not implemented' );
}
// EXPORTS //
module.exports = polyfill;
},{}],7:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Typed array constructor which returns a typed array representing an array of twos-complement 16-bit signed integers in the platform byte order.
*
* @module @stdlib/array/int16
*
* @example
* var ctor = require( '@stdlib/array/int16' );
*
* var arr = new ctor( 10 );
* // returns <Int16Array>
*/
// MODULES //
var hasInt16ArraySupport = require( '@stdlib/assert/has-int16array-support' );
var builtin = require( './int16array.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var ctor;
if ( hasInt16ArraySupport() ) {
ctor = builtin;
} else {
ctor = polyfill;
}
// EXPORTS //
module.exports = ctor;
},{"./int16array.js":8,"./polyfill.js":9,"@stdlib/assert/has-int16array-support":41}],8:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var ctor = ( typeof Int16Array === 'function' ) ? Int16Array : void 0; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = ctor;
},{}],9:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// TODO: write polyfill
// MAIN //
/**
* Typed array which represents an array of twos-complement 16-bit signed integers in the platform byte order.
*
* @throws {Error} not implemented
*/
function polyfill() {
throw new Error( 'not implemented' );
}
// EXPORTS //
module.exports = polyfill;
},{}],10:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Typed array constructor which returns a typed array representing an array of twos-complement 32-bit signed integers in the platform byte order.
*
* @module @stdlib/array/int32
*
* @example
* var ctor = require( '@stdlib/array/int32' );
*
* var arr = new ctor( 10 );
* // returns <Int32Array>
*/
// MODULES //
var hasInt32ArraySupport = require( '@stdlib/assert/has-int32array-support' );
var builtin = require( './int32array.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var ctor;
if ( hasInt32ArraySupport() ) {
ctor = builtin;
} else {
ctor = polyfill;
}
// EXPORTS //
module.exports = ctor;
},{"./int32array.js":11,"./polyfill.js":12,"@stdlib/assert/has-int32array-support":44}],11:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var ctor = ( typeof Int32Array === 'function' ) ? Int32Array : void 0; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = ctor;
},{}],12:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// TODO: write polyfill
// MAIN //
/**
* Typed array which represents an array of twos-complement 32-bit signed integers in the platform byte order.
*
* @throws {Error} not implemented
*/
function polyfill() {
throw new Error( 'not implemented' );
}
// EXPORTS //
module.exports = polyfill;
},{}],13:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Typed array constructor which returns a typed array representing an array of twos-complement 8-bit signed integers in the platform byte order.
*
* @module @stdlib/array/int8
*
* @example
* var ctor = require( '@stdlib/array/int8' );
*
* var arr = new ctor( 10 );
* // returns <Int8Array>
*/
// MODULES //
var hasInt8ArraySupport = require( '@stdlib/assert/has-int8array-support' );
var builtin = require( './int8array.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var ctor;
if ( hasInt8ArraySupport() ) {
ctor = builtin;
} else {
ctor = polyfill;
}
// EXPORTS //
module.exports = ctor;
},{"./int8array.js":14,"./polyfill.js":15,"@stdlib/assert/has-int8array-support":47}],14:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var ctor = ( typeof Int8Array === 'function' ) ? Int8Array : void 0; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = ctor;
},{}],15:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// TODO: write polyfill
// MAIN //
/**
* Typed array which represents an array of twos-complement 8-bit signed integers in the platform byte order.
*
* @throws {Error} not implemented
*/
function polyfill() {
throw new Error( 'not implemented' );
}
// EXPORTS //
module.exports = polyfill;
},{}],16:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var Int8Array = require( '@stdlib/array/int8' );
var Uint8Array = require( '@stdlib/array/uint8' );
var Uint8ClampedArray = require( '@stdlib/array/uint8c' );
var Int16Array = require( '@stdlib/array/int16' );
var Uint16Array = require( '@stdlib/array/uint16' );
var Int32Array = require( '@stdlib/array/int32' );
var Uint32Array = require( '@stdlib/array/uint32' );
var Float32Array = require( '@stdlib/array/float32' );
var Float64Array = require( '@stdlib/array/float64' );
// MAIN //
var CTORS = [
[ Float64Array, 'Float64Array' ],
[ Float32Array, 'Float32Array' ],
[ Int32Array, 'Int32Array' ],
[ Uint32Array, 'Uint32Array' ],
[ Int16Array, 'Int16Array' ],
[ Uint16Array, 'Uint16Array' ],
[ Int8Array, 'Int8Array' ],
[ Uint8Array, 'Uint8Array' ],
[ Uint8ClampedArray, 'Uint8ClampedArray' ]
];
// EXPORTS //
module.exports = CTORS;
},{"@stdlib/array/float32":2,"@stdlib/array/float64":5,"@stdlib/array/int16":7,"@stdlib/array/int32":10,"@stdlib/array/int8":13,"@stdlib/array/uint16":20,"@stdlib/array/uint32":23,"@stdlib/array/uint8":26,"@stdlib/array/uint8c":29}],17:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Return a JSON representation of a typed array.
*
* @module @stdlib/array/to-json
*
* @example
* var Float64Array = require( '@stdlib/array/float64' );
* var toJSON = require( '@stdlib/array/to-json' );
*
* var arr = new Float64Array( [ 5.0, 3.0 ] );
* var json = toJSON( arr );
* // returns { 'type': 'Float64Array', 'data': [ 5.0, 3.0 ] }
*/
// MODULES //
var toJSON = require( './to_json.js' );
// EXPORTS //
module.exports = toJSON;
},{"./to_json.js":18}],18:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isTypedArray = require( '@stdlib/assert/is-typed-array' );
var typeName = require( './type.js' );
// MAIN //
/**
* Returns a JSON representation of a typed array.
*
* ## Notes
*
* - We build a JSON object representing a typed array similar to how Node.js `Buffer` objects are represented. See [Buffer][1].
*
* [1]: https://nodejs.org/api/buffer.html#buffer_buf_tojson
*
* @param {TypedArray} arr - typed array to serialize
* @throws {TypeError} first argument must be a typed array
* @returns {Object} JSON representation
*
* @example
* var Float64Array = require( '@stdlib/array/float64' );
*
* var arr = new Float64Array( [ 5.0, 3.0 ] );
* var json = toJSON( arr );
* // returns { 'type': 'Float64Array', 'data': [ 5.0, 3.0 ] }
*/
function toJSON( arr ) {
var out;
var i;
if ( !isTypedArray( arr ) ) {
throw new TypeError( 'invalid argument. Must provide a typed array. Value: `' + arr + '`.' );
}
out = {};
out.type = typeName( arr );
out.data = [];
for ( i = 0; i < arr.length; i++ ) {
out.data.push( arr[ i ] );
}
return out;
}
// EXPORTS //
module.exports = toJSON;
},{"./type.js":19,"@stdlib/assert/is-typed-array":165}],19:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var instanceOf = require( '@stdlib/assert/instance-of' );
var ctorName = require( '@stdlib/utils/constructor-name' );
var getPrototypeOf = require( '@stdlib/utils/get-prototype-of' );
var CTORS = require( './ctors.js' );
// MAIN //
/**
* Returns the typed array type.
*
* @private
* @param {TypedArray} arr - typed array
* @returns {(string|void)} typed array type
*
* @example
* var Float64Array = require( '@stdlib/array/float64' );
*
* var arr = new Float64Array( 5 );
* var str = typeName( arr );
* // returns 'Float64Array'
*/
function typeName( arr ) {
var v;
var i;
// Check for typed array objects from the same realm (same Node.js `vm` or same `Window` object)...
for ( i = 0; i < CTORS.length; i++ ) {
if ( instanceOf( arr, CTORS[ i ][ 0 ] ) ) {
return CTORS[ i ][ 1 ];
}
}
// Walk the prototype tree until we find an object having a desired native class...
while ( arr ) {
v = ctorName( arr );
for ( i = 0; i < CTORS.length; i++ ) {
if ( v === CTORS[ i ][ 1 ] ) {
return CTORS[ i ][ 1 ];
}
}
arr = getPrototypeOf( arr );
}
}
// EXPORTS //
module.exports = typeName;
},{"./ctors.js":16,"@stdlib/assert/instance-of":71,"@stdlib/utils/constructor-name":336,"@stdlib/utils/get-prototype-of":359}],20:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Typed array constructor which returns a typed array representing an array of 16-bit unsigned integers in the platform byte order.
*
* @module @stdlib/array/uint16
*
* @example
* var ctor = require( '@stdlib/array/uint16' );
*
* var arr = new ctor( 10 );
* // returns <Uint16Array>
*/
// MODULES //
var hasUint16ArraySupport = require( '@stdlib/assert/has-uint16array-support' );
var builtin = require( './uint16array.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var ctor;
if ( hasUint16ArraySupport() ) {
ctor = builtin;
} else {
ctor = polyfill;
}
// EXPORTS //
module.exports = ctor;
},{"./polyfill.js":21,"./uint16array.js":22,"@stdlib/assert/has-uint16array-support":59}],21:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// TODO: write polyfill
// MAIN //
/**
* Typed array which represents an array of 16-bit unsigned integers in the platform byte order.
*
* @throws {Error} not implemented
*/
function polyfill() {
throw new Error( 'not implemented' );
}
// EXPORTS //
module.exports = polyfill;
},{}],22:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var ctor = ( typeof Uint16Array === 'function' ) ? Uint16Array : void 0; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = ctor;
},{}],23:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Typed array constructor which returns a typed array representing an array of 32-bit unsigned integers in the platform byte order.
*
* @module @stdlib/array/uint32
*
* @example
* var ctor = require( '@stdlib/array/uint32' );
*
* var arr = new ctor( 10 );
* // returns <Uint32Array>
*/
// MODULES //
var hasUint32ArraySupport = require( '@stdlib/assert/has-uint32array-support' );
var builtin = require( './uint32array.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var ctor;
if ( hasUint32ArraySupport() ) {
ctor = builtin;
} else {
ctor = polyfill;
}
// EXPORTS //
module.exports = ctor;
},{"./polyfill.js":24,"./uint32array.js":25,"@stdlib/assert/has-uint32array-support":62}],24:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// TODO: write polyfill
// MAIN //
/**
* Typed array which represents an array of 32-bit unsigned integers in the platform byte order.
*
* @throws {Error} not implemented
*/
function polyfill() {
throw new Error( 'not implemented' );
}
// EXPORTS //
module.exports = polyfill;
},{}],25:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var ctor = ( typeof Uint32Array === 'function' ) ? Uint32Array : void 0; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = ctor;
},{}],26:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Typed array constructor which returns a typed array representing an array of 8-bit unsigned integers in the platform byte order.
*
* @module @stdlib/array/uint8
*
* @example
* var ctor = require( '@stdlib/array/uint8' );
*
* var arr = new ctor( 10 );
* // returns <Uint8Array>
*/
// MODULES //
var hasUint8ArraySupport = require( '@stdlib/assert/has-uint8array-support' );
var builtin = require( './uint8array.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var ctor;
if ( hasUint8ArraySupport() ) {
ctor = builtin;
} else {
ctor = polyfill;
}
// EXPORTS //
module.exports = ctor;
},{"./polyfill.js":27,"./uint8array.js":28,"@stdlib/assert/has-uint8array-support":65}],27:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// TODO: write polyfill
// MAIN //
/**
* Typed array which represents an array of 8-bit unsigned integers in the platform byte order.
*
* @throws {Error} not implemented
*/
function polyfill() {
throw new Error( 'not implemented' );
}
// EXPORTS //
module.exports = polyfill;
},{}],28:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var ctor = ( typeof Uint8Array === 'function' ) ? Uint8Array : void 0; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = ctor;
},{}],29:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Typed array constructor which returns a typed array representing an array of 8-bit unsigned integers in the platform byte order clamped to 0-255.
*
* @module @stdlib/array/uint8c
*
* @example
* var ctor = require( '@stdlib/array/uint8c' );
*
* var arr = new ctor( 10 );
* // returns <Uint8ClampedArray>
*/
// MODULES //
var hasUint8ClampedArraySupport = require( '@stdlib/assert/has-uint8clampedarray-support' ); // eslint-disable-line id-length
var builtin = require( './uint8clampedarray.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var ctor;
if ( hasUint8ClampedArraySupport() ) {
ctor = builtin;
} else {
ctor = polyfill;
}
// EXPORTS //
module.exports = ctor;
},{"./polyfill.js":30,"./uint8clampedarray.js":31,"@stdlib/assert/has-uint8clampedarray-support":68}],30:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// TODO: write polyfill
// MAIN //
/**
* Typed array which represents an array of 8-bit unsigned integers in the platform byte order clamped to 0-255.
*
* @throws {Error} not implemented
*/
function polyfill() {
throw new Error( 'not implemented' );
}
// EXPORTS //
module.exports = polyfill;
},{}],31:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var ctor = ( typeof Uint8ClampedArray === 'function' ) ? Uint8ClampedArray : void 0; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = ctor;
},{}],32:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var main = ( typeof Float32Array === 'function' ) ? Float32Array : null; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = main;
},{}],33:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test for native `Float32Array` support.
*
* @module @stdlib/assert/has-float32array-support
*
* @example
* var hasFloat32ArraySupport = require( '@stdlib/assert/has-float32array-support' );
*
* var bool = hasFloat32ArraySupport();
* // returns <boolean>
*/
// MODULES //
var hasFloat32ArraySupport = require( './main.js' );
// EXPORTS //
module.exports = hasFloat32ArraySupport;
},{"./main.js":34}],34:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isFloat32Array = require( '@stdlib/assert/is-float32array' );
var PINF = require( '@stdlib/constants/float64/pinf' );
var GlobalFloat32Array = require( './float32array.js' );
// MAIN //
/**
* Tests for native `Float32Array` support.
*
* @returns {boolean} boolean indicating if an environment has `Float32Array` support
*
* @example
* var bool = hasFloat32ArraySupport();
* // returns <boolean>
*/
function hasFloat32ArraySupport() {
var bool;
var arr;
if ( typeof GlobalFloat32Array !== 'function' ) {
return false;
}
// Test basic support...
try {
arr = new GlobalFloat32Array( [ 1.0, 3.14, -3.14, 5.0e40 ] );
bool = (
isFloat32Array( arr ) &&
arr[ 0 ] === 1.0 &&
arr[ 1 ] === 3.140000104904175 &&
arr[ 2 ] === -3.140000104904175 &&
arr[ 3 ] === PINF
);
} catch ( err ) { // eslint-disable-line no-unused-vars
bool = false;
}
return bool;
}
// EXPORTS //
module.exports = hasFloat32ArraySupport;
},{"./float32array.js":32,"@stdlib/assert/is-float32array":98,"@stdlib/constants/float64/pinf":244}],35:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var main = ( typeof Float64Array === 'function' ) ? Float64Array : null; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = main;
},{}],36:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test for native `Float64Array` support.
*
* @module @stdlib/assert/has-float64array-support
*
* @example
* var hasFloat64ArraySupport = require( '@stdlib/assert/has-float64array-support' );
*
* var bool = hasFloat64ArraySupport();
* // returns <boolean>
*/
// MODULES //
var hasFloat64ArraySupport = require( './main.js' );
// EXPORTS //
module.exports = hasFloat64ArraySupport;
},{"./main.js":37}],37:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isFloat64Array = require( '@stdlib/assert/is-float64array' );
var GlobalFloat64Array = require( './float64array.js' );
// MAIN //
/**
* Tests for native `Float64Array` support.
*
* @returns {boolean} boolean indicating if an environment has `Float64Array` support
*
* @example
* var bool = hasFloat64ArraySupport();
* // returns <boolean>
*/
function hasFloat64ArraySupport() {
var bool;
var arr;
if ( typeof GlobalFloat64Array !== 'function' ) {
return false;
}
// Test basic support...
try {
arr = new GlobalFloat64Array( [ 1.0, 3.14, -3.14, NaN ] );
bool = (
isFloat64Array( arr ) &&
arr[ 0 ] === 1.0 &&
arr[ 1 ] === 3.14 &&
arr[ 2 ] === -3.14 &&
arr[ 3 ] !== arr[ 3 ]
);
} catch ( err ) { // eslint-disable-line no-unused-vars
bool = false;
}
return bool;
}
// EXPORTS //
module.exports = hasFloat64ArraySupport;
},{"./float64array.js":35,"@stdlib/assert/is-float64array":100}],38:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Dummy function.
*
* @private
*/
function foo() {
// No-op...
}
// EXPORTS //
module.exports = foo;
},{}],39:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test for native function `name` support.
*
* @module @stdlib/assert/has-function-name-support
*
* @example
* var hasFunctionNameSupport = require( '@stdlib/assert/has-function-name-support' );
*
* var bool = hasFunctionNameSupport();
* // returns <boolean>
*/
// MODULES //
var hasFunctionNameSupport = require( './main.js' );
// EXPORTS //
module.exports = hasFunctionNameSupport;
},{"./main.js":40}],40:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var foo = require( './foo.js' );
// MAIN //
/**
* Tests for native function `name` support.
*
* @returns {boolean} boolean indicating if an environment has function `name` support
*
* @example
* var bool = hasFunctionNameSupport();
* // returns <boolean>
*/
function hasFunctionNameSupport() {
return ( foo.name === 'foo' );
}
// EXPORTS //
module.exports = hasFunctionNameSupport;
},{"./foo.js":38}],41:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test for native `Int16Array` support.
*
* @module @stdlib/assert/has-int16array-support
*
* @example
* var hasInt16ArraySupport = require( '@stdlib/assert/has-int16array-support' );
*
* var bool = hasInt16ArraySupport();
* // returns <boolean>
*/
// MODULES //
var hasInt16ArraySupport = require( './main.js' );
// EXPORTS //
module.exports = hasInt16ArraySupport;
},{"./main.js":43}],42:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var main = ( typeof Int16Array === 'function' ) ? Int16Array : null; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = main;
},{}],43:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isInt16Array = require( '@stdlib/assert/is-int16array' );
var INT16_MAX = require( '@stdlib/constants/int16/max' );
var INT16_MIN = require( '@stdlib/constants/int16/min' );
var GlobalInt16Array = require( './int16array.js' );
// MAIN //
/**
* Tests for native `Int16Array` support.
*
* @returns {boolean} boolean indicating if an environment has `Int16Array` support
*
* @example
* var bool = hasInt16ArraySupport();
* // returns <boolean>
*/
function hasInt16ArraySupport() {
var bool;
var arr;
if ( typeof GlobalInt16Array !== 'function' ) {
return false;
}
// Test basic support...
try {
arr = new GlobalInt16Array( [ 1, 3.14, -3.14, INT16_MAX+1 ] );
bool = (
isInt16Array( arr ) &&
arr[ 0 ] === 1 &&
arr[ 1 ] === 3 && // truncation
arr[ 2 ] === -3 && // truncation
arr[ 3 ] === INT16_MIN // wrap around
);
} catch ( err ) { // eslint-disable-line no-unused-vars
bool = false;
}
return bool;
}
// EXPORTS //
module.exports = hasInt16ArraySupport;
},{"./int16array.js":42,"@stdlib/assert/is-int16array":104,"@stdlib/constants/int16/max":245,"@stdlib/constants/int16/min":246}],44:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test for native `Int32Array` support.
*
* @module @stdlib/assert/has-int32array-support
*
* @example
* var hasInt32ArraySupport = require( '@stdlib/assert/has-int32array-support' );
*
* var bool = hasInt32ArraySupport();
* // returns <boolean>
*/
// MODULES //
var hasInt32ArraySupport = require( './main.js' );
// EXPORTS //
module.exports = hasInt32ArraySupport;
},{"./main.js":46}],45:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var main = ( typeof Int32Array === 'function' ) ? Int32Array : null; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = main;
},{}],46:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isInt32Array = require( '@stdlib/assert/is-int32array' );
var INT32_MAX = require( '@stdlib/constants/int32/max' );
var INT32_MIN = require( '@stdlib/constants/int32/min' );
var GlobalInt32Array = require( './int32array.js' );
// MAIN //
/**
* Tests for native `Int32Array` support.
*
* @returns {boolean} boolean indicating if an environment has `Int32Array` support
*
* @example
* var bool = hasInt32ArraySupport();
* // returns <boolean>
*/
function hasInt32ArraySupport() {
var bool;
var arr;
if ( typeof GlobalInt32Array !== 'function' ) {
return false;
}
// Test basic support...
try {
arr = new GlobalInt32Array( [ 1, 3.14, -3.14, INT32_MAX+1 ] );
bool = (
isInt32Array( arr ) &&
arr[ 0 ] === 1 &&
arr[ 1 ] === 3 && // truncation
arr[ 2 ] === -3 && // truncation
arr[ 3 ] === INT32_MIN // wrap around
);
} catch ( err ) { // eslint-disable-line no-unused-vars
bool = false;
}
return bool;
}
// EXPORTS //
module.exports = hasInt32ArraySupport;
},{"./int32array.js":45,"@stdlib/assert/is-int32array":106,"@stdlib/constants/int32/max":247,"@stdlib/constants/int32/min":248}],47:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test for native `Int8Array` support.
*
* @module @stdlib/assert/has-int8array-support
*
* @example
* var hasInt8ArraySupport = require( '@stdlib/assert/has-int8array-support' );
*
* var bool = hasInt8ArraySupport();
* // returns <boolean>
*/
// MODULES //
var hasInt8ArraySupport = require( './main.js' );
// EXPORTS //
module.exports = hasInt8ArraySupport;
},{"./main.js":49}],48:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var main = ( typeof Int8Array === 'function' ) ? Int8Array : null; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = main;
},{}],49:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isInt8Array = require( '@stdlib/assert/is-int8array' );
var INT8_MAX = require( '@stdlib/constants/int8/max' );
var INT8_MIN = require( '@stdlib/constants/int8/min' );
var GlobalInt8Array = require( './int8array.js' );
// MAIN //
/**
* Tests for native `Int8Array` support.
*
* @returns {boolean} boolean indicating if an environment has `Int8Array` support
*
* @example
* var bool = hasInt8ArraySupport();
* // returns <boolean>
*/
function hasInt8ArraySupport() {
var bool;
var arr;
if ( typeof GlobalInt8Array !== 'function' ) {
return false;
}
// Test basic support...
try {
arr = new GlobalInt8Array( [ 1, 3.14, -3.14, INT8_MAX+1 ] );
bool = (
isInt8Array( arr ) &&
arr[ 0 ] === 1 &&
arr[ 1 ] === 3 && // truncation
arr[ 2 ] === -3 && // truncation
arr[ 3 ] === INT8_MIN // wrap around
);
} catch ( err ) { // eslint-disable-line no-unused-vars
bool = false;
}
return bool;
}
// EXPORTS //
module.exports = hasInt8ArraySupport;
},{"./int8array.js":48,"@stdlib/assert/is-int8array":108,"@stdlib/constants/int8/max":249,"@stdlib/constants/int8/min":250}],50:[function(require,module,exports){
(function (Buffer){(function (){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var main = ( typeof Buffer === 'function' ) ? Buffer : null; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = main;
}).call(this)}).call(this,require("buffer").Buffer)
},{"buffer":426}],51:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test for native `Buffer` support.
*
* @module @stdlib/assert/has-node-buffer-support
*
* @example
* var hasNodeBufferSupport = require( '@stdlib/assert/has-node-buffer-support' );
*
* var bool = hasNodeBufferSupport();
* // returns <boolean>
*/
// MODULES //
var hasNodeBufferSupport = require( './main.js' );
// EXPORTS //
module.exports = hasNodeBufferSupport;
},{"./main.js":52}],52:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isBuffer = require( '@stdlib/assert/is-buffer' );
var GlobalBuffer = require( './buffer.js' );
// MAIN //
/**
* Tests for native `Buffer` support.
*
* @returns {boolean} boolean indicating if an environment has `Buffer` support
*
* @example
* var bool = hasNodeBufferSupport();
* // returns <boolean>
*/
function hasNodeBufferSupport() {
var bool;
var b;
if ( typeof GlobalBuffer !== 'function' ) {
return false;
}
// Test basic support...
try {
if ( typeof GlobalBuffer.from === 'function' ) {
b = GlobalBuffer.from( [ 1, 2, 3, 4 ] );
} else {
b = new GlobalBuffer( [ 1, 2, 3, 4 ] ); // Note: this is deprecated behavior starting in Node v6 (see https://nodejs.org/api/buffer.html#buffer_new_buffer_array)
}
bool = (
isBuffer( b ) &&
b[ 0 ] === 1 &&
b[ 1 ] === 2 &&
b[ 2 ] === 3 &&
b[ 3 ] === 4
);
} catch ( err ) { // eslint-disable-line no-unused-vars
bool = false;
}
return bool;
}
// EXPORTS //
module.exports = hasNodeBufferSupport;
},{"./buffer.js":50,"@stdlib/assert/is-buffer":88}],53:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test whether an object has a specified property.
*
* @module @stdlib/assert/has-own-property
*
* @example
* var hasOwnProp = require( '@stdlib/assert/has-own-property' );
*
* var beep = {
* 'boop': true
* };
*
* var bool = hasOwnProp( beep, 'boop' );
* // returns true
*
* bool = hasOwnProp( beep, 'bop' );
* // returns false
*/
// MODULES //
var hasOwnProp = require( './main.js' );
// EXPORTS //
module.exports = hasOwnProp;
},{"./main.js":54}],54:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// FUNCTIONS //
var has = Object.prototype.hasOwnProperty;
// MAIN //
/**
* Tests if an object has a specified property.
*
* @param {*} value - value to test
* @param {*} property - property to test
* @returns {boolean} boolean indicating if an object has a specified property
*
* @example
* var beep = {
* 'boop': true
* };
*
* var bool = hasOwnProp( beep, 'boop' );
* // returns true
*
* @example
* var beep = {
* 'boop': true
* };
*
* var bool = hasOwnProp( beep, 'bap' );
* // returns false
*/
function hasOwnProp( value, property ) {
if (
value === void 0 ||
value === null
) {
return false;
}
return has.call( value, property );
}
// EXPORTS //
module.exports = hasOwnProp;
},{}],55:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test for native `Symbol` support.
*
* @module @stdlib/assert/has-symbol-support
*
* @example
* var hasSymbolSupport = require( '@stdlib/assert/has-symbol-support' );
*
* var bool = hasSymbolSupport();
* // returns <boolean>
*/
// MODULES //
var hasSymbolSupport = require( './main.js' );
// EXPORTS //
module.exports = hasSymbolSupport;
},{"./main.js":56}],56:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Tests for native `Symbol` support.
*
* @returns {boolean} boolean indicating if an environment has `Symbol` support
*
* @example
* var bool = hasSymbolSupport();
* // returns <boolean>
*/
function hasSymbolSupport() {
return (
typeof Symbol === 'function' &&
typeof Symbol( 'foo' ) === 'symbol'
);
}
// EXPORTS //
module.exports = hasSymbolSupport;
},{}],57:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test for native `toStringTag` support.
*
* @module @stdlib/assert/has-tostringtag-support
*
* @example
* var hasToStringTagSupport = require( '@stdlib/assert/has-tostringtag-support' );
*
* var bool = hasToStringTagSupport();
* // returns <boolean>
*/
// MODULES //
var hasToStringTagSupport = require( './main.js' );
// EXPORTS //
module.exports = hasToStringTagSupport;
},{"./main.js":58}],58:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var hasSymbols = require( '@stdlib/assert/has-symbol-support' );
// VARIABLES //
var FLG = hasSymbols();
// MAIN //
/**
* Tests for native `toStringTag` support.
*
* @returns {boolean} boolean indicating if an environment has `toStringTag` support
*
* @example
* var bool = hasToStringTagSupport();
* // returns <boolean>
*/
function hasToStringTagSupport() {
return ( FLG && typeof Symbol.toStringTag === 'symbol' );
}
// EXPORTS //
module.exports = hasToStringTagSupport;
},{"@stdlib/assert/has-symbol-support":55}],59:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test for native `Uint16Array` support.
*
* @module @stdlib/assert/has-uint16array-support
*
* @example
* var hasUint16ArraySupport = require( '@stdlib/assert/has-uint16array-support' );
*
* var bool = hasUint16ArraySupport();
* // returns <boolean>
*/
// MODULES //
var hasUint16ArraySupport = require( './main.js' );
// EXPORTS //
module.exports = hasUint16ArraySupport;
},{"./main.js":60}],60:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isUint16Array = require( '@stdlib/assert/is-uint16array' );
var UINT16_MAX = require( '@stdlib/constants/uint16/max' );
var GlobalUint16Array = require( './uint16array.js' );
// MAIN //
/**
* Tests for native `Uint16Array` support.
*
* @returns {boolean} boolean indicating if an environment has `Uint16Array` support
*
* @example
* var bool = hasUint16ArraySupport();
* // returns <boolean>
*/
function hasUint16ArraySupport() {
var bool;
var arr;
if ( typeof GlobalUint16Array !== 'function' ) {
return false;
}
// Test basic support...
try {
arr = [ 1, 3.14, -3.14, UINT16_MAX+1, UINT16_MAX+2 ];
arr = new GlobalUint16Array( arr );
bool = (
isUint16Array( arr ) &&
arr[ 0 ] === 1 &&
arr[ 1 ] === 3 && // truncation
arr[ 2 ] === UINT16_MAX-2 && // truncation and wrap around
arr[ 3 ] === 0 && // wrap around
arr[ 4 ] === 1 // wrap around
);
} catch ( err ) { // eslint-disable-line no-unused-vars
bool = false;
}
return bool;
}
// EXPORTS //
module.exports = hasUint16ArraySupport;
},{"./uint16array.js":61,"@stdlib/assert/is-uint16array":168,"@stdlib/constants/uint16/max":251}],61:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var main = ( typeof Uint16Array === 'function' ) ? Uint16Array : null; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = main;
},{}],62:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test for native `Uint32Array` support.
*
* @module @stdlib/assert/has-uint32array-support
*
* @example
* var hasUint32ArraySupport = require( '@stdlib/assert/has-uint32array-support' );
*
* var bool = hasUint32ArraySupport();
* // returns <boolean>
*/
// MODULES //
var hasUint32ArraySupport = require( './main.js' );
// EXPORTS //
module.exports = hasUint32ArraySupport;
},{"./main.js":63}],63:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isUint32Array = require( '@stdlib/assert/is-uint32array' );
var UINT32_MAX = require( '@stdlib/constants/uint32/max' );
var GlobalUint32Array = require( './uint32array.js' );
// MAIN //
/**
* Tests for native `Uint32Array` support.
*
* @returns {boolean} boolean indicating if an environment has `Uint32Array` support
*
* @example
* var bool = hasUint32ArraySupport();
* // returns <boolean>
*/
function hasUint32ArraySupport() {
var bool;
var arr;
if ( typeof GlobalUint32Array !== 'function' ) {
return false;
}
// Test basic support...
try {
arr = [ 1, 3.14, -3.14, UINT32_MAX+1, UINT32_MAX+2 ];
arr = new GlobalUint32Array( arr );
bool = (
isUint32Array( arr ) &&
arr[ 0 ] === 1 &&
arr[ 1 ] === 3 && // truncation
arr[ 2 ] === UINT32_MAX-2 && // truncation and wrap around
arr[ 3 ] === 0 && // wrap around
arr[ 4 ] === 1 // wrap around
);
} catch ( err ) { // eslint-disable-line no-unused-vars
bool = false;
}
return bool;
}
// EXPORTS //
module.exports = hasUint32ArraySupport;
},{"./uint32array.js":64,"@stdlib/assert/is-uint32array":170,"@stdlib/constants/uint32/max":252}],64:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var main = ( typeof Uint32Array === 'function' ) ? Uint32Array : null; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = main;
},{}],65:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test for native `Uint8Array` support.
*
* @module @stdlib/assert/has-uint8array-support
*
* @example
* var hasUint8ArraySupport = require( '@stdlib/assert/has-uint8array-support' );
*
* var bool = hasUint8ArraySupport();
* // returns <boolean>
*/
// MODULES //
var hasUint8ArraySupport = require( './main.js' );
// EXPORTS //
module.exports = hasUint8ArraySupport;
},{"./main.js":66}],66:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isUint8Array = require( '@stdlib/assert/is-uint8array' );
var UINT8_MAX = require( '@stdlib/constants/uint8/max' );
var GlobalUint8Array = require( './uint8array.js' );
// MAIN //
/**
* Tests for native `Uint8Array` support.
*
* @returns {boolean} boolean indicating if an environment has `Uint8Array` support
*
* @example
* var bool = hasUint8ArraySupport();
* // returns <boolean>
*/
function hasUint8ArraySupport() {
var bool;
var arr;
if ( typeof GlobalUint8Array !== 'function' ) {
return false;
}
// Test basic support...
try {
arr = [ 1, 3.14, -3.14, UINT8_MAX+1, UINT8_MAX+2 ];
arr = new GlobalUint8Array( arr );
bool = (
isUint8Array( arr ) &&
arr[ 0 ] === 1 &&
arr[ 1 ] === 3 && // truncation
arr[ 2 ] === UINT8_MAX-2 && // truncation and wrap around
arr[ 3 ] === 0 && // wrap around
arr[ 4 ] === 1 // wrap around
);
} catch ( err ) { // eslint-disable-line no-unused-vars
bool = false;
}
return bool;
}
// EXPORTS //
module.exports = hasUint8ArraySupport;
},{"./uint8array.js":67,"@stdlib/assert/is-uint8array":172,"@stdlib/constants/uint8/max":253}],67:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var main = ( typeof Uint8Array === 'function' ) ? Uint8Array : null; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = main;
},{}],68:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test for native `Uint8ClampedArray` support.
*
* @module @stdlib/assert/has-uint8clampedarray-support
*
* @example
* var hasUint8ClampedArraySupport = require( '@stdlib/assert/has-uint8clampedarray-support' );
*
* var bool = hasUint8ClampedArraySupport();
* // returns <boolean>
*/
// MODULES //
var hasUint8ClampedArraySupport = require( './main.js' );
// EXPORTS //
module.exports = hasUint8ClampedArraySupport;
},{"./main.js":69}],69:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isUint8ClampedArray = require( '@stdlib/assert/is-uint8clampedarray' );
var GlobalUint8ClampedArray = require( './uint8clampedarray.js' );
// MAIN //
/**
* Tests for native `Uint8ClampedArray` support.
*
* @returns {boolean} boolean indicating if an environment has `Uint8ClampedArray` support
*
* @example
* var bool = hasUint8ClampedArraySupport();
* // returns <boolean>
*/
function hasUint8ClampedArraySupport() { // eslint-disable-line id-length
var bool;
var arr;
if ( typeof GlobalUint8ClampedArray !== 'function' ) {
return false;
}
// Test basic support...
try {
arr = new GlobalUint8ClampedArray( [ -1, 0, 1, 3.14, 4.99, 255, 256 ] );
bool = (
isUint8ClampedArray( arr ) &&
arr[ 0 ] === 0 && // clamped
arr[ 1 ] === 0 &&
arr[ 2 ] === 1 &&
arr[ 3 ] === 3 && // round to nearest
arr[ 4 ] === 5 && // round to nearest
arr[ 5 ] === 255 &&
arr[ 6 ] === 255 // clamped
);
} catch ( err ) { // eslint-disable-line no-unused-vars
bool = false;
}
return bool;
}
// EXPORTS //
module.exports = hasUint8ClampedArraySupport;
},{"./uint8clampedarray.js":70,"@stdlib/assert/is-uint8clampedarray":174}],70:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var main = ( typeof Uint8ClampedArray === 'function' ) ? Uint8ClampedArray : null; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = main;
},{}],71:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test whether a value has in its prototype chain a specified constructor as a prototype property.
*
* @module @stdlib/assert/instance-of
*
* @example
* var instanceOf = require( '@stdlib/assert/instance-of' );
*
* var bool = instanceOf( [], Array );
* // returns true
*
* bool = instanceOf( {}, Object ); // exception
* // returns true
*
* bool = instanceOf( 'beep', String );
* // returns false
*
* bool = instanceOf( null, Object );
* // returns false
*
* bool = instanceOf( 5, Object );
* // returns false
*/
// MODULES //
var instanceOf = require( './main.js' );
// EXPORTS //
module.exports = instanceOf;
},{"./main.js":72}],72:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Tests whether a value has in its prototype chain a specified constructor as a prototype property.
*
* @param {*} value - value to test
* @param {Function} constructor - constructor to test against
* @throws {TypeError} constructor must be callable
* @returns {boolean} boolean indicating whether a value is an instance of a provided constructor
*
* @example
* var bool = instanceOf( [], Array );
* // returns true
*
* @example
* var bool = instanceOf( {}, Object ); // exception
* // returns true
*
* @example
* var bool = instanceOf( 'beep', String );
* // returns false
*
* @example
* var bool = instanceOf( null, Object );
* // returns false
*
* @example
* var bool = instanceOf( 5, Object );
* // returns false
*/
function instanceOf( value, constructor ) {
// TODO: replace with `isCallable` check
if ( typeof constructor !== 'function' ) {
throw new TypeError( 'invalid argument. `constructor` argument must be callable. Value: `'+constructor+'`.' );
}
return ( value instanceof constructor );
}
// EXPORTS //
module.exports = instanceOf;
},{}],73:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isArguments = require( './main.js' );
// VARIABLES //
var bool;
// FUNCTIONS //
/**
* Detects whether an environment returns the expected internal class of the `arguments` object.
*
* @private
* @returns {boolean} boolean indicating whether an environment behaves as expected
*
* @example
* var bool = detect();
* // returns <boolean>
*/
function detect() {
return isArguments( arguments );
}
// MAIN //
bool = detect();
// EXPORTS //
module.exports = bool;
},{"./main.js":75}],74:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is an `arguments` object.
*
* @module @stdlib/assert/is-arguments
*
* @example
* var isArguments = require( '@stdlib/assert/is-arguments' );
*
* function foo() {
* return arguments;
* }
*
* var bool = isArguments( foo() );
* // returns true
*
* bool = isArguments( [] );
* // returns false
*/
// MODULES //
var hasArgumentsClass = require( './detect.js' );
var main = require( './main.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var isArguments;
if ( hasArgumentsClass ) {
isArguments = main;
} else {
isArguments = polyfill;
}
// EXPORTS //
module.exports = isArguments;
},{"./detect.js":73,"./main.js":75,"./polyfill.js":76}],75:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var nativeClass = require( '@stdlib/utils/native-class' );
// MAIN //
/**
* Tests whether a value is an `arguments` object.
*
* @private
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether a value is an `arguments` object
*
* @example
* function foo() {
* return arguments;
* }
*
* var bool = isArguments( foo() );
* // returns true
*
* @example
* var bool = isArguments( [] );
* // returns false
*/
function isArguments( value ) {
return ( nativeClass( value ) === '[object Arguments]' );
}
// EXPORTS //
module.exports = isArguments;
},{"@stdlib/utils/native-class":393}],76:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var isEnumerableProperty = require( '@stdlib/assert/is-enumerable-property' );
var isArray = require( '@stdlib/assert/is-array' );
var isInteger = require( '@stdlib/math/base/assert/is-integer' );
var MAX_LENGTH = require( '@stdlib/constants/uint32/max' );
// MAIN //
/**
* Tests whether a value is an `arguments` object.
*
* @private
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether a value is an `arguments` object
*
* @example
* function foo() {
* return arguments;
* }
*
* var bool = isArguments( foo() );
* // returns true
*
* @example
* var bool = isArguments( [] );
* // returns false
*/
function isArguments( value ) {
return (
value !== null &&
typeof value === 'object' &&
!isArray( value ) &&
typeof value.length === 'number' &&
isInteger( value.length ) &&
value.length >= 0 &&
value.length <= MAX_LENGTH &&
hasOwnProp( value, 'callee' ) &&
!isEnumerableProperty( value, 'callee' )
);
}
// EXPORTS //
module.exports = isArguments;
},{"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-array":79,"@stdlib/assert/is-enumerable-property":93,"@stdlib/constants/uint32/max":252,"@stdlib/math/base/assert/is-integer":256}],77:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is array-like.
*
* @module @stdlib/assert/is-array-like
*
* @example
* var isArrayLike = require( '@stdlib/assert/is-array-like' );
*
* var bool = isArrayLike( [] );
* // returns true
*
* bool = isArrayLike( { 'length': 10 } );
* // returns true
*
* bool = isArrayLike( 'beep' );
* // returns true
*/
// MODULES //
var isArrayLike = require( './main.js' );
// EXPORTS //
module.exports = isArrayLike;
},{"./main.js":78}],78:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isInteger = require( '@stdlib/math/base/assert/is-integer' );
var MAX_LENGTH = require( '@stdlib/constants/array/max-array-length' );
// MAIN //
/**
* Tests if a value is array-like.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is array-like
*
* @example
* var bool = isArrayLike( [] );
* // returns true
*
* @example
* var bool = isArrayLike( {'length':10} );
* // returns true
*/
function isArrayLike( value ) {
return (
value !== void 0 &&
value !== null &&
typeof value !== 'function' &&
typeof value.length === 'number' &&
isInteger( value.length ) &&
value.length >= 0 &&
value.length <= MAX_LENGTH
);
}
// EXPORTS //
module.exports = isArrayLike;
},{"@stdlib/constants/array/max-array-length":235,"@stdlib/math/base/assert/is-integer":256}],79:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is an array.
*
* @module @stdlib/assert/is-array
*
* @example
* var isArray = require( '@stdlib/assert/is-array' );
*
* var bool = isArray( [] );
* // returns true
*
* bool = isArray( {} );
* // returns false
*/
// MODULES //
var isArray = require( './main.js' );
// EXPORTS //
module.exports = isArray;
},{"./main.js":80}],80:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var nativeClass = require( '@stdlib/utils/native-class' );
// VARIABLES //
var f;
// FUNCTIONS //
/**
* Tests if a value is an array.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is an array
*
* @example
* var bool = isArray( [] );
* // returns true
*
* @example
* var bool = isArray( {} );
* // returns false
*/
function isArray( value ) {
return ( nativeClass( value ) === '[object Array]' );
}
// MAIN //
if ( Array.isArray ) {
f = Array.isArray;
} else {
f = isArray;
}
// EXPORTS //
module.exports = f;
},{"@stdlib/utils/native-class":393}],81:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is a boolean.
*
* @module @stdlib/assert/is-boolean
*
* @example
* var isBoolean = require( '@stdlib/assert/is-boolean' );
*
* var bool = isBoolean( false );
* // returns true
*
* bool = isBoolean( new Boolean( false ) );
* // returns true
*
* @example
* // Use interface to check for boolean primitives...
* var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive;
*
* var bool = isBoolean( false );
* // returns true
*
* bool = isBoolean( new Boolean( true ) );
* // returns false
*
* @example
* // Use interface to check for boolean objects...
* var isBoolean = require( '@stdlib/assert/is-boolean' ).isObject;
*
* var bool = isBoolean( true );
* // returns false
*
* bool = isBoolean( new Boolean( false ) );
* // returns true
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var isBoolean = require( './main.js' );
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );
// MAIN //
setReadOnly( isBoolean, 'isPrimitive', isPrimitive );
setReadOnly( isBoolean, 'isObject', isObject );
// EXPORTS //
module.exports = isBoolean;
},{"./main.js":82,"./object.js":83,"./primitive.js":84,"@stdlib/utils/define-nonenumerable-read-only-property":344}],82:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );
// MAIN //
/**
* Tests if a value is a boolean.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is a boolean
*
* @example
* var bool = isBoolean( false );
* // returns true
*
* @example
* var bool = isBoolean( true );
* // returns true
*
* @example
* var bool = isBoolean( new Boolean( false ) );
* // returns true
*
* @example
* var bool = isBoolean( new Boolean( true ) );
* // returns true
*/
function isBoolean( value ) {
return ( isPrimitive( value ) || isObject( value ) );
}
// EXPORTS //
module.exports = isBoolean;
},{"./object.js":83,"./primitive.js":84}],83:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var hasToStringTag = require( '@stdlib/assert/has-tostringtag-support' );
var nativeClass = require( '@stdlib/utils/native-class' );
var test = require( './try2serialize.js' );
// VARIABLES //
var FLG = hasToStringTag();
// MAIN //
/**
* Tests if a value is a boolean object.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a boolean object
*
* @example
* var bool = isBoolean( true );
* // returns false
*
* @example
* var bool = isBoolean( new Boolean( false ) );
* // returns true
*/
function isBoolean( value ) {
if ( typeof value === 'object' ) {
if ( value instanceof Boolean ) {
return true;
}
if ( FLG ) {
return test( value );
}
return ( nativeClass( value ) === '[object Boolean]' );
}
return false;
}
// EXPORTS //
module.exports = isBoolean;
},{"./try2serialize.js":86,"@stdlib/assert/has-tostringtag-support":57,"@stdlib/utils/native-class":393}],84:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Tests if a value is a boolean primitive.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a boolean primitive
*
* @example
* var bool = isBoolean( true );
* // returns true
*
* @example
* var bool = isBoolean( false );
* // returns true
*
* @example
* var bool = isBoolean( new Boolean( true ) );
* // returns false
*/
function isBoolean( value ) {
return ( typeof value === 'boolean' );
}
// EXPORTS //
module.exports = isBoolean;
},{}],85:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// eslint-disable-next-line stdlib/no-redeclare
var toString = Boolean.prototype.toString; // non-generic
// EXPORTS //
module.exports = toString;
},{}],86:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var toString = require( './tostring.js' ); // eslint-disable-line stdlib/no-redeclare
// MAIN //
/**
* Attempts to serialize a value to a string.
*
* @private
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value can be serialized
*/
function test( value ) {
try {
toString.call( value );
return true;
} catch ( err ) { // eslint-disable-line no-unused-vars
return false;
}
}
// EXPORTS //
module.exports = test;
},{"./tostring.js":85}],87:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// EXPORTS //
module.exports = true;
},{}],88:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is a Buffer instance.
*
* @module @stdlib/assert/is-buffer
*
* @example
* var isBuffer = require( '@stdlib/assert/is-buffer' );
*
* var v = isBuffer( new Buffer( 'beep' ) );
* // returns true
*
* v = isBuffer( {} );
* // returns false
*/
// MODULES //
var isBuffer = require( './main.js' );
// EXPORTS //
module.exports = isBuffer;
},{"./main.js":89}],89:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isObjectLike = require( '@stdlib/assert/is-object-like' );
// MAIN //
/**
* Tests if a value is a Buffer instance.
*
* @param {*} value - value to validate
* @returns {boolean} boolean indicating if a value is a Buffer instance
*
* @example
* var v = isBuffer( new Buffer( 'beep' ) );
* // returns true
*
* @example
* var v = isBuffer( new Buffer( [1,2,3,4] ) );
* // returns true
*
* @example
* var v = isBuffer( {} );
* // returns false
*
* @example
* var v = isBuffer( [] );
* // returns false
*/
function isBuffer( value ) {
return (
isObjectLike( value ) &&
(
// eslint-disable-next-line no-underscore-dangle
value._isBuffer || // for envs missing Object.prototype.constructor (e.g., Safari 5-7)
(
value.constructor &&
// WARNING: `typeof` is not a foolproof check, as certain envs consider RegExp and NodeList instances to be functions
typeof value.constructor.isBuffer === 'function' &&
value.constructor.isBuffer( value )
)
)
);
}
// EXPORTS //
module.exports = isBuffer;
},{"@stdlib/assert/is-object-like":143}],90:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is a collection.
*
* @module @stdlib/assert/is-collection
*
* @example
* var isCollection = require( '@stdlib/assert/is-collection' );
*
* var bool = isCollection( [] );
* // returns true
*
* bool = isCollection( {} );
* // returns false
*/
// MODULES //
var isCollection = require( './main.js' );
// EXPORTS //
module.exports = isCollection;
},{"./main.js":91}],91:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isInteger = require( '@stdlib/math/base/assert/is-integer' );
var MAX_LENGTH = require( '@stdlib/constants/array/max-typed-array-length' );
// MAIN //
/**
* Tests if a value is a collection.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether a value is a collection
*
* @example
* var bool = isCollection( [] );
* // returns true
*
* @example
* var bool = isCollection( {} );
* // returns false
*/
function isCollection( value ) {
return (
typeof value === 'object' &&
value !== null &&
typeof value.length === 'number' &&
isInteger( value.length ) &&
value.length >= 0 &&
value.length <= MAX_LENGTH
);
}
// EXPORTS //
module.exports = isCollection;
},{"@stdlib/constants/array/max-typed-array-length":236,"@stdlib/math/base/assert/is-integer":256}],92:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isEnum = require( './native.js' );
// VARIABLES //
var bool;
// FUNCTIONS //
/**
* Detects whether an environment has a bug where String indices are not detected as "enumerable" properties. Observed in Node v0.10.
*
* @private
* @returns {boolean} boolean indicating whether an environment has the bug
*/
function detect() {
return !isEnum.call( 'beep', '0' );
}
// MAIN //
bool = detect();
// EXPORTS //
module.exports = bool;
},{"./native.js":95}],93:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test whether an object's own property is enumerable.
*
* @module @stdlib/assert/is-enumerable-property
*
* @example
* var isEnumerableProperty = require( '@stdlib/assert/is-enumerable-property' );
*
* var beep = {
* 'boop': true
* };
*
* var bool = isEnumerableProperty( beep, 'boop' );
* // returns true
*
* bool = isEnumerableProperty( beep, 'hasOwnProperty' );
* // returns false
*/
// MODULES //
var isEnumerableProperty = require( './main.js' );
// EXPORTS //
module.exports = isEnumerableProperty;
},{"./main.js":94}],94:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isString = require( '@stdlib/assert/is-string' );
var isnan = require( '@stdlib/assert/is-nan' ).isPrimitive;
var isInteger = require( '@stdlib/assert/is-integer' ).isPrimitive;
var isEnum = require( './native.js' );
var hasStringEnumBug = require( './has_string_enumerability_bug.js' );
// MAIN //
/**
* Tests if an object's own property is enumerable.
*
* @param {*} value - value to test
* @param {*} property - property to test
* @returns {boolean} boolean indicating if an object property is enumerable
*
* @example
* var beep = {
* 'boop': true
* };
*
* var bool = isEnumerableProperty( beep, 'boop' );
* // returns true
*
* @example
* var beep = {
* 'boop': true
* };
*
* var bool = isEnumerableProperty( beep, 'hasOwnProperty' );
* // returns false
*/
function isEnumerableProperty( value, property ) {
var bool;
if (
value === void 0 ||
value === null
) {
return false;
}
bool = isEnum.call( value, property );
if ( !bool && hasStringEnumBug && isString( value ) ) {
// Note: we only check for indices, as properties attached to a `String` object are properly detected as enumerable above.
property = +property;
return (
!isnan( property ) &&
isInteger( property ) &&
property >= 0 &&
property < value.length
);
}
return bool;
}
// EXPORTS //
module.exports = isEnumerableProperty;
},{"./has_string_enumerability_bug.js":92,"./native.js":95,"@stdlib/assert/is-integer":110,"@stdlib/assert/is-nan":118,"@stdlib/assert/is-string":158}],95:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Tests if an object's own property is enumerable.
*
* @private
* @name isEnumerableProperty
* @type {Function}
* @param {*} value - value to test
* @param {*} property - property to test
* @returns {boolean} boolean indicating if an object property is enumerable
*
* @example
* var beep = {
* 'boop': true
* };
*
* var bool = isEnumerableProperty( beep, 'boop' );
* // returns true
*
* @example
* var beep = {
* 'boop': true
* };
*
* var bool = isEnumerableProperty( beep, 'hasOwnProperty' );
* // returns false
*/
var isEnumerableProperty = Object.prototype.propertyIsEnumerable;
// EXPORTS //
module.exports = isEnumerableProperty;
},{}],96:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is an `Error` object.
*
* @module @stdlib/assert/is-error
*
* @example
* var isError = require( '@stdlib/assert/is-error' );
*
* var bool = isError( new Error( 'beep' ) );
* // returns true
*
* bool = isError( {} );
* // returns false
*/
// MODULES //
var isError = require( './main.js' );
// EXPORTS //
module.exports = isError;
},{"./main.js":97}],97:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var getPrototypeOf = require( '@stdlib/utils/get-prototype-of' );
var nativeClass = require( '@stdlib/utils/native-class' );
// MAIN //
/**
* Tests if a value is an `Error` object.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether a value is an `Error` object
*
* @example
* var bool = isError( new Error( 'beep' ) );
* // returns true
*
* @example
* var bool = isError( {} );
* // returns false
*/
function isError( value ) {
if ( typeof value !== 'object' || value === null ) {
return false;
}
// Check for `Error` objects from the same realm (same Node.js `vm` or same `Window` object)...
if ( value instanceof Error ) {
return true;
}
// Walk the prototype tree until we find an object having the desired native class...
while ( value ) {
if ( nativeClass( value ) === '[object Error]' ) {
return true;
}
value = getPrototypeOf( value );
}
return false;
}
// EXPORTS //
module.exports = isError;
},{"@stdlib/utils/get-prototype-of":359,"@stdlib/utils/native-class":393}],98:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is a Float32Array.
*
* @module @stdlib/assert/is-float32array
*
* @example
* var isFloat32Array = require( '@stdlib/assert/is-float32array' );
*
* var bool = isFloat32Array( new Float32Array( 10 ) );
* // returns true
*
* bool = isFloat32Array( [] );
* // returns false
*/
// MODULES //
var isFloat32Array = require( './main.js' );
// EXPORTS //
module.exports = isFloat32Array;
},{"./main.js":99}],99:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var nativeClass = require( '@stdlib/utils/native-class' );
// VARIABLES //
var hasFloat32Array = ( typeof Float32Array === 'function' );// eslint-disable-line stdlib/require-globals
// MAIN //
/**
* Tests if a value is a Float32Array.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is a Float32Array
*
* @example
* var bool = isFloat32Array( new Float32Array( 10 ) );
* // returns true
*
* @example
* var bool = isFloat32Array( [] );
* // returns false
*/
function isFloat32Array( value ) {
return (
( hasFloat32Array && value instanceof Float32Array ) || // eslint-disable-line stdlib/require-globals
nativeClass( value ) === '[object Float32Array]'
);
}
// EXPORTS //
module.exports = isFloat32Array;
},{"@stdlib/utils/native-class":393}],100:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is a Float64Array.
*
* @module @stdlib/assert/is-float64array
*
* @example
* var isFloat64Array = require( '@stdlib/assert/is-float64array' );
*
* var bool = isFloat64Array( new Float64Array( 10 ) );
* // returns true
*
* bool = isFloat64Array( [] );
* // returns false
*/
// MODULES //
var isFloat64Array = require( './main.js' );
// EXPORTS //
module.exports = isFloat64Array;
},{"./main.js":101}],101:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var nativeClass = require( '@stdlib/utils/native-class' );
// VARIABLES //
var hasFloat64Array = ( typeof Float64Array === 'function' ); // eslint-disable-line stdlib/require-globals
// MAIN //
/**
* Tests if a value is a Float64Array.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is a Float64Array
*
* @example
* var bool = isFloat64Array( new Float64Array( 10 ) );
* // returns true
*
* @example
* var bool = isFloat64Array( [] );
* // returns false
*/
function isFloat64Array( value ) {
return (
( hasFloat64Array && value instanceof Float64Array ) || // eslint-disable-line stdlib/require-globals
nativeClass( value ) === '[object Float64Array]'
);
}
// EXPORTS //
module.exports = isFloat64Array;
},{"@stdlib/utils/native-class":393}],102:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is a function.
*
* @module @stdlib/assert/is-function
*
* @example
* var isFunction = require( '@stdlib/assert/is-function' );
*
* function beep() {
* return 'beep';
* }
*
* var bool = isFunction( beep );
* // returns true
*/
// MODULES //
var isFunction = require( './main.js' );
// EXPORTS //
module.exports = isFunction;
},{"./main.js":103}],103:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var typeOf = require( '@stdlib/utils/type-of' );
// MAIN //
/**
* Tests if a value is a function.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is a function
*
* @example
* function beep() {
* return 'beep';
* }
*
* var bool = isFunction( beep );
* // returns true
*/
function isFunction( value ) {
// Note: cannot use `typeof` directly, as various browser engines incorrectly return `'function'` when operating on non-function objects, such as regular expressions and NodeLists.
return ( typeOf( value ) === 'function' );
}
// EXPORTS //
module.exports = isFunction;
},{"@stdlib/utils/type-of":420}],104:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is an Int16Array.
*
* @module @stdlib/assert/is-int16array
*
* @example
* var isInt16Array = require( '@stdlib/assert/is-int16array' );
*
* var bool = isInt16Array( new Int16Array( 10 ) );
* // returns true
*
* bool = isInt16Array( [] );
* // returns false
*/
// MODULES //
var isInt16Array = require( './main.js' );
// EXPORTS //
module.exports = isInt16Array;
},{"./main.js":105}],105:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var nativeClass = require( '@stdlib/utils/native-class' );
// VARIABLES //
var hasInt16Array = ( typeof Int16Array === 'function' ); // eslint-disable-line stdlib/require-globals
// MAIN //
/**
* Tests if a value is an Int16Array.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is an Int16Array
*
* @example
* var bool = isInt16Array( new Int16Array( 10 ) );
* // returns true
*
* @example
* var bool = isInt16Array( [] );
* // returns false
*/
function isInt16Array( value ) {
return (
( hasInt16Array && value instanceof Int16Array ) || // eslint-disable-line stdlib/require-globals
nativeClass( value ) === '[object Int16Array]'
);
}
// EXPORTS //
module.exports = isInt16Array;
},{"@stdlib/utils/native-class":393}],106:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is an Int32Array.
*
* @module @stdlib/assert/is-int32array
*
* @example
* var isInt32Array = require( '@stdlib/assert/is-int32array' );
*
* var bool = isInt32Array( new Int32Array( 10 ) );
* // returns true
*
* bool = isInt32Array( [] );
* // returns false
*/
// MODULES //
var isInt32Array = require( './main.js' );
// EXPORTS //
module.exports = isInt32Array;
},{"./main.js":107}],107:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var nativeClass = require( '@stdlib/utils/native-class' );
// VARIABLES //
var hasInt32Array = ( typeof Int32Array === 'function' ); // eslint-disable-line stdlib/require-globals
// MAIN //
/**
* Tests if a value is an Int32Array.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is an Int32Array
*
* @example
* var bool = isInt32Array( new Int32Array( 10 ) );
* // returns true
*
* @example
* var bool = isInt32Array( [] );
* // returns false
*/
function isInt32Array( value ) {
return (
( hasInt32Array && value instanceof Int32Array ) || // eslint-disable-line stdlib/require-globals
nativeClass( value ) === '[object Int32Array]'
);
}
// EXPORTS //
module.exports = isInt32Array;
},{"@stdlib/utils/native-class":393}],108:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is an Int8Array.
*
* @module @stdlib/assert/is-int8array
*
* @example
* var isInt8Array = require( '@stdlib/assert/is-int8array' );
*
* var bool = isInt8Array( new Int8Array( 10 ) );
* // returns true
*
* bool = isInt8Array( [] );
* // returns false
*/
// MODULES //
var isInt8Array = require( './main.js' );
// EXPORTS //
module.exports = isInt8Array;
},{"./main.js":109}],109:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var nativeClass = require( '@stdlib/utils/native-class' );
// VARIABLES //
var hasInt8Array = ( typeof Int8Array === 'function' ); // eslint-disable-line stdlib/require-globals
// MAIN //
/**
* Tests if a value is an Int8Array.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is an Int8Array
*
* @example
* var bool = isInt8Array( new Int8Array( 10 ) );
* // returns true
*
* @example
* var bool = isInt8Array( [] );
* // returns false
*/
function isInt8Array( value ) {
return (
( hasInt8Array && value instanceof Int8Array ) || // eslint-disable-line stdlib/require-globals
nativeClass( value ) === '[object Int8Array]'
);
}
// EXPORTS //
module.exports = isInt8Array;
},{"@stdlib/utils/native-class":393}],110:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is an integer.
*
* @module @stdlib/assert/is-integer
*
* @example
* var isInteger = require( '@stdlib/assert/is-integer' );
*
* var bool = isInteger( 5.0 );
* // returns true
*
* bool = isInteger( new Number( 5.0 ) );
* // returns true
*
* bool = isInteger( -3.14 );
* // returns false
*
* bool = isInteger( null );
* // returns false
*
* @example
* // Use interface to check for integer primitives...
* var isInteger = require( '@stdlib/assert/is-integer' ).isPrimitive;
*
* var bool = isInteger( -3.0 );
* // returns true
*
* bool = isInteger( new Number( -3.0 ) );
* // returns false
*
* @example
* // Use interface to check for integer objects...
* var isInteger = require( '@stdlib/assert/is-integer' ).isObject;
*
* var bool = isInteger( 3.0 );
* // returns false
*
* bool = isInteger( new Number( 3.0 ) );
* // returns true
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var isInteger = require( './main.js' );
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );
// MAIN //
setReadOnly( isInteger, 'isPrimitive', isPrimitive );
setReadOnly( isInteger, 'isObject', isObject );
// EXPORTS //
module.exports = isInteger;
},{"./main.js":112,"./object.js":113,"./primitive.js":114,"@stdlib/utils/define-nonenumerable-read-only-property":344}],111:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var PINF = require( '@stdlib/constants/float64/pinf' );
var NINF = require( '@stdlib/constants/float64/ninf' );
var isInt = require( '@stdlib/math/base/assert/is-integer' );
// MAIN //
/**
* Tests if a number primitive is an integer value.
*
* @private
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a number primitive is an integer value
*/
function isInteger( value ) {
return (
value < PINF &&
value > NINF &&
isInt( value )
);
}
// EXPORTS //
module.exports = isInteger;
},{"@stdlib/constants/float64/ninf":243,"@stdlib/constants/float64/pinf":244,"@stdlib/math/base/assert/is-integer":256}],112:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );
// MAIN //
/**
* Tests if a value is an integer.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is an integer
*
* @example
* var bool = isInteger( 5.0 );
* // returns true
*
* @example
* var bool = isInteger( new Number( 5.0 ) );
* // returns true
*
* @example
* var bool = isInteger( -3.14 );
* // returns false
*
* @example
* var bool = isInteger( null );
* // returns false
*/
function isInteger( value ) {
return ( isPrimitive( value ) || isObject( value ) );
}
// EXPORTS //
module.exports = isInteger;
},{"./object.js":113,"./primitive.js":114}],113:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isNumber = require( '@stdlib/assert/is-number' ).isObject;
var isInt = require( './integer.js' );
// MAIN //
/**
* Tests if a value is a number object having an integer value.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a number object having an integer value
*
* @example
* var bool = isInteger( 3.0 );
* // returns false
*
* @example
* var bool = isInteger( new Number( 3.0 ) );
* // returns true
*/
function isInteger( value ) {
return (
isNumber( value ) &&
isInt( value.valueOf() )
);
}
// EXPORTS //
module.exports = isInteger;
},{"./integer.js":111,"@stdlib/assert/is-number":137}],114:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isNumber = require( '@stdlib/assert/is-number' ).isPrimitive;
var isInt = require( './integer.js' );
// MAIN //
/**
* Tests if a value is a number primitive having an integer value.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a number primitive having an integer value
*
* @example
* var bool = isInteger( -3.0 );
* // returns true
*
* @example
* var bool = isInteger( new Number( -3.0 ) );
* // returns false
*/
function isInteger( value ) {
return (
isNumber( value ) &&
isInt( value )
);
}
// EXPORTS //
module.exports = isInteger;
},{"./integer.js":111,"@stdlib/assert/is-number":137}],115:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var Uint8Array = require( '@stdlib/array/uint8' );
var Uint16Array = require( '@stdlib/array/uint16' );
// MAIN //
var ctors = {
'uint16': Uint16Array,
'uint8': Uint8Array
};
// EXPORTS //
module.exports = ctors;
},{"@stdlib/array/uint16":20,"@stdlib/array/uint8":26}],116:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Return a boolean indicating if an environment is little endian.
*
* @module @stdlib/assert/is-little-endian
*
* @example
* var IS_LITTLE_ENDIAN = require( '@stdlib/assert/is-little-endian' );
*
* var bool = IS_LITTLE_ENDIAN;
* // returns <boolean>
*/
// MODULES //
var IS_LITTLE_ENDIAN = require( './main.js' );
// EXPORTS //
module.exports = IS_LITTLE_ENDIAN;
},{"./main.js":117}],117:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var ctors = require( './ctors.js' );
// VARIABLES //
var bool;
// FUNCTIONS //
/**
* Returns a boolean indicating if an environment is little endian.
*
* @private
* @returns {boolean} boolean indicating if an environment is little endian
*
* @example
* var bool = isLittleEndian();
* // returns <boolean>
*/
function isLittleEndian() {
var uint16view;
var uint8view;
uint16view = new ctors[ 'uint16' ]( 1 );
/*
* Set the uint16 view to a value having distinguishable lower and higher order words.
*
* 4660 => 0x1234 => 0x12 0x34 => '00010010 00110100' => (0x12,0x34) == (18,52)
*/
uint16view[ 0 ] = 0x1234;
// Create a uint8 view on top of the uint16 buffer:
uint8view = new ctors[ 'uint8' ]( uint16view.buffer );
// If little endian, the least significant byte will be first...
return ( uint8view[ 0 ] === 0x34 );
}
// MAIN //
bool = isLittleEndian();
// EXPORTS //
module.exports = bool;
},{"./ctors.js":115}],118:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is `NaN`.
*
* @module @stdlib/assert/is-nan
*
* @example
* var isnan = require( '@stdlib/assert/is-nan' );
*
* var bool = isnan( NaN );
* // returns true
*
* bool = isnan( new Number( NaN ) );
* // returns true
*
* bool = isnan( 3.14 );
* // returns false
*
* bool = isnan( null );
* // returns false
*
* @example
* var isnan = require( '@stdlib/assert/is-nan' ).isPrimitive;
*
* var bool = isnan( NaN );
* // returns true
*
* bool = isnan( 3.14 );
* // returns false
*
* bool = isnan( new Number( NaN ) );
* // returns false
*
* @example
* var isnan = require( '@stdlib/assert/is-nan' ).isObject;
*
* var bool = isnan( NaN );
* // returns false
*
* bool = isnan( new Number( NaN ) );
* // returns true
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var isnan = require( './main.js' );
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );
// MAIN //
setReadOnly( isnan, 'isPrimitive', isPrimitive );
setReadOnly( isnan, 'isObject', isObject );
// EXPORTS //
module.exports = isnan;
},{"./main.js":119,"./object.js":120,"./primitive.js":121,"@stdlib/utils/define-nonenumerable-read-only-property":344}],119:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );
// MAIN //
/**
* Tests if a value is `NaN`.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is `NaN`
*
* @example
* var bool = isnan( NaN );
* // returns true
*
* @example
* var bool = isnan( new Number( NaN ) );
* // returns true
*
* @example
* var bool = isnan( 3.14 );
* // returns false
*
* @example
* var bool = isnan( null );
* // returns false
*/
function isnan( value ) {
return ( isPrimitive( value ) || isObject( value ) );
}
// EXPORTS //
module.exports = isnan;
},{"./object.js":120,"./primitive.js":121}],120:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isNumber = require( '@stdlib/assert/is-number' ).isObject;
var isNan = require( '@stdlib/math/base/assert/is-nan' );
// MAIN //
/**
* Tests if a value is a number object having a value of `NaN`.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a number object having a value of `NaN`
*
* @example
* var bool = isnan( NaN );
* // returns false
*
* @example
* var bool = isnan( new Number( NaN ) );
* // returns true
*/
function isnan( value ) {
return (
isNumber( value ) &&
isNan( value.valueOf() )
);
}
// EXPORTS //
module.exports = isnan;
},{"@stdlib/assert/is-number":137,"@stdlib/math/base/assert/is-nan":258}],121:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isNumber = require( '@stdlib/assert/is-number' ).isPrimitive;
var isNan = require( '@stdlib/math/base/assert/is-nan' );
// MAIN //
/**
* Tests if a value is a `NaN` number primitive.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a `NaN` number primitive
*
* @example
* var bool = isnan( NaN );
* // returns true
*
* @example
* var bool = isnan( 3.14 );
* // returns false
*
* @example
* var bool = isnan( new Number( NaN ) );
* // returns false
*/
function isnan( value ) {
return (
isNumber( value ) &&
isNan( value )
);
}
// EXPORTS //
module.exports = isnan;
},{"@stdlib/assert/is-number":137,"@stdlib/math/base/assert/is-nan":258}],122:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is Node stream-like.
*
* @module @stdlib/assert/is-node-stream-like
*
* @example
* var transformStream = require( '@stdlib/streams/node/transform' );
* var isNodeStreamLike = require( '@stdlib/assert/is-node-stream-like' );
*
* var stream = transformStream();
*
* var bool = isNodeStreamLike( stream );
* // returns true
*
* bool = isNodeStreamLike( {} );
* // returns false
*/
// MODULES //
var isNodeStreamLike = require( './main.js' );
// EXPORTS //
module.exports = isNodeStreamLike;
},{"./main.js":123}],123:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Tests if a value is Node stream-like.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is Node stream-like
*
* @example
* var transformStream = require( '@stdlib/streams/node/transform' );
*
* var stream = transformStream();
*
* var bool = isNodeStreamLike( stream );
* // returns true
*
* bool = isNodeStreamLike( {} );
* // returns false
*/
function isNodeStreamLike( value ) {
return (
// Must be an object:
value !== null &&
typeof value === 'object' &&
// Should be an event emitter:
typeof value.on === 'function' &&
typeof value.once === 'function' &&
typeof value.emit === 'function' &&
typeof value.addListener === 'function' &&
typeof value.removeListener === 'function' &&
typeof value.removeAllListeners === 'function' &&
// Should have a `pipe` method (Node streams inherit from `Stream`, including writable streams):
typeof value.pipe === 'function'
);
}
// EXPORTS //
module.exports = isNodeStreamLike;
},{}],124:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is Node writable stream-like.
*
* @module @stdlib/assert/is-node-writable-stream-like
*
* @example
* var transformStream = require( '@stdlib/streams/node/transform' );
* var isNodeWritableStreamLike = require( '@stdlib/assert/is-node-writable-stream-like' );
*
* var stream = transformStream();
*
* var bool = isNodeWritableStreamLike( stream );
* // returns true
*
* bool = isNodeWritableStreamLike( {} );
* // returns false
*/
// MODULES //
var isNodeWritableStreamLike = require( './main.js' );
// EXPORTS //
module.exports = isNodeWritableStreamLike;
},{"./main.js":125}],125:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
/* eslint-disable no-underscore-dangle */
'use strict';
// MODULES //
var isNodeStreamLike = require( '@stdlib/assert/is-node-stream-like' );
// MAIN //
/**
* Tests if a value is Node writable stream-like.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is Node writable stream-like
*
* @example
* var transformStream = require( '@stdlib/streams/node/transform' );
*
* var stream = transformStream();
*
* var bool = isNodeWritableStreamLike( stream );
* // returns true
*
* bool = isNodeWritableStreamLike( {} );
* // returns false
*/
function isNodeWritableStreamLike( value ) {
return (
// Must be stream-like:
isNodeStreamLike( value ) &&
// Should have writable stream methods:
typeof value._write === 'function' &&
// Should have writable stream state:
typeof value._writableState === 'object'
);
}
// EXPORTS //
module.exports = isNodeWritableStreamLike;
},{"@stdlib/assert/is-node-stream-like":122}],126:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is an array-like object containing only nonnegative integers.
*
* @module @stdlib/assert/is-nonnegative-integer-array
*
* @example
* var isNonNegativeIntegerArray = require( '@stdlib/assert/is-nonnegative-integer-array' );
*
* var bool = isNonNegativeIntegerArray( [ 3.0, new Number(3.0) ] );
* // returns true
*
* bool = isNonNegativeIntegerArray( [ 3.0, '3.0' ] );
* // returns false
*
* @example
* var isNonNegativeIntegerArray = require( '@stdlib/assert/is-nonnegative-integer-array' ).primitives;
*
* var bool = isNonNegativeIntegerArray( [ 1.0, 0.0, 10.0 ] );
* // returns true
*
* bool = isNonNegativeIntegerArray( [ 3.0, new Number(1.0) ] );
* // returns false
*
* @example
* var isNonNegativeIntegerArray = require( '@stdlib/assert/is-nonnegative-integer-array' ).objects;
*
* var bool = isNonNegativeIntegerArray( [ new Number(3.0), new Number(1.0) ] );
* // returns true
*
* bool = isNonNegativeIntegerArray( [ 1.0, 0.0, 10.0 ] );
* // returns false
*/
// MODULES //
var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' );
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var arrayfun = require( '@stdlib/assert/tools/array-like-function' );
// MAIN //
var isNonNegativeIntegerArray = arrayfun( isNonNegativeInteger );
setReadOnly( isNonNegativeIntegerArray, 'primitives', arrayfun( isNonNegativeInteger.isPrimitive ) );
setReadOnly( isNonNegativeIntegerArray, 'objects', arrayfun( isNonNegativeInteger.isObject ) );
// EXPORTS //
module.exports = isNonNegativeIntegerArray;
},{"@stdlib/assert/is-nonnegative-integer":127,"@stdlib/assert/tools/array-like-function":179,"@stdlib/utils/define-nonenumerable-read-only-property":344}],127:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is a nonnegative integer.
*
* @module @stdlib/assert/is-nonnegative-integer
*
* @example
* var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' );
*
* var bool = isNonNegativeInteger( 5.0 );
* // returns true
*
* bool = isNonNegativeInteger( new Number( 5.0 ) );
* // returns true
*
* bool = isNonNegativeInteger( -5.0 );
* // returns false
*
* bool = isNonNegativeInteger( 3.14 );
* // returns false
*
* bool = isNonNegativeInteger( null );
* // returns false
*
* @example
* var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ).isPrimitive;
*
* var bool = isNonNegativeInteger( 3.0 );
* // returns true
*
* bool = isNonNegativeInteger( new Number( 3.0 ) );
* // returns false
*
* @example
* var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ).isObject;
*
* var bool = isNonNegativeInteger( 3.0 );
* // returns false
*
* bool = isNonNegativeInteger( new Number( 3.0 ) );
* // returns true
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var isNonNegativeInteger = require( './main.js' );
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );
// MAIN //
setReadOnly( isNonNegativeInteger, 'isPrimitive', isPrimitive );
setReadOnly( isNonNegativeInteger, 'isObject', isObject );
// EXPORTS //
module.exports = isNonNegativeInteger;
},{"./main.js":128,"./object.js":129,"./primitive.js":130,"@stdlib/utils/define-nonenumerable-read-only-property":344}],128:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );
// MAIN //
/**
* Tests if a value is a nonnegative integer.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is a nonnegative integer
*
* @example
* var bool = isNonNegativeInteger( 5.0 );
* // returns true
*
* @example
* var bool = isNonNegativeInteger( new Number( 5.0 ) );
* // returns true
*
* @example
* var bool = isNonNegativeInteger( -5.0 );
* // returns false
*
* @example
* var bool = isNonNegativeInteger( 3.14 );
* // returns false
*
* @example
* var bool = isNonNegativeInteger( null );
* // returns false
*/
function isNonNegativeInteger( value ) {
return ( isPrimitive( value ) || isObject( value ) );
}
// EXPORTS //
module.exports = isNonNegativeInteger;
},{"./object.js":129,"./primitive.js":130}],129:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isInteger = require( '@stdlib/assert/is-integer' ).isObject;
// MAIN //
/**
* Tests if a value is a number object having a nonnegative integer value.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a number object having a nonnegative integer value
*
* @example
* var bool = isNonNegativeInteger( 3.0 );
* // returns false
*
* @example
* var bool = isNonNegativeInteger( new Number( 3.0 ) );
* // returns true
*/
function isNonNegativeInteger( value ) {
return (
isInteger( value ) &&
value.valueOf() >= 0
);
}
// EXPORTS //
module.exports = isNonNegativeInteger;
},{"@stdlib/assert/is-integer":110}],130:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isInteger = require( '@stdlib/assert/is-integer' ).isPrimitive;
// MAIN //
/**
* Tests if a value is a number primitive having a nonnegative integer value.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a number primitive having a nonnegative integer value
*
* @example
* var bool = isNonNegativeInteger( 3.0 );
* // returns true
*
* @example
* var bool = isNonNegativeInteger( new Number( 3.0 ) );
* // returns false
*/
function isNonNegativeInteger( value ) {
return (
isInteger( value ) &&
value >= 0
);
}
// EXPORTS //
module.exports = isNonNegativeInteger;
},{"@stdlib/assert/is-integer":110}],131:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is a nonnegative number.
*
* @module @stdlib/assert/is-nonnegative-number
*
* @example
* var isNonNegativeNumber = require( '@stdlib/assert/is-nonnegative-number' );
*
* var bool = isNonNegativeNumber( 5.0 );
* // returns true
*
* bool = isNonNegativeNumber( new Number( 5.0 ) );
* // returns true
*
* bool = isNonNegativeNumber( 3.14 );
* // returns true
*
* bool = isNonNegativeNumber( -5.0 );
* // returns false
*
* bool = isNonNegativeNumber( null );
* // returns false
*
* @example
* var isNonNegativeNumber = require( '@stdlib/assert/is-nonnegative-number' ).isPrimitive;
*
* var bool = isNonNegativeNumber( 3.0 );
* // returns true
*
* bool = isNonNegativeNumber( new Number( 3.0 ) );
* // returns false
*
* @example
* var isNonNegativeNumber = require( '@stdlib/assert/is-nonnegative-number' ).isObject;
*
* var bool = isNonNegativeNumber( 3.0 );
* // returns false
*
* bool = isNonNegativeNumber( new Number( 3.0 ) );
* // returns true
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var isNonNegativeNumber = require( './main.js' );
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );
// MAIN //
setReadOnly( isNonNegativeNumber, 'isPrimitive', isPrimitive );
setReadOnly( isNonNegativeNumber, 'isObject', isObject );
// EXPORTS //
module.exports = isNonNegativeNumber;
},{"./main.js":132,"./object.js":133,"./primitive.js":134,"@stdlib/utils/define-nonenumerable-read-only-property":344}],132:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );
// MAIN //
/**
* Tests if a value is a nonnegative number.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is a nonnegative number
*
* @example
* var bool = isNonNegativeNumber( 5.0 );
* // returns true
*
* @example
* var bool = isNonNegativeNumber( new Number( 5.0 ) );
* // returns true
*
* @example
* var bool = isNonNegativeNumber( 3.14 );
* // returns true
*
* @example
* var bool = isNonNegativeNumber( -5.0 );
* // returns false
*
* @example
* var bool = isNonNegativeNumber( null );
* // returns false
*/
function isNonNegativeNumber( value ) {
return ( isPrimitive( value ) || isObject( value ) );
}
// EXPORTS //
module.exports = isNonNegativeNumber;
},{"./object.js":133,"./primitive.js":134}],133:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isNumber = require( '@stdlib/assert/is-number' ).isObject;
// MAIN //
/**
* Tests if a value is a number object having a nonnegative value.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a number object having a nonnegative number value
*
* @example
* var bool = isNonNegativeNumber( 3.0 );
* // returns false
*
* @example
* var bool = isNonNegativeNumber( new Number( 3.0 ) );
* // returns true
*/
function isNonNegativeNumber( value ) {
return (
isNumber( value ) &&
value.valueOf() >= 0.0
);
}
// EXPORTS //
module.exports = isNonNegativeNumber;
},{"@stdlib/assert/is-number":137}],134:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isNumber = require( '@stdlib/assert/is-number' ).isPrimitive;
// MAIN //
/**
* Tests if a value is a number primitive having a nonnegative value.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a number primitive having a nonnegative number value
*
* @example
* var bool = isNonNegativeNumber( 3.0 );
* // returns true
*
* @example
* var bool = isNonNegativeNumber( new Number( 3.0 ) );
* // returns false
*/
function isNonNegativeNumber( value ) {
return (
isNumber( value ) &&
value >= 0.0
);
}
// EXPORTS //
module.exports = isNonNegativeNumber;
},{"@stdlib/assert/is-number":137}],135:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is `null`.
*
* @module @stdlib/assert/is-null
*
* @example
* var isNull = require( '@stdlib/assert/is-null' );
*
* var value = null;
*
* var bool = isNull( value );
* // returns true
*/
// MODULES //
var isNull = require( './main.js' );
// EXPORTS //
module.exports = isNull;
},{"./main.js":136}],136:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Tests if a value is `null`.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is null
*
* @example
* var bool = isNull( null );
* // returns true
*
* bool = isNull( true );
* // returns false
*/
function isNull( value ) {
return value === null;
}
// EXPORTS //
module.exports = isNull;
},{}],137:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is a number.
*
* @module @stdlib/assert/is-number
*
* @example
* var isNumber = require( '@stdlib/assert/is-number' );
*
* var bool = isNumber( 3.14 );
* // returns true
*
* bool = isNumber( new Number( 3.14 ) );
* // returns true
*
* bool = isNumber( NaN );
* // returns true
*
* bool = isNumber( null );
* // returns false
*
* @example
* var isNumber = require( '@stdlib/assert/is-number' ).isPrimitive;
*
* var bool = isNumber( 3.14 );
* // returns true
*
* bool = isNumber( NaN );
* // returns true
*
* bool = isNumber( new Number( 3.14 ) );
* // returns false
*
* @example
* var isNumber = require( '@stdlib/assert/is-number' ).isObject;
*
* var bool = isNumber( 3.14 );
* // returns false
*
* bool = isNumber( new Number( 3.14 ) );
* // returns true
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var isNumber = require( './main.js' );
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );
// MAIN //
setReadOnly( isNumber, 'isPrimitive', isPrimitive );
setReadOnly( isNumber, 'isObject', isObject );
// EXPORTS //
module.exports = isNumber;
},{"./main.js":138,"./object.js":139,"./primitive.js":140,"@stdlib/utils/define-nonenumerable-read-only-property":344}],138:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );
// MAIN //
/**
* Tests if a value is a number.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is a number
*
* @example
* var bool = isNumber( 3.14 );
* // returns true
*
* @example
* var bool = isNumber( new Number( 3.14 ) );
* // returns true
*
* @example
* var bool = isNumber( NaN );
* // returns true
*
* @example
* var bool = isNumber( null );
* // returns false
*/
function isNumber( value ) {
return ( isPrimitive( value ) || isObject( value ) );
}
// EXPORTS //
module.exports = isNumber;
},{"./object.js":139,"./primitive.js":140}],139:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var hasToStringTag = require( '@stdlib/assert/has-tostringtag-support' );
var nativeClass = require( '@stdlib/utils/native-class' );
var Number = require( '@stdlib/number/ctor' );
var test = require( './try2serialize.js' );
// VARIABLES //
var FLG = hasToStringTag();
// MAIN //
/**
* Tests if a value is a number object.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a number object
*
* @example
* var bool = isNumber( 3.14 );
* // returns false
*
* @example
* var bool = isNumber( new Number( 3.14 ) );
* // returns true
*/
function isNumber( value ) {
if ( typeof value === 'object' ) {
if ( value instanceof Number ) {
return true;
}
if ( FLG ) {
return test( value );
}
return ( nativeClass( value ) === '[object Number]' );
}
return false;
}
// EXPORTS //
module.exports = isNumber;
},{"./try2serialize.js":142,"@stdlib/assert/has-tostringtag-support":57,"@stdlib/number/ctor":273,"@stdlib/utils/native-class":393}],140:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Tests if a value is a number primitive.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a number primitive
*
* @example
* var bool = isNumber( 3.14 );
* // returns true
*
* @example
* var bool = isNumber( NaN );
* // returns true
*
* @example
* var bool = isNumber( new Number( 3.14 ) );
* // returns false
*/
function isNumber( value ) {
return ( typeof value === 'number' );
}
// EXPORTS //
module.exports = isNumber;
},{}],141:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var Number = require( '@stdlib/number/ctor' );
// MAIN //
// eslint-disable-next-line stdlib/no-redeclare
var toString = Number.prototype.toString; // non-generic
// EXPORTS //
module.exports = toString;
},{"@stdlib/number/ctor":273}],142:[function(require,module,exports){
arguments[4][86][0].apply(exports,arguments)
},{"./tostring.js":141,"dup":86}],143:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is object-like.
*
* @module @stdlib/assert/is-object-like
*
* @example
* var isObjectLike = require( '@stdlib/assert/is-object-like' );
*
* var bool = isObjectLike( {} );
* // returns true
*
* bool = isObjectLike( [] );
* // returns true
*
* bool = isObjectLike( null );
* // returns false
*
* @example
* var isObjectLike = require( '@stdlib/assert/is-object-like' ).isObjectLikeArray;
*
* var bool = isObjectLike( [ {}, [] ] );
* // returns true
*
* bool = isObjectLike( [ {}, '3.0' ] );
* // returns false
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var arrayfun = require( '@stdlib/assert/tools/array-function' );
var isObjectLike = require( './main.js' );
// MAIN //
setReadOnly( isObjectLike, 'isObjectLikeArray', arrayfun( isObjectLike ) );
// EXPORTS //
module.exports = isObjectLike;
},{"./main.js":144,"@stdlib/assert/tools/array-function":177,"@stdlib/utils/define-nonenumerable-read-only-property":344}],144:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Tests if a value is object-like.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether a value is object-like
*
* @example
* var bool = isObjectLike( {} );
* // returns true
*
* @example
* var bool = isObjectLike( [] );
* // returns true
*
* @example
* var bool = isObjectLike( null );
* // returns false
*/
function isObjectLike( value ) {
return (
value !== null &&
typeof value === 'object'
);
}
// EXPORTS //
module.exports = isObjectLike;
},{}],145:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is an object.
*
* @module @stdlib/assert/is-object
*
* @example
* var isObject = require( '@stdlib/assert/is-object' );
*
* var bool = isObject( {} );
* // returns true
*
* bool = isObject( true );
* // returns false
*/
// MODULES //
var isObject = require( './main.js' );
// EXPORTS //
module.exports = isObject;
},{"./main.js":146}],146:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isArray = require( '@stdlib/assert/is-array' );
// MAIN //
/**
* Tests if a value is an object; e.g., `{}`.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is an object
*
* @example
* var bool = isObject( {} );
* // returns true
*
* @example
* var bool = isObject( null );
* // returns false
*/
function isObject( value ) {
return (
typeof value === 'object' &&
value !== null &&
!isArray( value )
);
}
// EXPORTS //
module.exports = isObject;
},{"@stdlib/assert/is-array":79}],147:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is a plain object.
*
* @module @stdlib/assert/is-plain-object
*
* @example
* var isPlainObject = require( '@stdlib/assert/is-plain-object' );
*
* var bool = isPlainObject( {} );
* // returns true
*
* bool = isPlainObject( null );
* // returns false
*/
// MODULES //
var isPlainObject = require( './main.js' );
// EXPORTS //
module.exports = isPlainObject;
},{"./main.js":148}],148:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isObject = require( '@stdlib/assert/is-object' );
var isFunction = require( '@stdlib/assert/is-function' );
var getPrototypeOf = require( '@stdlib/utils/get-prototype-of' );
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var nativeClass = require( '@stdlib/utils/native-class' );
// VARIABLES //
var objectPrototype = Object.prototype;
// FUNCTIONS //
/**
* Tests that an object only has own properties.
*
* @private
* @param {Object} obj - value to test
* @returns {boolean} boolean indicating if an object only has own properties
*/
function ownProps( obj ) {
var key;
// NOTE: possibility of perf boost if key enumeration order is known (see http://stackoverflow.com/questions/18531624/isplainobject-thing).
for ( key in obj ) {
if ( !hasOwnProp( obj, key ) ) {
return false;
}
}
return true;
}
// MAIN //
/**
* Tests if a value is a plain object.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is a plain object
*
* @example
* var bool = isPlainObject( {} );
* // returns true
*
* @example
* var bool = isPlainObject( null );
* // returns false
*/
function isPlainObject( value ) {
var proto;
// Screen for obvious non-objects...
if ( !isObject( value ) ) {
return false;
}
// Objects with no prototype (e.g., `Object.create( null )`) are plain...
proto = getPrototypeOf( value );
if ( !proto ) {
return true;
}
// Objects having a prototype are plain if and only if they are constructed with a global `Object` function and the prototype points to the prototype of a plain object...
return (
// Cannot have own `constructor` property:
!hasOwnProp( value, 'constructor' ) &&
// Prototype `constructor` property must be a function (see also https://bugs.jquery.com/ticket/9897 and http://stackoverflow.com/questions/18531624/isplainobject-thing):
hasOwnProp( proto, 'constructor' ) &&
isFunction( proto.constructor ) &&
nativeClass( proto.constructor ) === '[object Function]' &&
// Test for object-specific method:
hasOwnProp( proto, 'isPrototypeOf' ) &&
isFunction( proto.isPrototypeOf ) &&
(
// Test if the prototype matches the global `Object` prototype (same realm):
proto === objectPrototype ||
// Test that all properties are own properties (cross-realm; *most* likely a plain object):
ownProps( value )
)
);
}
// EXPORTS //
module.exports = isPlainObject;
},{"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-function":102,"@stdlib/assert/is-object":145,"@stdlib/utils/get-prototype-of":359,"@stdlib/utils/native-class":393}],149:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is a positive integer.
*
* @module @stdlib/assert/is-positive-integer
*
* @example
* var isPositiveInteger = require( '@stdlib/assert/is-positive-integer' );
*
* var bool = isPositiveInteger( 5.0 );
* // returns true
*
* bool = isPositiveInteger( new Number( 5.0 ) );
* // returns true
*
* bool = isPositiveInteger( -5.0 );
* // returns false
*
* bool = isPositiveInteger( 3.14 );
* // returns false
*
* bool = isPositiveInteger( null );
* // returns false
*
* @example
* var isPositiveInteger = require( '@stdlib/assert/is-positive-integer' ).isPrimitive;
*
* var bool = isPositiveInteger( 3.0 );
* // returns true
*
* bool = isPositiveInteger( new Number( 3.0 ) );
* // returns false
*
* @example
* var isPositiveInteger = require( '@stdlib/assert/is-positive-integer' ).isObject;
*
* var bool = isPositiveInteger( 3.0 );
* // returns false
*
* bool = isPositiveInteger( new Number( 3.0 ) );
* // returns true
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var isPositiveInteger = require( './main.js' );
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );
// MAIN //
setReadOnly( isPositiveInteger, 'isPrimitive', isPrimitive );
setReadOnly( isPositiveInteger, 'isObject', isObject );
// EXPORTS //
module.exports = isPositiveInteger;
},{"./main.js":150,"./object.js":151,"./primitive.js":152,"@stdlib/utils/define-nonenumerable-read-only-property":344}],150:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );
// MAIN //
/**
* Tests if a value is a positive integer.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is a positive integer
*
* @example
* var bool = isPositiveInteger( 5.0 );
* // returns true
*
* @example
* var bool = isPositiveInteger( new Number( 5.0 ) );
* // returns true
*
* @example
* var bool = isPositiveInteger( 0.0 );
* // returns false
*
* @example
* var bool = isPositiveInteger( -5.0 );
* // returns false
*
* @example
* var bool = isPositiveInteger( 3.14 );
* // returns false
*
* @example
* var bool = isPositiveInteger( null );
* // returns false
*/
function isPositiveInteger( value ) {
return ( isPrimitive( value ) || isObject( value ) );
}
// EXPORTS //
module.exports = isPositiveInteger;
},{"./object.js":151,"./primitive.js":152}],151:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isInteger = require( '@stdlib/assert/is-integer' ).isObject;
// MAIN //
/**
* Tests if a value is a number object having a positive integer value.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a number object having a positive integer value
*
* @example
* var bool = isPositiveInteger( 3.0 );
* // returns false
*
* @example
* var bool = isPositiveInteger( new Number( 3.0 ) );
* // returns true
*/
function isPositiveInteger( value ) {
return (
isInteger( value ) &&
value.valueOf() > 0.0
);
}
// EXPORTS //
module.exports = isPositiveInteger;
},{"@stdlib/assert/is-integer":110}],152:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isInteger = require( '@stdlib/assert/is-integer' ).isPrimitive;
// MAIN //
/**
* Tests if a value is a number primitive having a positive integer value.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a number primitive having a positive integer value
*
* @example
* var bool = isPositiveInteger( 3.0 );
* // returns true
*
* @example
* var bool = isPositiveInteger( new Number( 3.0 ) );
* // returns false
*/
function isPositiveInteger( value ) {
return (
isInteger( value ) &&
value > 0.0
);
}
// EXPORTS //
module.exports = isPositiveInteger;
},{"@stdlib/assert/is-integer":110}],153:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
var exec = RegExp.prototype.exec; // non-generic
// EXPORTS //
module.exports = exec;
},{}],154:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is a regular expression.
*
* @module @stdlib/assert/is-regexp
*
* @example
* var isRegExp = require( '@stdlib/assert/is-regexp' );
*
* var bool = isRegExp( /\.+/ );
* // returns true
*
* bool = isRegExp( {} );
* // returns false
*/
// MODULES //
var isRegExp = require( './main.js' );
// EXPORTS //
module.exports = isRegExp;
},{"./main.js":155}],155:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var hasToStringTag = require( '@stdlib/assert/has-tostringtag-support' );
var nativeClass = require( '@stdlib/utils/native-class' );
var test = require( './try2exec.js' );
// VARIABLES //
var FLG = hasToStringTag();
// MAIN //
/**
* Tests if a value is a regular expression.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is a regular expression
*
* @example
* var bool = isRegExp( /\.+/ );
* // returns true
*
* @example
* var bool = isRegExp( {} );
* // returns false
*/
function isRegExp( value ) {
if ( typeof value === 'object' ) {
if ( value instanceof RegExp ) {
return true;
}
if ( FLG ) {
return test( value );
}
return ( nativeClass( value ) === '[object RegExp]' );
}
return false;
}
// EXPORTS //
module.exports = isRegExp;
},{"./try2exec.js":156,"@stdlib/assert/has-tostringtag-support":57,"@stdlib/utils/native-class":393}],156:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var exec = require( './exec.js' );
// MAIN //
/**
* Attempts to call a `RegExp` method.
*
* @private
* @param {*} value - value to test
* @returns {boolean} boolean indicating if able to call a `RegExp` method
*/
function test( value ) {
try {
exec.call( value );
return true;
} catch ( err ) { // eslint-disable-line no-unused-vars
return false;
}
}
// EXPORTS //
module.exports = test;
},{"./exec.js":153}],157:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is an array of strings.
*
* @module @stdlib/assert/is-string-array
*
* @example
* var isStringArray = require( '@stdlib/assert/is-string-array' );
*
* var bool = isStringArray( [ 'abc', 'def' ] );
* // returns true
*
* bool = isStringArray( [ 'abc', 123 ] );
* // returns false
*
* @example
* var isStringArray = require( '@stdlib/assert/is-string-array' ).primitives;
*
* var bool = isStringArray( [ 'abc', 'def' ] );
* // returns true
*
* bool = isStringArray( [ 'abc', new String( 'def' ) ] );
* // returns false
*
* @example
* var isStringArray = require( '@stdlib/assert/is-string-array' ).objects;
*
* var bool = isStringArray( [ new String( 'abc' ), new String( 'def' ) ] );
* // returns true
*
* bool = isStringArray( [ new String( 'abc' ), 'def' ] );
* // returns false
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var arrayfun = require( '@stdlib/assert/tools/array-function' );
var isString = require( '@stdlib/assert/is-string' );
// MAIN //
var isStringArray = arrayfun( isString );
setReadOnly( isStringArray, 'primitives', arrayfun( isString.isPrimitive ) );
setReadOnly( isStringArray, 'objects', arrayfun( isString.isObject ) );
// EXPORTS //
module.exports = isStringArray;
},{"@stdlib/assert/is-string":158,"@stdlib/assert/tools/array-function":177,"@stdlib/utils/define-nonenumerable-read-only-property":344}],158:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is a string.
*
* @module @stdlib/assert/is-string
*
* @example
* var isString = require( '@stdlib/assert/is-string' );
*
* var bool = isString( 'beep' );
* // returns true
*
* bool = isString( new String( 'beep' ) );
* // returns true
*
* bool = isString( 5 );
* // returns false
*
* @example
* var isString = require( '@stdlib/assert/is-string' ).isObject;
*
* var bool = isString( new String( 'beep' ) );
* // returns true
*
* bool = isString( 'beep' );
* // returns false
*
* @example
* var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
*
* var bool = isString( 'beep' );
* // returns true
*
* bool = isString( new String( 'beep' ) );
* // returns false
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var isString = require( './main.js' );
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );
// MAIN //
setReadOnly( isString, 'isPrimitive', isPrimitive );
setReadOnly( isString, 'isObject', isObject );
// EXPORTS //
module.exports = isString;
},{"./main.js":159,"./object.js":160,"./primitive.js":161,"@stdlib/utils/define-nonenumerable-read-only-property":344}],159:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );
// MAIN //
/**
* Tests if a value is a string.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is a string
*
* @example
* var bool = isString( new String( 'beep' ) );
* // returns true
*
* @example
* var bool = isString( 'beep' );
* // returns true
*/
function isString( value ) {
return ( isPrimitive( value ) || isObject( value ) );
}
// EXPORTS //
module.exports = isString;
},{"./object.js":160,"./primitive.js":161}],160:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var hasToStringTag = require( '@stdlib/assert/has-tostringtag-support' );
var nativeClass = require( '@stdlib/utils/native-class' );
var test = require( './try2valueof.js' );
// VARIABLES //
var FLG = hasToStringTag();
// MAIN //
/**
* Tests if a value is a string object.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a string object
*
* @example
* var bool = isString( new String( 'beep' ) );
* // returns true
*
* @example
* var bool = isString( 'beep' );
* // returns false
*/
function isString( value ) {
if ( typeof value === 'object' ) {
if ( value instanceof String ) {
return true;
}
if ( FLG ) {
return test( value );
}
return ( nativeClass( value ) === '[object String]' );
}
return false;
}
// EXPORTS //
module.exports = isString;
},{"./try2valueof.js":162,"@stdlib/assert/has-tostringtag-support":57,"@stdlib/utils/native-class":393}],161:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Tests if a value is a string primitive.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a string primitive
*
* @example
* var bool = isString( 'beep' );
* // returns true
*
* @example
* var bool = isString( new String( 'beep' ) );
* // returns false
*/
function isString( value ) {
return ( typeof value === 'string' );
}
// EXPORTS //
module.exports = isString;
},{}],162:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var valueOf = require( './valueof.js' ); // eslint-disable-line stdlib/no-redeclare
// MAIN //
/**
* Attempts to extract a string value.
*
* @private
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a string can be extracted
*/
function test( value ) {
try {
valueOf.call( value );
return true;
} catch ( err ) { // eslint-disable-line no-unused-vars
return false;
}
}
// EXPORTS //
module.exports = test;
},{"./valueof.js":163}],163:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// eslint-disable-next-line stdlib/no-redeclare
var valueOf = String.prototype.valueOf; // non-generic
// EXPORTS //
module.exports = valueOf;
},{}],164:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var Int8Array = require( '@stdlib/array/int8' );
var Uint8Array = require( '@stdlib/array/uint8' );
var Uint8ClampedArray = require( '@stdlib/array/uint8c' );
var Int16Array = require( '@stdlib/array/int16' );
var Uint16Array = require( '@stdlib/array/uint16' );
var Int32Array = require( '@stdlib/array/int32' );
var Uint32Array = require( '@stdlib/array/uint32' );
var Float32Array = require( '@stdlib/array/float32' );
var Float64Array = require( '@stdlib/array/float64' );
// MAIN //
var CTORS = [
Float64Array,
Float32Array,
Int32Array,
Uint32Array,
Int16Array,
Uint16Array,
Int8Array,
Uint8Array,
Uint8ClampedArray
];
// EXPORTS //
module.exports = CTORS;
},{"@stdlib/array/float32":2,"@stdlib/array/float64":5,"@stdlib/array/int16":7,"@stdlib/array/int32":10,"@stdlib/array/int8":13,"@stdlib/array/uint16":20,"@stdlib/array/uint32":23,"@stdlib/array/uint8":26,"@stdlib/array/uint8c":29}],165:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is a typed array.
*
* @module @stdlib/assert/is-typed-array
*
* @example
* var Int8Array = require( '@stdlib/array/int8' );
* var isTypedArray = require( '@stdlib/assert/is-typed-array' );
*
* var bool = isTypedArray( new Int8Array( 10 ) );
* // returns true
*/
// MODULES //
var isTypedArray = require( './main.js' );
// EXPORTS //
module.exports = isTypedArray;
},{"./main.js":166}],166:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var ctorName = require( '@stdlib/utils/constructor-name' );
var fcnName = require( '@stdlib/utils/function-name' );
var getPrototypeOf = require( '@stdlib/utils/get-prototype-of' );
var hasFloat64ArraySupport = require( '@stdlib/assert/has-float64array-support' );
var Float64Array = require( '@stdlib/array/float64' );
var CTORS = require( './ctors.js' );
var NAMES = require( './names.json' );
// VARIABLES //
// Abstract `TypedArray` class:
var TypedArray = ( hasFloat64ArraySupport() ) ? getPrototypeOf( Float64Array ) : Dummy; // eslint-disable-line max-len
// Ensure abstract typed array class has expected name:
TypedArray = ( fcnName( TypedArray ) === 'TypedArray' ) ? TypedArray : Dummy;
// FUNCTIONS //
/**
* Dummy constructor.
*
* @private
*/
function Dummy() {} // eslint-disable-line no-empty-function
// MAIN //
/**
* Tests if a value is a typed array.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a typed array
*
* @example
* var Int8Array = require( '@stdlib/array/int8' );
*
* var bool = isTypedArray( new Int8Array( 10 ) );
* // returns true
*/
function isTypedArray( value ) {
var v;
var i;
if ( typeof value !== 'object' || value === null ) {
return false;
}
// Check for the abstract class...
if ( value instanceof TypedArray ) {
return true;
}
// Check for typed array objects from the same realm (same Node.js `vm` or same `Window` object)...
for ( i = 0; i < CTORS.length; i++ ) {
if ( value instanceof CTORS[ i ] ) {
return true;
}
}
// Walk the prototype tree until we find an object having a desired class...
while ( value ) {
v = ctorName( value );
for ( i = 0; i < NAMES.length; i++ ) {
if ( NAMES[ i ] === v ) {
return true;
}
}
value = getPrototypeOf( value );
}
return false;
}
// EXPORTS //
module.exports = isTypedArray;
},{"./ctors.js":164,"./names.json":167,"@stdlib/array/float64":5,"@stdlib/assert/has-float64array-support":36,"@stdlib/utils/constructor-name":336,"@stdlib/utils/function-name":356,"@stdlib/utils/get-prototype-of":359}],167:[function(require,module,exports){
module.exports=[
"Int8Array",
"Uint8Array",
"Uint8ClampedArray",
"Int16Array",
"Uint16Array",
"Int32Array",
"Uint32Array",
"Float32Array",
"Float64Array"
]
},{}],168:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is a Uint16Array.
*
* @module @stdlib/assert/is-uint16array
*
* @example
* var isUint16Array = require( '@stdlib/assert/is-uint16array' );
*
* var bool = isUint16Array( new Uint16Array( 10 ) );
* // returns true
*
* bool = isUint16Array( [] );
* // returns false
*/
// MODULES //
var isUint16Array = require( './main.js' );
// EXPORTS //
module.exports = isUint16Array;
},{"./main.js":169}],169:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var nativeClass = require( '@stdlib/utils/native-class' );
// VARIABLES //
var hasUint16Array = ( typeof Uint16Array === 'function' ); // eslint-disable-line stdlib/require-globals
// MAIN //
/**
* Tests if a value is a Uint16Array.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is a Uint16Array
*
* @example
* var bool = isUint16Array( new Uint16Array( 10 ) );
* // returns true
*
* @example
* var bool = isUint16Array( [] );
* // returns false
*/
function isUint16Array( value ) {
return (
( hasUint16Array && value instanceof Uint16Array ) || // eslint-disable-line stdlib/require-globals
nativeClass( value ) === '[object Uint16Array]'
);
}
// EXPORTS //
module.exports = isUint16Array;
},{"@stdlib/utils/native-class":393}],170:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is a Uint32Array.
*
* @module @stdlib/assert/is-uint32array
*
* @example
* var isUint32Array = require( '@stdlib/assert/is-uint32array' );
*
* var bool = isUint32Array( new Uint32Array( 10 ) );
* // returns true
*
* bool = isUint32Array( [] );
* // returns false
*/
// MODULES //
var isUint32Array = require( './main.js' );
// EXPORTS //
module.exports = isUint32Array;
},{"./main.js":171}],171:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var nativeClass = require( '@stdlib/utils/native-class' );
// VARIABLES //
var hasUint32Array = ( typeof Uint32Array === 'function' ); // eslint-disable-line stdlib/require-globals
// MAIN //
/**
* Tests if a value is a Uint32Array.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is a Uint32Array
*
* @example
* var bool = isUint32Array( new Uint32Array( 10 ) );
* // returns true
*
* @example
* var bool = isUint32Array( [] );
* // returns false
*/
function isUint32Array( value ) {
return (
( hasUint32Array && value instanceof Uint32Array ) || // eslint-disable-line stdlib/require-globals
nativeClass( value ) === '[object Uint32Array]'
);
}
// EXPORTS //
module.exports = isUint32Array;
},{"@stdlib/utils/native-class":393}],172:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is a Uint8Array.
*
* @module @stdlib/assert/is-uint8array
*
* @example
* var isUint8Array = require( '@stdlib/assert/is-uint8array' );
*
* var bool = isUint8Array( new Uint8Array( 10 ) );
* // returns true
*
* bool = isUint8Array( [] );
* // returns false
*/
// MODULES //
var isUint8Array = require( './main.js' );
// EXPORTS //
module.exports = isUint8Array;
},{"./main.js":173}],173:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var nativeClass = require( '@stdlib/utils/native-class' );
// VARIABLES //
var hasUint8Array = ( typeof Uint8Array === 'function' ); // eslint-disable-line stdlib/require-globals
// MAIN //
/**
* Tests if a value is a Uint8Array.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is a Uint8Array
*
* @example
* var bool = isUint8Array( new Uint8Array( 10 ) );
* // returns true
*
* @example
* var bool = isUint8Array( [] );
* // returns false
*/
function isUint8Array( value ) {
return (
( hasUint8Array && value instanceof Uint8Array ) || // eslint-disable-line stdlib/require-globals
nativeClass( value ) === '[object Uint8Array]'
);
}
// EXPORTS //
module.exports = isUint8Array;
},{"@stdlib/utils/native-class":393}],174:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is a Uint8ClampedArray.
*
* @module @stdlib/assert/is-uint8clampedarray
*
* @example
* var isUint8ClampedArray = require( '@stdlib/assert/is-uint8clampedarray' );
*
* var bool = isUint8ClampedArray( new Uint8ClampedArray( 10 ) );
* // returns true
*
* bool = isUint8ClampedArray( [] );
* // returns false
*/
// MODULES //
var isUint8ClampedArray = require( './main.js' );
// EXPORTS //
module.exports = isUint8ClampedArray;
},{"./main.js":175}],175:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var nativeClass = require( '@stdlib/utils/native-class' );
// VARIABLES //
var hasUint8ClampedArray = ( typeof Uint8ClampedArray === 'function' ); // eslint-disable-line stdlib/require-globals
// MAIN //
/**
* Tests if a value is a Uint8ClampedArray.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is a Uint8ClampedArray
*
* @example
* var bool = isUint8ClampedArray( new Uint8ClampedArray( 10 ) );
* // returns true
*
* @example
* var bool = isUint8ClampedArray( [] );
* // returns false
*/
function isUint8ClampedArray( value ) {
return (
( hasUint8ClampedArray && value instanceof Uint8ClampedArray ) || // eslint-disable-line stdlib/require-globals
nativeClass( value ) === '[object Uint8ClampedArray]'
);
}
// EXPORTS //
module.exports = isUint8ClampedArray;
},{"@stdlib/utils/native-class":393}],176:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isArray = require( '@stdlib/assert/is-array' );
// MAIN //
/**
* Returns a function which tests if every element in an array passes a test condition.
*
* @param {Function} predicate - function to apply
* @throws {TypeError} must provide a function
* @returns {Function} an array function
*
* @example
* var isOdd = require( '@stdlib/assert/is-odd' );
*
* var arr1 = [ 1, 3, 5, 7 ];
* var arr2 = [ 3, 5, 8 ];
*
* var validate = arrayfcn( isOdd );
*
* var bool = validate( arr1 );
* // returns true
*
* bool = validate( arr2 );
* // returns false
*/
function arrayfcn( predicate ) {
if ( typeof predicate !== 'function' ) {
throw new TypeError( 'invalid argument. Must provide a function. Value: `' + predicate + '`.' );
}
return every;
/**
* Tests if every element in an array passes a test condition.
*
* @private
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether a value is an array for which all elements pass a test condition
*/
function every( value ) {
var len;
var i;
if ( !isArray( value ) ) {
return false;
}
len = value.length;
if ( len === 0 ) {
return false;
}
for ( i = 0; i < len; i++ ) {
if ( predicate( value[ i ] ) === false ) {
return false;
}
}
return true;
}
}
// EXPORTS //
module.exports = arrayfcn;
},{"@stdlib/assert/is-array":79}],177:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Return a function which tests if every element in an array passes a test condition.
*
* @module @stdlib/assert/tools/array-function
*
* @example
* var isOdd = require( '@stdlib/assert/is-odd' );
* var arrayfcn = require( '@stdlib/assert/tools/array-function' );
*
* var arr1 = [ 1, 3, 5, 7 ];
* var arr2 = [ 3, 5, 8 ];
*
* var validate = arrayfcn( isOdd );
*
* var bool = validate( arr1 );
* // returns true
*
* bool = validate( arr2 );
* // returns false
*/
// MODULES //
var arrayfcn = require( './arrayfcn.js' );
// EXPORTS //
module.exports = arrayfcn;
},{"./arrayfcn.js":176}],178:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isArrayLike = require( '@stdlib/assert/is-array-like' );
// MAIN //
/**
* Returns a function which tests if every element in an array-like object passes a test condition.
*
* @param {Function} predicate - function to apply
* @throws {TypeError} must provide a function
* @returns {Function} an array-like object function
*
* @example
* var isOdd = require( '@stdlib/assert/is-odd' );
*
* var arr1 = [ 1, 3, 5, 7 ];
* var arr2 = [ 3, 5, 8 ];
*
* var validate = arraylikefcn( isOdd );
*
* var bool = validate( arr1 );
* // returns true
*
* bool = validate( arr2 );
* // returns false
*/
function arraylikefcn( predicate ) {
if ( typeof predicate !== 'function' ) {
throw new TypeError( 'invalid argument. Must provide a function. Value: `' + predicate + '`.' );
}
return every;
/**
* Tests if every element in an array-like object passes a test condition.
*
* @private
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether a value is an array-like object for which all elements pass a test condition
*/
function every( value ) {
var len;
var i;
if ( !isArrayLike( value ) ) {
return false;
}
len = value.length;
if ( len === 0 ) {
return false;
}
for ( i = 0; i < len; i++ ) {
if ( predicate( value[ i ] ) === false ) {
return false;
}
}
return true;
}
}
// EXPORTS //
module.exports = arraylikefcn;
},{"@stdlib/assert/is-array-like":77}],179:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Return a function which tests if every element in an array-like object passes a test condition.
*
* @module @stdlib/assert/tools/array-like-function
*
* @example
* var isOdd = require( '@stdlib/assert/is-odd' );
* var arraylikefcn = require( '@stdlib/assert/tools/array-like-function' );
*
* var arr1 = [ 1, 3, 5, 7 ];
* var arr2 = [ 3, 5, 8 ];
*
* var validate = arraylikefcn( isOdd );
*
* var bool = validate( arr1 );
* // returns true
*
* bool = validate( arr2 );
* // returns false
*/
// MODULES //
var arraylikefcn = require( './arraylikefcn.js' );
// EXPORTS //
module.exports = arraylikefcn;
},{"./arraylikefcn.js":178}],180:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var TransformStream = require( '@stdlib/streams/node/transform' );
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var isFunction = require( '@stdlib/assert/is-function' );
var createHarness = require( './harness' );
var harness = require( './get_harness.js' );
// VARIABLES //
var listeners = [];
// FUNCTIONS //
/**
* Callback invoked when a harness finishes running all benchmarks.
*
* @private
*/
function done() {
var len;
var f;
var i;
len = listeners.length;
// Inform all the listeners that the harness has finished...
for ( i = 0; i < len; i++ ) {
f = listeners.shift();
f();
}
}
/**
* Creates a results stream.
*
* @private
* @param {Options} [options] - stream options
* @throws {Error} must provide valid stream options
* @returns {TransformStream} results stream
*/
function createStream( options ) {
var stream;
var bench;
var opts;
if ( arguments.length ) {
opts = options;
} else {
opts = {};
}
// If we have already created a harness, calling this function simply creates another results stream...
if ( harness.cached ) {
bench = harness();
return bench.createStream( opts );
}
stream = new TransformStream( opts );
opts.stream = stream;
// Create a harness which uses the created output stream:
harness( opts, done );
return stream;
}
/**
* Adds a listener for when a harness finishes running all benchmarks.
*
* @private
* @param {Callback} clbk - listener
* @throws {TypeError} must provide a function
* @throws {Error} must provide a listener only once
* @returns {void}
*/
function onFinish( clbk ) {
var i;
if ( !isFunction( clbk ) ) {
throw new TypeError( 'invalid argument. Must provide a function. Value: `'+clbk+'`.' );
}
// Allow adding a listener only once...
for ( i = 0; i < listeners.length; i++ ) {
if ( clbk === listeners[ i ] ) {
throw new Error( 'invalid argument. Attempted to add duplicate listener.' );
}
}
listeners.push( clbk );
}
// MAIN //
/**
* Runs a benchmark.
*
* @param {string} name - benchmark name
* @param {Options} [options] - benchmark options
* @param {boolean} [options.skip=false] - boolean indicating whether to skip a benchmark
* @param {(PositiveInteger|null)} [options.iterations=null] - number of iterations
* @param {PositiveInteger} [options.repeats=3] - number of repeats
* @param {PositiveInteger} [options.timeout=300000] - number of milliseconds before a benchmark automatically fails
* @param {Function} [benchmark] - function containing benchmark code
* @throws {TypeError} first argument must be a string
* @throws {TypeError} options argument must be an object
* @throws {TypeError} must provide valid options
* @throws {TypeError} benchmark argument must a function
* @returns {Benchmark} benchmark harness
*
* @example
* bench( 'beep', function benchmark( b ) {
* var x;
* var i;
* b.tic();
* for ( i = 0; i < b.iterations; i++ ) {
* x = Math.sin( Math.random() );
* if ( x !== x ) {
* b.ok( false, 'should not return NaN' );
* }
* }
* b.toc();
* if ( x !== x ) {
* b.ok( false, 'should not return NaN' );
* }
* b.end();
* });
*/
function bench( name, options, benchmark ) {
var h = harness( done );
if ( arguments.length < 2 ) {
h( name );
} else if ( arguments.length === 2 ) {
h( name, options );
} else {
h( name, options, benchmark );
}
return bench;
}
/**
* Creates a benchmark harness.
*
* @name createHarness
* @memberof bench
* @type {Function}
* @param {Options} [options] - harness options
* @param {Callback} [clbk] - callback to invoke when a harness finishes running all benchmarks
* @throws {TypeError} options argument must be an object
* @throws {TypeError} must provide valid options
* @throws {TypeError} callback argument must be a function
* @returns {Function} benchmark harness
*/
setReadOnly( bench, 'createHarness', createHarness );
/**
* Creates a results stream.
*
* @name createStream
* @memberof bench
* @type {Function}
* @param {Options} [options] - stream options
* @throws {Error} must provide valid stream options
* @returns {TransformStream} results stream
*/
setReadOnly( bench, 'createStream', createStream );
/**
* Adds a listener for when a harness finishes running all benchmarks.
*
* @name onFinish
* @memberof bench
* @type {Function}
* @param {Callback} clbk - listener
* @throws {TypeError} must provide a function
* @throws {Error} must provide a listener only once
* @returns {void}
*/
setReadOnly( bench, 'onFinish', onFinish );
// EXPORTS //
module.exports = bench;
},{"./get_harness.js":202,"./harness":203,"@stdlib/assert/is-function":102,"@stdlib/streams/node/transform":320,"@stdlib/utils/define-nonenumerable-read-only-property":344}],181:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
// MAIN //
/**
* Generates an assertion.
*
* @private
* @param {boolean} ok - assertion outcome
* @param {Options} opts - options
*/
function assert( ok, opts ) {
/* eslint-disable no-invalid-this, no-unused-vars */ // TODO: remove no-unused-vars once `err` is used
var result;
var err;
result = {
'id': this._count,
'ok': ok,
'skip': opts.skip,
'todo': opts.todo,
'name': opts.message || '(unnamed assert)',
'operator': opts.operator
};
if ( hasOwnProp( opts, 'actual' ) ) {
result.actual = opts.actual;
}
if ( hasOwnProp( opts, 'expected' ) ) {
result.expected = opts.expected;
}
if ( !ok ) {
result.error = opts.error || new Error( this.name );
err = new Error( 'exception' );
// TODO: generate an exception in order to locate the calling function (https://github.com/substack/tape/blob/master/lib/test.js#L215)
}
this._count += 1;
this.emit( 'result', result );
}
// EXPORTS //
module.exports = assert;
},{"@stdlib/assert/has-own-property":53}],182:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// EXPORTS //
module.exports = clearTimeout;
},{}],183:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var trim = require( '@stdlib/string/trim' );
var replace = require( '@stdlib/string/replace' );
var EOL = require( '@stdlib/regexp/eol' ).REGEXP;
// VARIABLES //
var RE_COMMENT = /^#\s*/;
// MAIN //
/**
* Writes a comment.
*
* @private
* @param {string} msg - comment message
*/
function comment( msg ) {
/* eslint-disable no-invalid-this */
var lines;
var i;
msg = trim( msg );
lines = msg.split( EOL );
for ( i = 0; i < lines.length; i++ ) {
msg = trim( lines[ i ] );
msg = replace( msg, RE_COMMENT, '' );
this.emit( 'result', msg );
}
}
// EXPORTS //
module.exports = comment;
},{"@stdlib/regexp/eol":300,"@stdlib/string/replace":326,"@stdlib/string/trim":328}],184:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Asserts that `actual` is deeply equal to `expected`.
*
* @private
* @param {*} actual - actual value
* @param {*} expected - expected value
* @param {string} [msg] message
*/
function deepEqual( actual, expected, msg ) {
/* eslint-disable no-invalid-this */
this.comment( 'actual: '+actual+'. expected: '+expected+'. msg: '+msg+'.' );
// TODO: implement
}
// EXPORTS //
module.exports = deepEqual;
},{}],185:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var nextTick = require( './../utils/next_tick.js' );
// MAIN //
/**
* Ends a benchmark.
*
* @private
*/
function end() {
/* eslint-disable no-invalid-this */
var self = this;
if ( this._ended ) {
this.fail( '.end() called more than once' );
} else {
// Prevents releasing the zalgo when running synchronous benchmarks.
nextTick( onTick );
}
this._ended = true;
this._running = false;
/**
* Callback invoked upon a subsequent tick of the event loop.
*
* @private
*/
function onTick() {
self.emit( 'end' );
}
}
// EXPORTS //
module.exports = end;
},{"./../utils/next_tick.js":222}],186:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Returns a `boolean` indicating if a benchmark has ended.
*
* @private
* @returns {boolean} boolean indicating if a benchmark has ended
*/
function ended() {
/* eslint-disable no-invalid-this */
return this._ended;
}
// EXPORTS //
module.exports = ended;
},{}],187:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Asserts that `actual` is strictly equal to `expected`.
*
* @private
* @param {*} actual - actual value
* @param {*} expected - expected value
* @param {string} [msg] - message
*/
function equal( actual, expected, msg ) {
/* eslint-disable no-invalid-this */
this._assert( actual === expected, {
'message': msg || 'should be equal',
'operator': 'equal',
'expected': expected,
'actual': actual
});
}
// EXPORTS //
module.exports = equal;
},{}],188:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Forcefully ends a benchmark.
*
* @private
* @returns {void}
*/
function exit() {
/* eslint-disable no-invalid-this */
if ( this._exited ) {
// If we have already "exited", do not create more failing assertions when one should suffice...
return;
}
// Only "exit" when a benchmark has either not yet been run or is currently running. If a benchmark has already ended, no need to generate a failing assertion.
if ( !this._ended ) {
this._exited = true;
this.fail( 'benchmark exited without ending' );
// Allow running benchmarks to call `end` on their own...
if ( !this._running ) {
this.end();
}
}
}
// EXPORTS //
module.exports = exit;
},{}],189:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Generates a failing assertion.
*
* @private
* @param {string} msg - message
*/
function fail( msg ) {
/* eslint-disable no-invalid-this */
this._assert( false, {
'message': msg,
'operator': 'fail'
});
}
// EXPORTS //
module.exports = fail;
},{}],190:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var EventEmitter = require( 'events' ).EventEmitter;
var inherit = require( '@stdlib/utils/inherit' );
var defineProperty = require( '@stdlib/utils/define-property' );
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var tic = require( '@stdlib/time/tic' );
var toc = require( '@stdlib/time/toc' );
var run = require( './run.js' );
var exit = require( './exit.js' );
var ended = require( './ended.js' );
var assert = require( './assert.js' );
var comment = require( './comment.js' );
var skip = require( './skip.js' );
var todo = require( './todo.js' );
var fail = require( './fail.js' );
var pass = require( './pass.js' );
var ok = require( './ok.js' );
var notOk = require( './not_ok.js' );
var equal = require( './equal.js' );
var notEqual = require( './not_equal.js' );
var deepEqual = require( './deep_equal.js' );
var notDeepEqual = require( './not_deep_equal.js' );
var end = require( './end.js' );
// MAIN //
/**
* Benchmark constructor.
*
* @constructor
* @param {string} name - benchmark name
* @param {Options} opts - benchmark options
* @param {boolean} opts.skip - boolean indicating whether to skip a benchmark
* @param {PositiveInteger} opts.iterations - number of iterations
* @param {PositiveInteger} opts.timeout - number of milliseconds before a benchmark automatically fails
* @param {Function} [benchmark] - function containing benchmark code
* @returns {Benchmark} Benchmark instance
*
* @example
* var bench = new Benchmark( 'beep', function benchmark( b ) {
* var x;
* var i;
* b.comment( 'Running benchmarks...' );
* b.tic();
* for ( i = 0; i < b.iterations; i++ ) {
* x = Math.sin( Math.random() );
* if ( x !== x ) {
* b.ok( false, 'should not return NaN' );
* }
* }
* b.toc();
* if ( x !== x ) {
* b.ok( false, 'should not return NaN' );
* }
* b.comment( 'Finished running benchmarks.' );
* b.end();
* });
*/
function Benchmark( name, opts, benchmark ) {
var hasTicked;
var hasTocked;
var self;
var time;
if ( !( this instanceof Benchmark ) ) {
return new Benchmark( name, opts, benchmark );
}
self = this;
hasTicked = false;
hasTocked = false;
EventEmitter.call( this );
// Private properties:
setReadOnly( this, '_benchmark', benchmark );
setReadOnly( this, '_skip', opts.skip );
defineProperty( this, '_ended', {
'configurable': false,
'enumerable': false,
'writable': true,
'value': false
});
defineProperty( this, '_running', {
'configurable': false,
'enumerable': false,
'writable': true,
'value': false
});
defineProperty( this, '_exited', {
'configurable': false,
'enumerable': false,
'writable': true,
'value': false
});
defineProperty( this, '_count', {
'configurable': false,
'enumerable': false,
'writable': true,
'value': 0
});
// Read-only:
setReadOnly( this, 'name', name );
setReadOnly( this, 'tic', start );
setReadOnly( this, 'toc', stop );
setReadOnly( this, 'iterations', opts.iterations );
setReadOnly( this, 'timeout', opts.timeout );
return this;
/**
* Starts a benchmark timer.
*
* ## Notes
*
* - Using a scoped variable prevents nefarious mutation by bad actors hoping to manipulate benchmark results.
* - The one attack vector which remains is manipulation of the `require` cache for `tic` and `toc`.
* - One way to combat cache manipulation is by comparing the checksum of `Function#toString()` against known values.
*
* @private
*/
function start() {
if ( hasTicked ) {
self.fail( '.tic() called more than once' );
} else {
self.emit( 'tic' );
hasTicked = true;
time = tic();
}
}
/**
* Stops a benchmark timer.
*
* @private
* @returns {void}
*/
function stop() {
var elapsed;
var secs;
var rate;
var out;
if ( hasTicked === false ) {
return self.fail( '.toc() called before .tic()' );
}
elapsed = toc( time );
if ( hasTocked ) {
return self.fail( '.toc() called more than once' );
}
hasTocked = true;
self.emit( 'toc' );
secs = elapsed[ 0 ] + ( elapsed[ 1 ]/1e9 );
rate = self.iterations / secs;
out = {
'ok': true,
'operator': 'result',
'iterations': self.iterations,
'elapsed': secs,
'rate': rate
};
self.emit( 'result', out );
}
}
/*
* Inherit from the `EventEmitter` prototype.
*/
inherit( Benchmark, EventEmitter );
/**
* Runs a benchmark.
*
* @private
* @name run
* @memberof Benchmark.prototype
* @type {Function}
*/
setReadOnly( Benchmark.prototype, 'run', run );
/**
* Forcefully ends a benchmark.
*
* @private
* @name exit
* @memberof Benchmark.prototype
* @type {Function}
*/
setReadOnly( Benchmark.prototype, 'exit', exit );
/**
* Returns a `boolean` indicating if a benchmark has ended.
*
* @private
* @name ended
* @memberof Benchmark.prototype
* @type {Function}
* @returns {boolean} boolean indicating if a benchmark has ended
*/
setReadOnly( Benchmark.prototype, 'ended', ended );
/**
* Generates an assertion.
*
* @private
* @name _assert
* @memberof Benchmark.prototype
* @type {Function}
* @param {boolean} ok - assertion outcome
* @param {Options} opts - options
*/
setReadOnly( Benchmark.prototype, '_assert', assert );
/**
* Writes a comment.
*
* @name comment
* @memberof Benchmark.prototype
* @type {Function}
* @param {string} msg - comment message
*/
setReadOnly( Benchmark.prototype, 'comment', comment );
/**
* Generates an assertion which will be skipped.
*
* @name skip
* @memberof Benchmark.prototype
* @type {Function}
* @param {*} value - value
* @param {string} msg - message
*/
setReadOnly( Benchmark.prototype, 'skip', skip );
/**
* Generates an assertion which should be implemented.
*
* @name todo
* @memberof Benchmark.prototype
* @type {Function}
* @param {*} value - value
* @param {string} msg - message
*/
setReadOnly( Benchmark.prototype, 'todo', todo );
/**
* Generates a failing assertion.
*
* @name fail
* @memberof Benchmark.prototype
* @type {Function}
* @param {string} msg - message
*/
setReadOnly( Benchmark.prototype, 'fail', fail );
/**
* Generates a passing assertion.
*
* @name pass
* @memberof Benchmark.prototype
* @type {Function}
* @param {string} msg - message
*/
setReadOnly( Benchmark.prototype, 'pass', pass );
/**
* Asserts that a `value` is truthy.
*
* @name ok
* @memberof Benchmark.prototype
* @type {Function}
* @param {*} value - value
* @param {string} [msg] - message
*/
setReadOnly( Benchmark.prototype, 'ok', ok );
/**
* Asserts that a `value` is falsy.
*
* @name notOk
* @memberof Benchmark.prototype
* @type {Function}
* @param {*} value - value
* @param {string} [msg] - message
*/
setReadOnly( Benchmark.prototype, 'notOk', notOk );
/**
* Asserts that `actual` is strictly equal to `expected`.
*
* @name equal
* @memberof Benchmark.prototype
* @type {Function}
* @param {*} actual - actual value
* @param {*} expected - expected value
* @param {string} [msg] - message
*/
setReadOnly( Benchmark.prototype, 'equal', equal );
/**
* Asserts that `actual` is not strictly equal to `expected`.
*
* @name notEqual
* @memberof Benchmark.prototype
* @type {Function}
* @param {*} actual - actual value
* @param {*} expected - expected value
* @param {string} [msg] - message
*/
setReadOnly( Benchmark.prototype, 'notEqual', notEqual );
/**
* Asserts that `actual` is deeply equal to `expected`.
*
* @name deepEqual
* @memberof Benchmark.prototype
* @type {Function}
* @param {*} actual - actual value
* @param {*} expected - expected value
* @param {string} [msg] message
*/
setReadOnly( Benchmark.prototype, 'deepEqual', deepEqual );
/**
* Asserts that `actual` is not deeply equal to `expected`.
*
* @name notDeepEqual
* @memberof Benchmark.prototype
* @type {Function}
* @param {*} actual - actual value
* @param {*} expected - expected value
* @param {string} [msg] message
*/
setReadOnly( Benchmark.prototype, 'notDeepEqual', notDeepEqual );
/**
* Ends a benchmark.
*
* @name end
* @memberof Benchmark.prototype
* @type {Function}
*/
setReadOnly( Benchmark.prototype, 'end', end );
// EXPORTS //
module.exports = Benchmark;
},{"./assert.js":181,"./comment.js":183,"./deep_equal.js":184,"./end.js":185,"./ended.js":186,"./equal.js":187,"./exit.js":188,"./fail.js":189,"./not_deep_equal.js":191,"./not_equal.js":192,"./not_ok.js":193,"./ok.js":194,"./pass.js":195,"./run.js":196,"./skip.js":198,"./todo.js":199,"@stdlib/time/tic":330,"@stdlib/time/toc":334,"@stdlib/utils/define-nonenumerable-read-only-property":344,"@stdlib/utils/define-property":351,"@stdlib/utils/inherit":372,"events":425}],191:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Asserts that `actual` is not deeply equal to `expected`.
*
* @private
* @param {*} actual - actual value
* @param {*} expected - expected value
* @param {string} [msg] message
*/
function notDeepEqual( actual, expected, msg ) {
/* eslint-disable no-invalid-this */
this.comment( 'actual: '+actual+'. expected: '+expected+'. msg: '+msg+'.' );
// TODO: implement
}
// EXPORTS //
module.exports = notDeepEqual;
},{}],192:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Asserts that `actual` is not strictly equal to `expected`.
*
* @private
* @param {*} actual - actual value
* @param {*} expected - expected value
* @param {string} [msg] - message
*/
function notEqual( actual, expected, msg ) {
/* eslint-disable no-invalid-this */
this._assert( actual !== expected, {
'message': msg || 'should not be equal',
'operator': 'notEqual',
'expected': expected,
'actual': actual
});
}
// EXPORTS //
module.exports = notEqual;
},{}],193:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Asserts that a `value` is falsy.
*
* @private
* @param {*} value - value
* @param {string} [msg] - message
*/
function notOk( value, msg ) {
/* eslint-disable no-invalid-this */
this._assert( !value, {
'message': msg || 'should be falsy',
'operator': 'notOk',
'expected': false,
'actual': value
});
}
// EXPORTS //
module.exports = notOk;
},{}],194:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Asserts that a `value` is truthy.
*
* @private
* @param {*} value - value
* @param {string} [msg] - message
*/
function ok( value, msg ) {
/* eslint-disable no-invalid-this */
this._assert( !!value, {
'message': msg || 'should be truthy',
'operator': 'ok',
'expected': true,
'actual': value
});
}
// EXPORTS //
module.exports = ok;
},{}],195:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Generates a passing assertion.
*
* @private
* @param {string} msg - message
*/
function pass( msg ) {
/* eslint-disable no-invalid-this */
this._assert( true, {
'message': msg,
'operator': 'pass'
});
}
// EXPORTS //
module.exports = pass;
},{}],196:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var timeout = require( './set_timeout.js' );
var clear = require( './clear_timeout.js' );
// MAIN //
/**
* Runs a benchmark.
*
* @private
* @returns {void}
*/
function run() {
/* eslint-disable no-invalid-this */
var self;
var id;
if ( this._skip ) {
this.comment( 'SKIP '+this.name );
return this.end();
}
if ( !this._benchmark ) {
this.comment( 'TODO '+this.name );
return this.end();
}
self = this;
this._running = true;
id = timeout( onTimeout, this.timeout );
this.once( 'end', endTimeout );
this.emit( 'prerun' );
this._benchmark( this );
this.emit( 'run' );
/**
* Callback invoked once a timeout ends.
*
* @private
*/
function onTimeout() {
self.fail( 'benchmark timed out after '+self.timeout+'ms' );
}
/**
* Clears a timeout.
*
* @private
*/
function endTimeout() {
clear( id );
}
}
// EXPORTS //
module.exports = run;
},{"./clear_timeout.js":182,"./set_timeout.js":197}],197:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// EXPORTS //
module.exports = setTimeout;
},{}],198:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Generates an assertion which will be skipped.
*
* @private
* @param {*} value - value
* @param {string} msg - message
*/
function skip( value, msg ) {
/* eslint-disable no-invalid-this */
this._assert( true, {
'message': msg,
'operator': 'skip',
'skip': true
});
}
// EXPORTS //
module.exports = skip;
},{}],199:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Generates an assertion which should be implemented.
*
* @private
* @param {*} value - value
* @param {string} msg - message
*/
function todo( value, msg ) {
/* eslint-disable no-invalid-this */
this._assert( !!value, {
'message': msg,
'operator': 'todo',
'todo': true
});
}
// EXPORTS //
module.exports = todo;
},{}],200:[function(require,module,exports){
module.exports={
"skip": false,
"iterations": null,
"repeats": 3,
"timeout": 300000
}
},{}],201:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isFunction = require( '@stdlib/assert/is-function' );
var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive;
var isObject = require( '@stdlib/assert/is-plain-object' );
var isNodeWritableStreamLike = require( '@stdlib/assert/is-node-writable-stream-like' );
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var pick = require( '@stdlib/utils/pick' );
var omit = require( '@stdlib/utils/omit' );
var noop = require( '@stdlib/utils/noop' );
var createHarness = require( './harness' );
var logStream = require( './log' );
var canEmitExit = require( './utils/can_emit_exit.js' );
var proc = require( './utils/process.js' );
// MAIN //
/**
* Creates a benchmark harness which supports closing when a process exits.
*
* @private
* @param {Options} [options] - function options
* @param {boolean} [options.autoclose] - boolean indicating whether to automatically close a harness after a harness finishes running all benchmarks
* @param {Stream} [options.stream] - output writable stream
* @param {Callback} [clbk] - callback to invoke when a harness finishes running all benchmarks
* @throws {TypeError} options argument must be an object
* @throws {TypeError} must provide valid options
* @throws {TypeError} callback argument must be a function
* @returns {Function} benchmark harness
*
* @example
* var proc = require( 'process' );
* var bench = createExitHarness( onFinish );
*
* function onFinish() {
* bench.close();
* }
*
* bench( 'beep', function benchmark( b ) {
* var x;
* var i;
* b.tic();
* for ( i = 0; i < b.iterations; i++ ) {
* x = Math.sin( Math.random() );
* if ( x !== x ) {
* b.ok( false, 'should not return NaN' );
* }
* }
* b.toc();
* if ( x !== x ) {
* b.ok( false, 'should not return NaN' );
* }
* b.end();
* });
*
* @example
* var stdout = require( '@stdlib/streams/node/stdout' );
*
* var stream = createExitHarness().createStream();
* stream.pipe( stdout );
*/
function createExitHarness() {
var exitCode;
var pipeline;
var harness;
var options;
var stream;
var topts;
var opts;
var clbk;
if ( arguments.length === 0 ) {
options = {};
clbk = noop;
} else if ( arguments.length === 1 ) {
if ( isFunction( arguments[ 0 ] ) ) {
options = {};
clbk = arguments[ 0 ];
} else if ( isObject( arguments[ 0 ] ) ) {
options = arguments[ 0 ];
clbk = noop;
} else {
throw new TypeError( 'invalid argument. Must provide either an options object or a callback function. Value: `'+arguments[ 0 ]+'`.' );
}
} else {
options = arguments[ 0 ];
if ( !isObject( options ) ) {
throw new TypeError( 'invalid argument. First argument must be an object. Value: `'+options+'`.' );
}
clbk = arguments[ 1 ];
if ( !isFunction( clbk ) ) {
throw new TypeError( 'invalid argument. Second argument must be a function. Value: `'+clbk+'`.' );
}
}
opts = {};
if ( hasOwnProp( options, 'autoclose' ) ) {
opts.autoclose = options.autoclose;
if ( !isBoolean( opts.autoclose ) ) {
throw new TypeError( 'invalid option. `autoclose` option must be a boolean primitive. Option: `'+opts.autoclose+'`.' );
}
}
if ( hasOwnProp( options, 'stream' ) ) {
opts.stream = options.stream;
if ( !isNodeWritableStreamLike( opts.stream ) ) {
throw new TypeError( 'invalid option. `stream` option must be a writable stream. Option: `'+opts.stream+'`.' );
}
}
exitCode = 0;
// Create a new harness:
topts = pick( opts, [ 'autoclose' ] );
harness = createHarness( topts, done );
// Create a results stream:
topts = omit( options, [ 'autoclose', 'stream' ] );
stream = harness.createStream( topts );
// Pipe results to an output stream:
pipeline = stream.pipe( opts.stream || logStream() );
// If a process can emit an 'exit' event, capture errors in order to set the exit code...
if ( canEmitExit ) {
pipeline.on( 'error', onError );
proc.on( 'exit', onExit );
}
return harness;
/**
* Callback invoked when a harness finishes.
*
* @private
* @returns {void}
*/
function done() {
return clbk();
}
/**
* Callback invoked upon a stream `error` event.
*
* @private
* @param {Error} error - error object
*/
function onError() {
exitCode = 1;
}
/**
* Callback invoked upon an `exit` event.
*
* @private
* @param {integer} code - exit code
*/
function onExit( code ) {
if ( code !== 0 ) {
// Allow the process to exit...
return;
}
harness.close();
proc.exit( exitCode || harness.exitCode );
}
}
// EXPORTS //
module.exports = createExitHarness;
},{"./harness":203,"./log":209,"./utils/can_emit_exit.js":220,"./utils/process.js":223,"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-boolean":81,"@stdlib/assert/is-function":102,"@stdlib/assert/is-node-writable-stream-like":124,"@stdlib/assert/is-plain-object":147,"@stdlib/utils/noop":400,"@stdlib/utils/omit":402,"@stdlib/utils/pick":404}],202:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var canEmitExit = require( './utils/can_emit_exit.js' );
var createExitHarness = require( './exit_harness.js' );
// VARIABLES //
var harness;
// MAIN //
/**
* Returns a benchmark harness. If a harness has already been created, returns the cached harness.
*
* @private
* @param {Options} [options] - harness options
* @param {Callback} [clbk] - callback to invoke when a harness finishes running all benchmarks
* @returns {Function} benchmark harness
*/
function getHarness( options, clbk ) {
var opts;
var cb;
if ( harness ) {
return harness;
}
if ( arguments.length > 1 ) {
opts = options;
cb = clbk;
} else {
opts = {};
cb = options;
}
opts.autoclose = !canEmitExit;
harness = createExitHarness( opts, cb );
// Update state:
getHarness.cached = true;
return harness;
}
// EXPORTS //
module.exports = getHarness;
},{"./exit_harness.js":201,"./utils/can_emit_exit.js":220}],203:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var setReadOnlyAccessor = require( '@stdlib/utils/define-nonenumerable-read-only-accessor' );
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var isFunction = require( '@stdlib/assert/is-function' );
var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive;
var isObject = require( '@stdlib/assert/is-plain-object' );
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var copy = require( '@stdlib/utils/copy' );
var Benchmark = require( './../benchmark-class' );
var Runner = require( './../runner' );
var nextTick = require( './../utils/next_tick.js' );
var DEFAULTS = require( './../defaults.json' );
var validate = require( './validate.js' );
var init = require( './init.js' );
// MAIN //
/**
* Creates a benchmark harness.
*
* @param {Options} [options] - function options
* @param {boolean} [options.autoclose] - boolean indicating whether to automatically close a harness after a harness finishes running all benchmarks
* @param {Callback} [clbk] - callback to invoke when a harness finishes running all benchmarks
* @throws {TypeError} options argument must be an object
* @throws {TypeError} must provide valid options
* @throws {TypeError} callback argument must be a function
* @returns {Function} benchmark harness
*
* @example
* var bench = createHarness( onFinish );
*
* function onFinish() {
* bench.close();
* console.log( 'Exit code: %d', bench.exitCode );
* }
*
* bench( 'beep', function benchmark( b ) {
* var x;
* var i;
* b.tic();
* for ( i = 0; i < b.iterations; i++ ) {
* x = Math.sin( Math.random() );
* if ( x !== x ) {
* b.ok( false, 'should not return NaN' );
* }
* }
* b.toc();
* if ( x !== x ) {
* b.ok( false, 'should not return NaN' );
* }
* b.end();
* });
*
* @example
* var stdout = require( '@stdlib/streams/node/stdout' );
*
* var stream = createHarness().createStream();
* stream.pipe( stdout );
*/
function createHarness( options, clbk ) {
var exitCode;
var runner;
var queue;
var opts;
var cb;
opts = {};
if ( arguments.length === 1 ) {
if ( isFunction( options ) ) {
cb = options;
} else if ( isObject( options ) ) {
opts = options;
} else {
throw new TypeError( 'invalid argument. Must provide either an options object or a callback function. Value: `'+options+'`.' );
}
} else if ( arguments.length > 1 ) {
if ( !isObject( options ) ) {
throw new TypeError( 'invalid argument. First argument must be an object. Value: `'+options+'`.' );
}
if ( hasOwnProp( options, 'autoclose' ) ) {
opts.autoclose = options.autoclose;
if ( !isBoolean( opts.autoclose ) ) {
throw new TypeError( 'invalid option. `autoclose` option must be a boolean primitive. Option: `'+opts.autoclose+'`.' );
}
}
cb = clbk;
if ( !isFunction( cb ) ) {
throw new TypeError( 'invalid argument. Second argument must be a function. Value: `'+cb+'`.' );
}
}
runner = new Runner();
if ( opts.autoclose ) {
runner.once( 'done', close );
}
if ( cb ) {
runner.once( 'done', cb );
}
exitCode = 0;
queue = [];
/**
* Benchmark harness.
*
* @private
* @param {string} name - benchmark name
* @param {Options} [options] - benchmark options
* @param {boolean} [options.skip=false] - boolean indicating whether to skip a benchmark
* @param {(PositiveInteger|null)} [options.iterations=null] - number of iterations
* @param {PositiveInteger} [options.repeats=3] - number of repeats
* @param {PositiveInteger} [options.timeout=300000] - number of milliseconds before a benchmark automatically fails
* @param {Function} [benchmark] - function containing benchmark code
* @throws {TypeError} first argument must be a string
* @throws {TypeError} options argument must be an object
* @throws {TypeError} must provide valid options
* @throws {TypeError} benchmark argument must a function
* @throws {Error} benchmark error
* @returns {Function} benchmark harness
*/
function harness( name, options, benchmark ) {
var opts;
var err;
var b;
if ( !isString( name ) ) {
throw new TypeError( 'invalid argument. First argument must be a string. Value: `'+name+'`.' );
}
opts = copy( DEFAULTS );
if ( arguments.length === 2 ) {
if ( isFunction( options ) ) {
b = options;
} else {
err = validate( opts, options );
if ( err ) {
throw err;
}
}
} else if ( arguments.length > 2 ) {
err = validate( opts, options );
if ( err ) {
throw err;
}
b = benchmark;
if ( !isFunction( b ) ) {
throw new TypeError( 'invalid argument. Third argument must be a function. Value: `'+b+'`.' );
}
}
// Add the benchmark to the initialization queue:
queue.push( [ name, opts, b ] );
// Perform initialization on the next turn of the event loop (note: this allows all benchmarks to be "registered" within the same turn of the loop; otherwise, we run the risk of registration-execution race conditions (i.e., a benchmark registers and executes before other benchmarks can register, depleting the benchmark queue and leading the harness to close)):
if ( queue.length === 1 ) {
nextTick( initialize );
}
return harness;
}
/**
* Initializes each benchmark.
*
* @private
* @returns {void}
*/
function initialize() {
var idx = -1;
return next();
/**
* Initialize the next benchmark.
*
* @private
* @returns {void}
*/
function next() {
var args;
idx += 1;
// If all benchmarks have been initialized, begin running the benchmarks:
if ( idx === queue.length ) {
queue.length = 0;
return runner.run();
}
// Initialize the next benchmark:
args = queue[ idx ];
init( args[ 0 ], args[ 1 ], args[ 2 ], onInit );
}
/**
* Callback invoked after performing initialization tasks.
*
* @private
* @param {string} name - benchmark name
* @param {Options} opts - benchmark options
* @param {(Function|undefined)} benchmark - function containing benchmark code
* @returns {void}
*/
function onInit( name, opts, benchmark ) {
var b;
var i;
// Create a `Benchmark` instance for each repeat to ensure each benchmark has its own state...
for ( i = 0; i < opts.repeats; i++ ) {
b = new Benchmark( name, opts, benchmark );
b.on( 'result', onResult );
runner.push( b );
}
return next();
}
}
/**
* Callback invoked upon a `result` event.
*
* @private
* @param {(string|Object)} result - result
*/
function onResult( result ) {
if (
!isString( result ) &&
!result.ok &&
!result.todo
) {
exitCode = 1;
}
}
/**
* Returns a results stream.
*
* @private
* @param {Object} [options] - options
* @returns {TransformStream} transform stream
*/
function createStream( options ) {
if ( arguments.length ) {
return runner.createStream( options );
}
return runner.createStream();
}
/**
* Closes a benchmark harness.
*
* @private
*/
function close() {
runner.close();
}
/**
* Forcefully exits a benchmark harness.
*
* @private
*/
function exit() {
runner.exit();
}
/**
* Returns the harness exit code.
*
* @private
* @returns {NonNegativeInteger} exit code
*/
function getExitCode() {
return exitCode;
}
setReadOnly( harness, 'createStream', createStream );
setReadOnly( harness, 'close', close );
setReadOnly( harness, 'exit', exit );
setReadOnlyAccessor( harness, 'exitCode', getExitCode );
return harness;
}
// EXPORTS //
module.exports = createHarness;
},{"./../benchmark-class":190,"./../defaults.json":200,"./../runner":217,"./../utils/next_tick.js":222,"./init.js":204,"./validate.js":207,"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-boolean":81,"@stdlib/assert/is-function":102,"@stdlib/assert/is-plain-object":147,"@stdlib/assert/is-string":158,"@stdlib/utils/copy":340,"@stdlib/utils/define-nonenumerable-read-only-accessor":342,"@stdlib/utils/define-nonenumerable-read-only-property":344}],204:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var pretest = require( './pretest.js' );
var iterations = require( './iterations.js' );
// MAIN //
/**
* Performs benchmark initialization tasks.
*
* @private
* @param {string} name - benchmark name
* @param {Options} opts - benchmark options
* @param {(Function|undefined)} benchmark - function containing benchmark code
* @param {Callback} clbk - callback to invoke after completing initialization tasks
* @returns {void}
*/
function init( name, opts, benchmark, clbk ) {
// If no benchmark function, then the benchmark is considered a "todo", so no need to repeat multiple times...
if ( !benchmark ) {
opts.repeats = 1;
return clbk( name, opts, benchmark );
}
// If the `skip` option to `true`, no need to initialize or repeat multiple times as will not be running the benchmark:
if ( opts.skip ) {
opts.repeats = 1;
return clbk( name, opts, benchmark );
}
// Perform pretests:
pretest( name, opts, benchmark, onPreTest );
/**
* Callback invoked upon completing pretests.
*
* @private
* @param {Error} [error] - error object
* @returns {void}
*/
function onPreTest( error ) {
// If the pretests failed, don't run the benchmark multiple times...
if ( error ) {
opts.repeats = 1;
opts.iterations = 1;
return clbk( name, opts, benchmark );
}
// If a user specified an iteration number, we can begin running benchmarks...
if ( opts.iterations ) {
return clbk( name, opts, benchmark );
}
// Determine iteration number:
iterations( name, opts, benchmark, onIterations );
}
/**
* Callback invoked upon determining an iteration number.
*
* @private
* @param {(Error|null)} error - error object
* @param {PositiveInteger} iter - number of iterations
* @returns {void}
*/
function onIterations( error, iter ) {
// If provided an error, then a benchmark failed, and, similar to pretests, don't run the benchmark multiple times...
if ( error ) {
opts.repeats = 1;
opts.iterations = 1;
return clbk( name, opts, benchmark );
}
opts.iterations = iter;
return clbk( name, opts, benchmark );
}
}
// EXPORTS //
module.exports = init;
},{"./iterations.js":205,"./pretest.js":206}],205:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var copy = require( '@stdlib/utils/copy' );
var Benchmark = require( './../benchmark-class' );
// VARIABLES //
var MIN_TIME = 0.1; // seconds
var ITERATIONS = 10; // 10^1
var MAX_ITERATIONS = 10000000000; // 10^10
// MAIN //
/**
* Determines the number of iterations.
*
* @private
* @param {string} name - benchmark name
* @param {Options} options - benchmark options
* @param {(Function|undefined)} benchmark - function containing benchmark code
* @param {Callback} clbk - callback to invoke after determining number of iterations
* @returns {void}
*/
function iterations( name, options, benchmark, clbk ) {
var opts;
var time;
// Elapsed time (in seconds):
time = 0;
// Create a local copy:
opts = copy( options );
opts.iterations = ITERATIONS;
// Begin running benchmarks:
return next();
/**
* Run a new benchmark.
*
* @private
*/
function next() {
var b = new Benchmark( name, opts, benchmark );
b.on( 'result', onResult );
b.once( 'end', onEnd );
b.run();
}
/**
* Callback invoked upon a `result` event.
*
* @private
* @param {(string|Object)} result - result
*/
function onResult( result ) {
if ( !isString( result ) && result.operator === 'result' ) {
time = result.elapsed;
}
}
/**
* Callback invoked upon an `end` event.
*
* @private
* @returns {void}
*/
function onEnd() {
if (
time < MIN_TIME &&
opts.iterations < MAX_ITERATIONS
) {
opts.iterations *= 10;
return next();
}
clbk( null, opts.iterations );
}
}
// EXPORTS //
module.exports = iterations;
},{"./../benchmark-class":190,"@stdlib/assert/is-string":158,"@stdlib/utils/copy":340}],206:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var copy = require( '@stdlib/utils/copy' );
var Benchmark = require( './../benchmark-class' );
// MAIN //
/**
* Runs pretests to sanity check and/or catch failures.
*
* @private
* @param {string} name - benchmark name
* @param {Options} options - benchmark options
* @param {(Function|undefined)} benchmark - function containing benchmark code
* @param {Callback} clbk - callback to invoke after completing pretests
*/
function pretest( name, options, benchmark, clbk ) {
var fail;
var opts;
var tic;
var toc;
var b;
// Counters to determine the number of `tic` and `toc` events:
tic = 0;
toc = 0;
// Local copy:
opts = copy( options );
opts.iterations = 1;
// Pretest to check for minimum requirements and/or errors...
b = new Benchmark( name, opts, benchmark );
b.on( 'result', onResult );
b.on( 'tic', onTic );
b.on( 'toc', onToc );
b.once( 'end', onEnd );
b.run();
/**
* Callback invoked upon a `result` event.
*
* @private
* @param {(string|Object)} result - result
*/
function onResult( result ) {
if (
!isString( result ) &&
!result.ok &&
!result.todo
) {
fail = true;
}
}
/**
* Callback invoked upon a `tic` event.
*
* @private
*/
function onTic() {
tic += 1;
}
/**
* Callback invoked upon a `toc` event.
*
* @private
*/
function onToc() {
toc += 1;
}
/**
* Callback invoked upon an `end` event.
*
* @private
* @returns {void}
*/
function onEnd() {
var err;
if ( fail ) {
// Possibility that failure is intermittent, but we will assume that the usual case is that the failure would persist across all repeats and no sense failing multiple times when once suffices.
err = new Error( 'benchmark failed' );
} else if ( tic !== 1 || toc !== 1 ) {
// Unable to do anything definitive with timing information (e.g., a tic with no toc or vice versa, or benchmark function calls neither tic nor toc).
err = new Error( 'invalid benchmark' );
}
if ( err ) {
return clbk( err );
}
return clbk();
}
}
// EXPORTS //
module.exports = pretest;
},{"./../benchmark-class":190,"@stdlib/assert/is-string":158,"@stdlib/utils/copy":340}],207:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isObject = require( '@stdlib/assert/is-plain-object' );
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive;
var isNull = require( '@stdlib/assert/is-null' );
var isPositiveInteger = require( '@stdlib/assert/is-positive-integer' ).isPrimitive;
// MAIN //
/**
* Validates function options.
*
* @private
* @param {Object} opts - destination object
* @param {Options} options - function options
* @param {boolean} [options.skip] - boolean indicating whether to skip a benchmark
* @param {(PositiveInteger|null)} [options.iterations] - number of iterations
* @param {PositiveInteger} [options.repeats] - number of repeats
* @param {PositiveInteger} [options.timeout] - number of milliseconds before a benchmark automatically fails
* @returns {(Error|null)} error object or null
*
* @example
* var opts = {};
* var options = {
* 'skip': false,
* 'iterations': 1e6,
* 'repeats': 3,
* 'timeout': 10000
* };
*
* var err = validate( opts, options );
* if ( err ) {
* throw err;
* }
*/
function validate( opts, options ) {
if ( !isObject( options ) ) {
return new TypeError( 'invalid argument. Options argument must be an object. Value: `' + options + '`.' );
}
if ( hasOwnProp( options, 'skip' ) ) {
opts.skip = options.skip;
if ( !isBoolean( opts.skip ) ) {
return new TypeError( 'invalid option. `skip` option must be a boolean primitive. Option: `' + opts.skip + '`.' );
}
}
if ( hasOwnProp( options, 'iterations' ) ) {
opts.iterations = options.iterations;
if (
!isPositiveInteger( opts.iterations ) &&
!isNull( opts.iterations )
) {
return new TypeError( 'invalid option. `iterations` option must be either a positive integer or `null`. Option: `' + opts.iterations + '`.' );
}
}
if ( hasOwnProp( options, 'repeats' ) ) {
opts.repeats = options.repeats;
if ( !isPositiveInteger( opts.repeats ) ) {
return new TypeError( 'invalid option. `repeats` option must be a positive integer. Option: `' + opts.repeats + '`.' );
}
}
if ( hasOwnProp( options, 'timeout' ) ) {
opts.timeout = options.timeout;
if ( !isPositiveInteger( opts.timeout ) ) {
return new TypeError( 'invalid option. `timeout` option must be a positive integer. Option: `' + opts.timeout + '`.' );
}
}
return null;
}
// EXPORTS //
module.exports = validate;
},{"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-boolean":81,"@stdlib/assert/is-null":135,"@stdlib/assert/is-plain-object":147,"@stdlib/assert/is-positive-integer":149}],208:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Benchmark harness.
*
* @module @stdlib/bench/harness
*
* @example
* var bench = require( '@stdlib/bench/harness' );
*
* bench( 'beep', function benchmark( b ) {
* var x;
* var i;
* b.tic();
* for ( i = 0; i < b.iterations; i++ ) {
* x = Math.sin( Math.random() );
* if ( x !== x ) {
* b.ok( false, 'should not return NaN' );
* }
* }
* b.toc();
* if ( x !== x ) {
* b.ok( false, 'should not return NaN' );
* }
* b.end();
* });
*/
// MODULES //
var bench = require( './bench.js' );
// EXPORTS //
module.exports = bench;
},{"./bench.js":180}],209:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var TransformStream = require( '@stdlib/streams/node/transform' );
var fromCodePoint = require( '@stdlib/string/from-code-point' );
var log = require( './log.js' );
// MAIN //
/**
* Returns a Transform stream for logging to the console.
*
* @private
* @returns {TransformStream} transform stream
*/
function createStream() {
var stream;
var line;
stream = new TransformStream({
'transform': transform,
'flush': flush
});
line = '';
return stream;
/**
* Callback invoked upon receiving a new chunk.
*
* @private
* @param {(Buffer|string)} chunk - chunk
* @param {string} enc - Buffer encoding
* @param {Callback} clbk - callback to invoke after transforming the streamed chunk
*/
function transform( chunk, enc, clbk ) {
var c;
var i;
for ( i = 0; i < chunk.length; i++ ) {
c = fromCodePoint( chunk[ i ] );
if ( c === '\n' ) {
flush();
} else {
line += c;
}
}
clbk();
}
/**
* Callback to flush data to `stdout`.
*
* @private
* @param {Callback} [clbk] - callback to invoke after processing data
* @returns {void}
*/
function flush( clbk ) {
try {
log( line );
} catch ( err ) {
stream.emit( 'error', err );
}
line = '';
if ( clbk ) {
return clbk();
}
}
}
// EXPORTS //
module.exports = createStream;
},{"./log.js":210,"@stdlib/streams/node/transform":320,"@stdlib/string/from-code-point":324}],210:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Writes a string to the console.
*
* @private
* @param {string} str - string to write
*/
function log( str ) {
console.log( str ); // eslint-disable-line no-console
}
// EXPORTS //
module.exports = log;
},{}],211:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Removes any pending benchmarks.
*
* @private
*/
function clear() {
/* eslint-disable no-invalid-this */
this._benchmarks.length = 0;
}
// EXPORTS //
module.exports = clear;
},{}],212:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Closes a benchmark runner.
*
* @private
* @returns {void}
*/
function closeRunner() {
/* eslint-disable no-invalid-this */
var self = this;
if ( this._closed ) {
return;
}
this._closed = true;
if ( this._benchmarks.length ) {
this.clear();
this._stream.write( '# WARNING: harness closed before completion.\n' );
} else {
this._stream.write( '#\n' );
this._stream.write( '1..'+this.total+'\n' );
this._stream.write( '# total '+this.total+'\n' );
this._stream.write( '# pass '+this.pass+'\n' );
if ( this.fail ) {
this._stream.write( '# fail '+this.fail+'\n' );
}
if ( this.skip ) {
this._stream.write( '# skip '+this.skip+'\n' );
}
if ( this.todo ) {
this._stream.write( '# todo '+this.todo+'\n' );
}
if ( !this.fail ) {
this._stream.write( '#\n# ok\n' );
}
}
this._stream.once( 'close', onClose );
this._stream.destroy();
/**
* Callback invoked upon a `close` event.
*
* @private
*/
function onClose() {
self.emit( 'close' );
}
}
// EXPORTS //
module.exports = closeRunner;
},{}],213:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
/* eslint-disable no-underscore-dangle */
'use strict';
// MODULES //
var TransformStream = require( '@stdlib/streams/node/transform' );
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var nextTick = require( './../utils/next_tick.js' );
// VARIABLES //
var TAP_HEADER = 'TAP version 13';
// MAIN //
/**
* Creates a results stream.
*
* @private
* @param {Options} [options] - stream options
* @throws {TypeError} options argument must be an object
* @throws {TypeError} must provide valid options
* @returns {TransformStream} transform stream
*/
function createStream( options ) {
/* eslint-disable no-invalid-this */
var stream;
var opts;
var self;
var id;
self = this;
if ( arguments.length ) {
opts = options;
} else {
opts = {};
}
stream = new TransformStream( opts );
if ( opts.objectMode ) {
id = 0;
this.on( '_push', onPush );
this.on( 'done', onDone );
} else {
stream.write( TAP_HEADER+'\n' );
this._stream.pipe( stream );
}
this.on( '_run', onRun );
return stream;
/**
* Runs the next benchmark.
*
* @private
*/
function next() {
nextTick( onTick );
}
/**
* Callback invoked upon the next tick.
*
* @private
* @returns {void}
*/
function onTick() {
var b = self._benchmarks.shift();
if ( b ) {
b.run();
if ( !b.ended() ) {
return b.once( 'end', next );
}
return next();
}
self._running = false;
self.emit( 'done' );
}
/**
* Callback invoked upon a run event.
*
* @private
* @returns {void}
*/
function onRun() {
if ( !self._running ) {
self._running = true;
return next();
}
}
/**
* Callback invoked upon a push event.
*
* @private
* @param {Benchmark} b - benchmark
*/
function onPush( b ) {
var bid = id;
id += 1;
b.once( 'prerun', onPreRun );
b.on( 'result', onResult );
b.on( 'end', onEnd );
/**
* Callback invoked upon a `prerun` event.
*
* @private
*/
function onPreRun() {
var row = {
'type': 'benchmark',
'name': b.name,
'id': bid
};
stream.write( row );
}
/**
* Callback invoked upon a `result` event.
*
* @private
* @param {(Object|string)} res - result
*/
function onResult( res ) {
if ( isString( res ) ) {
res = {
'benchmark': bid,
'type': 'comment',
'name': res
};
} else if ( res.operator === 'result' ) {
res.benchmark = bid;
res.type = 'result';
} else {
res.benchmark = bid;
res.type = 'assert';
}
stream.write( res );
}
/**
* Callback invoked upon an `end` event.
*
* @private
*/
function onEnd() {
stream.write({
'benchmark': bid,
'type': 'end'
});
}
}
/**
* Callback invoked upon a `done` event.
*
* @private
*/
function onDone() {
stream.destroy();
}
}
// EXPORTS //
module.exports = createStream;
},{"./../utils/next_tick.js":222,"@stdlib/assert/is-string":158,"@stdlib/streams/node/transform":320}],214:[function(require,module,exports){
/* eslint-disable stdlib/jsdoc-require-throws-tags */
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var replace = require( '@stdlib/string/replace' );
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var reEOL = require( '@stdlib/regexp/eol' );
// VARIABLES //
var RE_WHITESPACE = /\s+/g;
// MAIN //
/**
* Encodes an assertion.
*
* @private
* @param {Object} result - result
* @param {PositiveInteger} count - result count
* @returns {string} encoded assertion
*/
function encodeAssertion( result, count ) {
var actualStack;
var errorStack;
var expected;
var actual;
var indent;
var stack;
var lines;
var out;
var i;
out = '';
if ( !result.ok ) {
out += 'not ';
}
// Add result count:
out += 'ok ' + count;
// Add description:
if ( result.name ) {
out += ' ' + replace( result.name.toString(), RE_WHITESPACE, ' ' );
}
// Append directives:
if ( result.skip ) {
out += ' # SKIP';
} else if ( result.todo ) {
out += ' # TODO';
}
out += '\n';
if ( result.ok ) {
return out;
}
// Format diagnostics as YAML...
indent = ' ';
out += indent + '---\n';
out += indent + 'operator: ' + result.operator + '\n';
if (
hasOwnProp( result, 'actual' ) ||
hasOwnProp( result, 'expected' )
) {
// TODO: inspect object logic (https://github.com/substack/tape/blob/master/lib/results.js#L145)
expected = result.expected;
actual = result.actual;
if ( actual !== actual && expected !== expected ) {
throw new Error( 'TODO: remove me' );
}
}
if ( result.at ) {
out += indent + 'at: ' + result.at + '\n';
}
if ( result.actual ) {
actualStack = result.actual.stack;
}
if ( result.error ) {
errorStack = result.error.stack;
}
if ( actualStack ) {
stack = actualStack;
} else {
stack = errorStack;
}
if ( stack ) {
lines = stack.toString().split( reEOL.REGEXP );
out += indent + 'stack: |-\n';
for ( i = 0; i < lines.length; i++ ) {
out += indent + ' ' + lines[ i ] + '\n';
}
}
out += indent + '...\n';
return out;
}
// EXPORTS //
module.exports = encodeAssertion;
},{"@stdlib/assert/has-own-property":53,"@stdlib/regexp/eol":300,"@stdlib/string/replace":326}],215:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// VARIABLES //
var YAML_INDENT = ' ';
var YAML_BEGIN = YAML_INDENT + '---\n';
var YAML_END = YAML_INDENT + '...\n';
// MAIN //
/**
* Encodes a result as a YAML block.
*
* @private
* @param {Object} result - result
* @returns {string} encoded result
*/
function encodeResult( result ) {
var out = YAML_BEGIN;
out += YAML_INDENT + 'iterations: '+result.iterations+'\n';
out += YAML_INDENT + 'elapsed: '+result.elapsed+'\n';
out += YAML_INDENT + 'rate: '+result.rate+'\n';
out += YAML_END;
return out;
}
// EXPORTS //
module.exports = encodeResult;
},{}],216:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Forcefully exits a benchmark runner.
*
* @private
*/
function exit() {
/* eslint-disable no-invalid-this */
var self;
var i;
for ( i = 0; i < this._benchmarks.length; i++ ) {
this._benchmarks[ i ].exit();
}
self = this;
this.clear();
this._stream.once( 'close', onClose );
this._stream.destroy();
/**
* Callback invoked upon a `close` event.
*
* @private
*/
function onClose() {
self.emit( 'close' );
}
}
// EXPORTS //
module.exports = exit;
},{}],217:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var EventEmitter = require( 'events' ).EventEmitter;
var inherit = require( '@stdlib/utils/inherit' );
var defineProperty = require( '@stdlib/utils/define-property' );
var TransformStream = require( '@stdlib/streams/node/transform' );
var push = require( './push.js' );
var createStream = require( './create_stream.js' );
var run = require( './run.js' );
var clear = require( './clear.js' );
var close = require( './close.js' ); // eslint-disable-line stdlib/no-redeclare
var exit = require( './exit.js' );
// MAIN //
/**
* Benchmark runner.
*
* @private
* @constructor
* @returns {Runner} Runner instance
*
* @example
* var runner = new Runner();
*/
function Runner() {
if ( !( this instanceof Runner ) ) {
return new Runner();
}
EventEmitter.call( this );
// Private properties:
defineProperty( this, '_benchmarks', {
'value': [],
'configurable': false,
'writable': false,
'enumerable': false
});
defineProperty( this, '_stream', {
'value': new TransformStream(),
'configurable': false,
'writable': false,
'enumerable': false
});
defineProperty( this, '_closed', {
'value': false,
'configurable': false,
'writable': true,
'enumerable': false
});
defineProperty( this, '_running', {
'value': false,
'configurable': false,
'writable': true,
'enumerable': false
});
// Public properties:
defineProperty( this, 'total', {
'value': 0,
'configurable': false,
'writable': true,
'enumerable': true
});
defineProperty( this, 'fail', {
'value': 0,
'configurable': false,
'writable': true,
'enumerable': true
});
defineProperty( this, 'pass', {
'value': 0,
'configurable': false,
'writable': true,
'enumerable': true
});
defineProperty( this, 'skip', {
'value': 0,
'configurable': false,
'writable': true,
'enumerable': true
});
defineProperty( this, 'todo', {
'value': 0,
'configurable': false,
'writable': true,
'enumerable': true
});
return this;
}
/*
* Inherit from the `EventEmitter` prototype.
*/
inherit( Runner, EventEmitter );
/**
* Adds a new benchmark.
*
* @private
* @memberof Runner.prototype
* @function push
* @param {Benchmark} b - benchmark
*/
defineProperty( Runner.prototype, 'push', {
'value': push,
'configurable': false,
'writable': false,
'enumerable': false
});
/**
* Creates a results stream.
*
* @private
* @memberof Runner.prototype
* @function createStream
* @param {Options} [options] - stream options
* @returns {TransformStream} transform stream
*/
defineProperty( Runner.prototype, 'createStream', {
'value': createStream,
'configurable': false,
'writable': false,
'enumerable': false
});
/**
* Runs pending benchmarks.
*
* @private
* @memberof Runner.prototype
* @function run
*/
defineProperty( Runner.prototype, 'run', {
'value': run,
'configurable': false,
'writable': false,
'enumerable': false
});
/**
* Removes any pending benchmarks.
*
* @private
* @memberof Runner.prototype
* @function clear
*/
defineProperty( Runner.prototype, 'clear', {
'value': clear,
'configurable': false,
'writable': false,
'enumerable': false
});
/**
* Closes a benchmark runner.
*
* @private
* @memberof Runner.prototype
* @function close
*/
defineProperty( Runner.prototype, 'close', {
'value': close,
'configurable': false,
'writable': false,
'enumerable': false
});
/**
* Forcefully exits a benchmark runner.
*
* @private
* @memberof Runner.prototype
* @function exit
*/
defineProperty( Runner.prototype, 'exit', {
'value': exit,
'configurable': false,
'writable': false,
'enumerable': false
});
// EXPORTS //
module.exports = Runner;
},{"./clear.js":211,"./close.js":212,"./create_stream.js":213,"./exit.js":216,"./push.js":218,"./run.js":219,"@stdlib/streams/node/transform":320,"@stdlib/utils/define-property":351,"@stdlib/utils/inherit":372,"events":425}],218:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
/* eslint-disable no-underscore-dangle */
'use strict';
// MODULES //
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var encodeAssertion = require( './encode_assertion.js' );
var encodeResult = require( './encode_result.js' );
// MAIN //
/**
* Adds a new benchmark.
*
* @private
* @param {Benchmark} b - benchmark
*/
function push( b ) {
/* eslint-disable no-invalid-this */
var self = this;
this._benchmarks.push( b );
b.once( 'prerun', onPreRun );
b.on( 'result', onResult );
this.emit( '_push', b );
/**
* Callback invoked upon a `prerun` event.
*
* @private
*/
function onPreRun() {
self._stream.write( '# '+b.name+'\n' );
}
/**
* Callback invoked upon a `result` event.
*
* @private
* @param {(Object|string)} res - result
* @returns {void}
*/
function onResult( res ) {
// Check for a comment...
if ( isString( res ) ) {
return self._stream.write( '# '+res+'\n' );
}
if ( res.operator === 'result' ) {
res = encodeResult( res );
return self._stream.write( res );
}
self.total += 1;
if ( res.ok ) {
if ( res.skip ) {
self.skip += 1;
} else if ( res.todo ) {
self.todo += 1;
}
self.pass += 1;
}
// According to the TAP spec, todos pass even if not "ok"...
else if ( res.todo ) {
self.pass += 1;
self.todo += 1;
}
// Everything else is a failure...
else {
self.fail += 1;
}
res = encodeAssertion( res, self.total );
self._stream.write( res );
}
}
// EXPORTS //
module.exports = push;
},{"./encode_assertion.js":214,"./encode_result.js":215,"@stdlib/assert/is-string":158}],219:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Runs pending benchmarks.
*
* @private
*/
function run() {
/* eslint-disable no-invalid-this */
this.emit( '_run' );
}
// EXPORTS //
module.exports = run;
},{}],220:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var IS_BROWSER = require( '@stdlib/assert/is-browser' );
var canExit = require( './can_exit.js' );
// MAIN //
var bool = ( !IS_BROWSER && canExit );
// EXPORTS //
module.exports = bool;
},{"./can_exit.js":221,"@stdlib/assert/is-browser":87}],221:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var proc = require( './process.js' );
// MAIN //
var bool = ( proc && typeof proc.exit === 'function' );
// EXPORTS //
module.exports = bool;
},{"./process.js":223}],222:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Runs a function on a subsequent turn of the event loop.
*
* ## Notes
*
* - `process.nextTick` is only Node.js.
* - `setImmediate` is non-standard.
* - Everything else is browser based (e.g., mutation observer, requestAnimationFrame, etc).
* - Only API which is universal is `setTimeout`.
* - Note that `0` is not actually `0ms`. Browser environments commonly have a minimum delay of `4ms`. This is acceptable. Here, the main intent of this function is to give the runtime a chance to run garbage collection, clear state, and tend to any other pending tasks before returning control to benchmark tasks. The larger aim (attainable or not) is to provide each benchmark run with as much of a fresh state as possible.
*
*
* @private
* @param {Function} fcn - function to run upon a subsequent turn of the event loop
*/
function nextTick( fcn ) {
setTimeout( fcn, 0 );
}
// EXPORTS //
module.exports = nextTick;
},{}],223:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var proc = require( 'process' );
// EXPORTS //
module.exports = proc;
},{"process":436}],224:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Benchmark harness.
*
* @module @stdlib/bench
*
* @example
* var bench = require( '@stdlib/bench' );
*
* bench( 'beep', function benchmark( b ) {
* var x;
* var i;
* b.tic();
* for ( i = 0; i < b.iterations; i++ ) {
* x = Math.sin( Math.random() );
* if ( x !== x ) {
* b.ok( false, 'should not return NaN' );
* }
* }
* b.toc();
* if ( x !== x ) {
* b.ok( false, 'should not return NaN' );
* }
* b.end();
* });
*/
// MODULES //
var bench = require( '@stdlib/bench/harness' );
// EXPORTS //
module.exports = bench;
},{"@stdlib/bench/harness":208}],225:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* BLAS level 1 routine to copy values from `x` into `y`.
*
* @module @stdlib/blas/base/gcopy
*
* @example
* var gcopy = require( '@stdlib/blas/base/gcopy' );
*
* var x = [ 1.0, 2.0, 3.0, 4.0, 5.0 ];
* var y = [ 6.0, 7.0, 8.0, 9.0, 10.0 ];
*
* gcopy( x.length, x, 1, y, 1 );
* // y => [ 1.0, 2.0, 3.0, 4.0, 5.0 ]
*
* @example
* var gcopy = require( '@stdlib/blas/base/gcopy' );
*
* var x = [ 1.0, 2.0, 3.0, 4.0, 5.0 ];
* var y = [ 6.0, 7.0, 8.0, 9.0, 10.0 ];
*
* gcopy.ndarray( x.length, x, 1, 0, y, 1, 0 );
* // y => [ 1.0, 2.0, 3.0, 4.0, 5.0 ]
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var gcopy = require( './main.js' );
var ndarray = require( './ndarray.js' );
// MAIN //
setReadOnly( gcopy, 'ndarray', ndarray );
// EXPORTS //
module.exports = gcopy;
},{"./main.js":226,"./ndarray.js":227,"@stdlib/utils/define-nonenumerable-read-only-property":344}],226:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// VARIABLES //
var M = 8;
// MAIN //
/**
* Copies values from `x` into `y`.
*
* @param {PositiveInteger} N - number of values to copy
* @param {NumericArray} x - input array
* @param {integer} strideX - `x` stride length
* @param {NumericArray} y - destination array
* @param {integer} strideY - `y` stride length
* @returns {NumericArray} `y`
*
* @example
* var x = [ 1.0, 2.0, 3.0, 4.0, 5.0 ];
* var y = [ 6.0, 7.0, 8.0, 9.0, 10.0 ];
*
* gcopy( x.length, x, 1, y, 1 );
* // y => [ 1.0, 2.0, 3.0, 4.0, 5.0 ]
*/
function gcopy( N, x, strideX, y, strideY ) {
var ix;
var iy;
var m;
var i;
if ( N <= 0 ) {
return y;
}
// Use unrolled loops if both strides are equal to `1`...
if ( strideX === 1 && strideY === 1 ) {
m = N % M;
// If we have a remainder, run a clean-up loop...
if ( m > 0 ) {
for ( i = 0; i < m; i++ ) {
y[ i ] = x[ i ];
}
}
if ( N < M ) {
return y;
}
for ( i = m; i < N; i += M ) {
y[ i ] = x[ i ];
y[ i+1 ] = x[ i+1 ];
y[ i+2 ] = x[ i+2 ];
y[ i+3 ] = x[ i+3 ];
y[ i+4 ] = x[ i+4 ];
y[ i+5 ] = x[ i+5 ];
y[ i+6 ] = x[ i+6 ];
y[ i+7 ] = x[ i+7 ];
}
return y;
}
if ( strideX < 0 ) {
ix = (1-N) * strideX;
} else {
ix = 0;
}
if ( strideY < 0 ) {
iy = (1-N) * strideY;
} else {
iy = 0;
}
for ( i = 0; i < N; i++ ) {
y[ iy ] = x[ ix ];
ix += strideX;
iy += strideY;
}
return y;
}
// EXPORTS //
module.exports = gcopy;
},{}],227:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// VARIABLES //
var M = 8;
// MAIN //
/**
* Copies values from `x` into `y`.
*
* @param {PositiveInteger} N - number of values to copy
* @param {NumericArray} x - input array
* @param {integer} strideX - `x` stride length
* @param {NonNegativeInteger} offsetX - starting `x` index
* @param {NumericArray} y - destination array
* @param {integer} strideY - `y` stride length
* @param {NonNegativeInteger} offsetY - starting `y` index
* @returns {NumericArray} `y`
*
* @example
* var x = [ 1.0, 2.0, 3.0, 4.0, 5.0 ];
* var y = [ 6.0, 7.0, 8.0, 9.0, 10.0 ];
*
* gcopy( x.length, x, 1, 0, y, 1, 0 );
* // y => [ 1.0, 2.0, 3.0, 4.0, 5.0 ]
*/
function gcopy( N, x, strideX, offsetX, y, strideY, offsetY ) {
var ix;
var iy;
var m;
var i;
if ( N <= 0 ) {
return y;
}
ix = offsetX;
iy = offsetY;
// Use unrolled loops if both strides are equal to `1`...
if ( strideX === 1 && strideY === 1 ) {
m = N % M;
// If we have a remainder, run a clean-up loop...
if ( m > 0 ) {
for ( i = 0; i < m; i++ ) {
y[ iy ] = x[ ix ];
ix += strideX;
iy += strideY;
}
}
if ( N < M ) {
return y;
}
for ( i = m; i < N; i += M ) {
y[ iy ] = x[ ix ];
y[ iy+1 ] = x[ ix+1 ];
y[ iy+2 ] = x[ ix+2 ];
y[ iy+3 ] = x[ ix+3 ];
y[ iy+4 ] = x[ ix+4 ];
y[ iy+5 ] = x[ ix+5 ];
y[ iy+6 ] = x[ ix+6 ];
y[ iy+7 ] = x[ ix+7 ];
ix += M;
iy += M;
}
return y;
}
for ( i = 0; i < N; i++ ) {
y[ iy ] = x[ ix ];
ix += strideX;
iy += strideY;
}
return y;
}
// EXPORTS //
module.exports = gcopy;
},{}],228:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var ctor = require( 'buffer' ).Buffer; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = ctor;
},{"buffer":426}],229:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Buffer constructor.
*
* @module @stdlib/buffer/ctor
*
* @example
* var ctor = require( '@stdlib/buffer/ctor' );
*
* var b = new ctor( [ 1, 2, 3, 4 ] );
* // returns <Buffer>
*/
// MODULES //
var hasNodeBufferSupport = require( '@stdlib/assert/has-node-buffer-support' );
var main = require( './buffer.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var ctor;
if ( hasNodeBufferSupport() ) {
ctor = main;
} else {
ctor = polyfill;
}
// EXPORTS //
module.exports = ctor;
},{"./buffer.js":228,"./polyfill.js":230,"@stdlib/assert/has-node-buffer-support":51}],230:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// TODO: write (browser) polyfill
// MAIN //
/**
* Buffer constructor.
*
* @throws {Error} not implemented
*/
function polyfill() {
throw new Error( 'not implemented' );
}
// EXPORTS //
module.exports = polyfill;
},{}],231:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isFunction = require( '@stdlib/assert/is-function' );
var Buffer = require( '@stdlib/buffer/ctor' );
// MAIN //
var bool = isFunction( Buffer.from );
// EXPORTS //
module.exports = bool;
},{"@stdlib/assert/is-function":102,"@stdlib/buffer/ctor":229}],232:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Copy buffer data to a new `Buffer` instance.
*
* @module @stdlib/buffer/from-buffer
*
* @example
* var fromArray = require( '@stdlib/buffer/from-array' );
* var copyBuffer = require( '@stdlib/buffer/from-buffer' );
*
* var b1 = fromArray( [ 1, 2, 3, 4 ] );
* // returns <Buffer>
*
* var b2 = copyBuffer( b1 );
* // returns <Buffer>
*/
// MODULES //
var hasFrom = require( './has_from.js' );
var main = require( './main.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var copyBuffer;
if ( hasFrom ) {
copyBuffer = main;
} else {
copyBuffer = polyfill;
}
// EXPORTS //
module.exports = copyBuffer;
},{"./has_from.js":231,"./main.js":233,"./polyfill.js":234}],233:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isBuffer = require( '@stdlib/assert/is-buffer' );
var Buffer = require( '@stdlib/buffer/ctor' );
// MAIN //
/**
* Copies buffer data to a new `Buffer` instance.
*
* @param {Buffer} buffer - buffer from which to copy
* @throws {TypeError} must provide a `Buffer` instance
* @returns {Buffer} new `Buffer` instance
*
* @example
* var fromArray = require( '@stdlib/buffer/from-array' );
*
* var b1 = fromArray( [ 1, 2, 3, 4 ] );
* // returns <Buffer>
*
* var b2 = fromBuffer( b1 );
* // returns <Buffer>
*/
function fromBuffer( buffer ) {
if ( !isBuffer( buffer ) ) {
throw new TypeError( 'invalid argument. Must provide a Buffer. Value: `' + buffer + '`' );
}
return Buffer.from( buffer );
}
// EXPORTS //
module.exports = fromBuffer;
},{"@stdlib/assert/is-buffer":88,"@stdlib/buffer/ctor":229}],234:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isBuffer = require( '@stdlib/assert/is-buffer' );
var Buffer = require( '@stdlib/buffer/ctor' );
// MAIN //
/**
* Copies buffer data to a new `Buffer` instance.
*
* @param {Buffer} buffer - buffer from which to copy
* @throws {TypeError} must provide a `Buffer` instance
* @returns {Buffer} new `Buffer` instance
*
* @example
* var fromArray = require( '@stdlib/buffer/from-array' );
*
* var b1 = fromArray( [ 1, 2, 3, 4 ] );
* // returns <Buffer>
*
* var b2 = fromBuffer( b1 );
* // returns <Buffer>
*/
function fromBuffer( buffer ) {
if ( !isBuffer( buffer ) ) {
throw new TypeError( 'invalid argument. Must provide a Buffer. Value: `' + buffer + '`' );
}
return new Buffer( buffer ); // eslint-disable-line no-buffer-constructor
}
// EXPORTS //
module.exports = fromBuffer;
},{"@stdlib/assert/is-buffer":88,"@stdlib/buffer/ctor":229}],235:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Maximum length of a generic array.
*
* @module @stdlib/constants/array/max-array-length
*
* @example
* var MAX_ARRAY_LENGTH = require( '@stdlib/constants/array/max-array-length' );
* // returns 4294967295
*/
// MAIN //
/**
* Maximum length of a generic array.
*
* ```tex
* 2^{32} - 1
* ```
*
* @constant
* @type {uinteger32}
* @default 4294967295
*/
var MAX_ARRAY_LENGTH = 4294967295>>>0; // asm type annotation
// EXPORTS //
module.exports = MAX_ARRAY_LENGTH;
},{}],236:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Maximum length of a typed array.
*
* @module @stdlib/constants/array/max-typed-array-length
*
* @example
* var MAX_TYPED_ARRAY_LENGTH = require( '@stdlib/constants/array/max-typed-array-length' );
* // returns 9007199254740991
*/
// MAIN //
/**
* Maximum length of a typed array.
*
* ```tex
* 2^{53} - 1
* ```
*
* @constant
* @type {number}
* @default 9007199254740991
*/
var MAX_TYPED_ARRAY_LENGTH = 9007199254740991;
// EXPORTS //
module.exports = MAX_TYPED_ARRAY_LENGTH;
},{}],237:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Difference between one and the smallest value greater than one that can be represented as a double-precision floating-point number.
*
* @module @stdlib/constants/float64/eps
* @type {number}
*
* @example
* var FLOAT64_EPSILON = require( '@stdlib/constants/float64/eps' );
* // returns 2.220446049250313e-16
*/
// MAIN //
/**
* Difference between one and the smallest value greater than one that can be represented as a double-precision floating-point number.
*
* ## Notes
*
* The difference is
*
* ```tex
* \frac{1}{2^{52}}
* ```
*
* @constant
* @type {number}
* @default 2.220446049250313e-16
* @see [IEEE 754]{@link https://en.wikipedia.org/wiki/IEEE_754-1985}
* @see [Machine Epsilon]{@link https://en.wikipedia.org/wiki/Machine_epsilon}
*/
var FLOAT64_EPSILON = 2.2204460492503130808472633361816E-16;
// EXPORTS //
module.exports = FLOAT64_EPSILON;
},{}],238:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* The bias of a double-precision floating-point number's exponent.
*
* @module @stdlib/constants/float64/exponent-bias
* @type {integer32}
*
* @example
* var FLOAT64_EXPONENT_BIAS = require( '@stdlib/constants/float64/exponent-bias' );
* // returns 1023
*/
// MAIN //
/**
* Bias of a double-precision floating-point number's exponent.
*
* ## Notes
*
* The bias can be computed via
*
* ```tex
* \mathrm{bias} = 2^{k-1} - 1
* ```
*
* where \\(k\\) is the number of bits in the exponent; here, \\(k = 11\\).
*
* @constant
* @type {integer32}
* @default 1023
* @see [IEEE 754]{@link https://en.wikipedia.org/wiki/IEEE_754-1985}
*/
var FLOAT64_EXPONENT_BIAS = 1023|0; // asm type annotation
// EXPORTS //
module.exports = FLOAT64_EXPONENT_BIAS;
},{}],239:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* High word mask for the exponent of a double-precision floating-point number.
*
* @module @stdlib/constants/float64/high-word-exponent-mask
* @type {uinteger32}
*
* @example
* var FLOAT64_HIGH_WORD_EXPONENT_MASK = require( '@stdlib/constants/float64/high-word-exponent-mask' );
* // returns 2146435072
*/
// MAIN //
/**
* High word mask for the exponent of a double-precision floating-point number.
*
* ## Notes
*
* The high word mask for the exponent of a double-precision floating-point number is an unsigned 32-bit integer with the value \\( 2146435072 \\), which corresponds to the bit sequence
*
* ```binarystring
* 0 11111111111 00000000000000000000
* ```
*
* @constant
* @type {uinteger32}
* @default 0x7ff00000
* @see [IEEE 754]{@link https://en.wikipedia.org/wiki/IEEE_754-1985}
*/
var FLOAT64_HIGH_WORD_EXPONENT_MASK = 0x7ff00000;
// EXPORTS //
module.exports = FLOAT64_HIGH_WORD_EXPONENT_MASK;
},{}],240:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* High word mask for the significand of a double-precision floating-point number.
*
* @module @stdlib/constants/float64/high-word-significand-mask
* @type {uinteger32}
*
* @example
* var FLOAT64_HIGH_WORD_SIGNIFICAND_MASK = require( '@stdlib/constants/float64/high-word-significand-mask' );
* // returns 1048575
*/
// MAIN //
/**
* High word mask for the significand of a double-precision floating-point number.
*
* ## Notes
*
* The high word mask for the significand of a double-precision floating-point number is an unsigned 32-bit integer with the value \\( 1048575 \\), which corresponds to the bit sequence
*
* ```binarystring
* 0 00000000000 11111111111111111111
* ```
*
* @constant
* @type {uinteger32}
* @default 0x000fffff
* @see [IEEE 754]{@link https://en.wikipedia.org/wiki/IEEE_754-1985}
*/
var FLOAT64_HIGH_WORD_SIGNIFICAND_MASK = 0x000fffff;
// EXPORTS //
module.exports = FLOAT64_HIGH_WORD_SIGNIFICAND_MASK;
},{}],241:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Natural logarithm of `2`.
*
* @module @stdlib/constants/float64/ln-two
* @type {number}
*
* @example
* var LN2 = require( '@stdlib/constants/float64/ln-two' );
* // returns 0.6931471805599453
*/
// MAIN //
/**
* Natural logarithm of `2`.
*
* ```tex
* \ln 2
* ```
*
* @constant
* @type {number}
* @default 0.6931471805599453
*/
var LN2 = 6.93147180559945309417232121458176568075500134360255254120680009493393621969694715605863326996418687542001481021e-01; // eslint-disable-line max-len
// EXPORTS //
module.exports = LN2;
},{}],242:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Maximum safe double-precision floating-point integer.
*
* @module @stdlib/constants/float64/max-safe-integer
* @type {number}
*
* @example
* var FLOAT64_MAX_SAFE_INTEGER = require( '@stdlib/constants/float64/max-safe-integer' );
* // returns 9007199254740991
*/
// MAIN //
/**
* Maximum safe double-precision floating-point integer.
*
* ## Notes
*
* The integer has the value
*
* ```tex
* 2^{53} - 1
* ```
*
* @constant
* @type {number}
* @default 9007199254740991
* @see [Safe Integers]{@link http://www.2ality.com/2013/10/safe-integers.html}
* @see [IEEE 754]{@link https://en.wikipedia.org/wiki/IEEE_754-1985}
*/
var FLOAT64_MAX_SAFE_INTEGER = 9007199254740991;
// EXPORTS //
module.exports = FLOAT64_MAX_SAFE_INTEGER;
},{}],243:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Double-precision floating-point negative infinity.
*
* @module @stdlib/constants/float64/ninf
* @type {number}
*
* @example
* var FLOAT64_NINF = require( '@stdlib/constants/float64/ninf' );
* // returns -Infinity
*/
// MODULES //
var Number = require( '@stdlib/number/ctor' );
// MAIN //
/**
* Double-precision floating-point negative infinity.
*
* ## Notes
*
* Double-precision floating-point negative infinity has the bit sequence
*
* ```binarystring
* 1 11111111111 00000000000000000000 00000000000000000000000000000000
* ```
*
* @constant
* @type {number}
* @default Number.NEGATIVE_INFINITY
* @see [IEEE 754]{@link https://en.wikipedia.org/wiki/IEEE_754-1985}
*/
var FLOAT64_NINF = Number.NEGATIVE_INFINITY;
// EXPORTS //
module.exports = FLOAT64_NINF;
},{"@stdlib/number/ctor":273}],244:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Double-precision floating-point positive infinity.
*
* @module @stdlib/constants/float64/pinf
* @type {number}
*
* @example
* var FLOAT64_PINF = require( '@stdlib/constants/float64/pinf' );
* // returns Infinity
*/
// MAIN //
/**
* Double-precision floating-point positive infinity.
*
* ## Notes
*
* Double-precision floating-point positive infinity has the bit sequence
*
* ```binarystring
* 0 11111111111 00000000000000000000 00000000000000000000000000000000
* ```
*
* @constant
* @type {number}
* @default Number.POSITIVE_INFINITY
* @see [IEEE 754]{@link https://en.wikipedia.org/wiki/IEEE_754-1985}
*/
var FLOAT64_PINF = Number.POSITIVE_INFINITY; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = FLOAT64_PINF;
},{}],245:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Maximum signed 16-bit integer.
*
* @module @stdlib/constants/int16/max
* @type {integer32}
*
* @example
* var INT16_MAX = require( '@stdlib/constants/int16/max' );
* // returns 32767
*/
// MAIN //
/**
* Maximum signed 16-bit integer.
*
* ## Notes
*
* The number has the value
*
* ```tex
* 2^{15} - 1
* ```
*
* which corresponds to the bit sequence
*
* ```binarystring
* 0111111111111111
* ```
*
* @constant
* @type {integer32}
* @default 32767
*/
var INT16_MAX = 32767|0; // asm type annotation
// EXPORTS //
module.exports = INT16_MAX;
},{}],246:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Minimum signed 16-bit integer.
*
* @module @stdlib/constants/int16/min
* @type {integer32}
*
* @example
* var INT16_MIN = require( '@stdlib/constants/int16/min' );
* // returns -32768
*/
// MAIN //
/**
* Minimum signed 16-bit integer.
*
* ## Notes
*
* The number has the value
*
* ```tex
* -(2^{15})
* ```
*
* which corresponds to the two's complement bit sequence
*
* ```binarystring
* 1000000000000000
* ```
*
* @constant
* @type {integer32}
* @default -32768
*/
var INT16_MIN = -32768|0; // asm type annotation
// EXPORTS //
module.exports = INT16_MIN;
},{}],247:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Maximum signed 32-bit integer.
*
* @module @stdlib/constants/int32/max
* @type {integer32}
*
* @example
* var INT32_MAX = require( '@stdlib/constants/int32/max' );
* // returns 2147483647
*/
// MAIN //
/**
* Maximum signed 32-bit integer.
*
* ## Notes
*
* The number has the value
*
* ```tex
* 2^{31} - 1
* ```
*
* which corresponds to the bit sequence
*
* ```binarystring
* 01111111111111111111111111111111
* ```
*
* @constant
* @type {integer32}
* @default 2147483647
*/
var INT32_MAX = 2147483647|0; // asm type annotation
// EXPORTS //
module.exports = INT32_MAX;
},{}],248:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Minimum signed 32-bit integer.
*
* @module @stdlib/constants/int32/min
* @type {integer32}
*
* @example
* var INT32_MIN = require( '@stdlib/constants/int32/min' );
* // returns -2147483648
*/
// MAIN //
/**
* Minimum signed 32-bit integer.
*
* ## Notes
*
* The number has the value
*
* ```tex
* -(2^{31})
* ```
*
* which corresponds to the two's complement bit sequence
*
* ```binarystring
* 10000000000000000000000000000000
* ```
*
* @constant
* @type {integer32}
* @default -2147483648
*/
var INT32_MIN = -2147483648|0; // asm type annotation
// EXPORTS //
module.exports = INT32_MIN;
},{}],249:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Maximum signed 8-bit integer.
*
* @module @stdlib/constants/int8/max
* @type {integer32}
*
* @example
* var INT8_MAX = require( '@stdlib/constants/int8/max' );
* // returns 127
*/
// MAIN //
/**
* Maximum signed 8-bit integer.
*
* ## Notes
*
* The number is given by
*
* ```tex
* 2^{7} - 1
* ```
*
* which corresponds to the bit sequence
*
* ```binarystring
* 01111111
* ```
*
* @constant
* @type {integer32}
* @default 127
*/
var INT8_MAX = 127|0; // asm type annotation
// EXPORTS //
module.exports = INT8_MAX;
},{}],250:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Minimum signed 8-bit integer.
*
* @module @stdlib/constants/int8/min
* @type {integer32}
*
* @example
* var INT8_MIN = require( '@stdlib/constants/int8/min' );
* // returns -128
*/
// MAIN //
/**
* Minimum signed 8-bit integer.
*
* ## Notes
*
* The number is given by
*
* ```tex
* -(2^{7})
* ```
*
* which corresponds to the two's complement bit sequence
*
* ```binarystring
* 10000000
* ```
*
* @constant
* @type {integer32}
* @default -128
*/
var INT8_MIN = -128|0; // asm type annotation
// EXPORTS //
module.exports = INT8_MIN;
},{}],251:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Maximum unsigned 16-bit integer.
*
* @module @stdlib/constants/uint16/max
* @type {integer32}
*
* @example
* var UINT16_MAX = require( '@stdlib/constants/uint16/max' );
* // returns 65535
*/
// MAIN //
/**
* Maximum unsigned 16-bit integer.
*
* ## Notes
*
* The number has the value
*
* ```tex
* 2^{16} - 1
* ```
*
* which corresponds to the bit sequence
*
* ```binarystring
* 1111111111111111
* ```
*
* @constant
* @type {integer32}
* @default 65535
*/
var UINT16_MAX = 65535|0; // asm type annotation
// EXPORTS //
module.exports = UINT16_MAX;
},{}],252:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Maximum unsigned 32-bit integer.
*
* @module @stdlib/constants/uint32/max
* @type {uinteger32}
*
* @example
* var UINT32_MAX = require( '@stdlib/constants/uint32/max' );
* // returns 4294967295
*/
// MAIN //
/**
* Maximum unsigned 32-bit integer.
*
* ## Notes
*
* The number has the value
*
* ```tex
* 2^{32} - 1
* ```
*
* which corresponds to the bit sequence
*
* ```binarystring
* 11111111111111111111111111111111
* ```
*
* @constant
* @type {uinteger32}
* @default 4294967295
*/
var UINT32_MAX = 4294967295;
// EXPORTS //
module.exports = UINT32_MAX;
},{}],253:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Maximum unsigned 8-bit integer.
*
* @module @stdlib/constants/uint8/max
* @type {integer32}
*
* @example
* var UINT8_MAX = require( '@stdlib/constants/uint8/max' );
* // returns 255
*/
// MAIN //
/**
* Maximum unsigned 8-bit integer.
*
* ## Notes
*
* The number has the value
*
* ```tex
* 2^{8} - 1
* ```
*
* which corresponds to the bit sequence
*
* ```binarystring
* 11111111
* ```
*
* @constant
* @type {integer32}
* @default 255
*/
var UINT8_MAX = 255|0; // asm type annotation
// EXPORTS //
module.exports = UINT8_MAX;
},{}],254:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Maximum Unicode code point in the Basic Multilingual Plane (BMP).
*
* @module @stdlib/constants/unicode/max-bmp
* @type {integer32}
*
* @example
* var UNICODE_MAX_BMP = require( '@stdlib/constants/unicode/max-bmp' );
* // returns 65535
*/
// MAIN //
/**
* Maximum Unicode code point in the Basic Multilingual Plane (BMP).
*
* @constant
* @type {integer32}
* @default 65535
* @see [Unicode]{@link https://en.wikipedia.org/wiki/Unicode}
*/
var UNICODE_MAX_BMP = 0xFFFF|0; // asm type annotation
// EXPORTS //
module.exports = UNICODE_MAX_BMP;
},{}],255:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Maximum Unicode code point.
*
* @module @stdlib/constants/unicode/max
* @type {integer32}
*
* @example
* var UNICODE_MAX = require( '@stdlib/constants/unicode/max' );
* // returns 1114111
*/
// MAIN //
/**
* Maximum Unicode code point.
*
* @constant
* @type {integer32}
* @default 1114111
* @see [Unicode]{@link https://en.wikipedia.org/wiki/Unicode}
*/
var UNICODE_MAX = 0x10FFFF|0; // asm type annotation
// EXPORTS //
module.exports = UNICODE_MAX;
},{}],256:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a finite double-precision floating-point number is an integer.
*
* @module @stdlib/math/base/assert/is-integer
*
* @example
* var isInteger = require( '@stdlib/math/base/assert/is-integer' );
*
* var bool = isInteger( 1.0 );
* // returns true
*
* bool = isInteger( 3.14 );
* // returns false
*/
// MODULES //
var isInteger = require( './is_integer.js' );
// EXPORTS //
module.exports = isInteger;
},{"./is_integer.js":257}],257:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var floor = require( '@stdlib/math/base/special/floor' );
// MAIN //
/**
* Tests if a finite double-precision floating-point number is an integer.
*
* @param {number} x - value to test
* @returns {boolean} boolean indicating whether the value is an integer
*
* @example
* var bool = isInteger( 1.0 );
* // returns true
*
* @example
* var bool = isInteger( 3.14 );
* // returns false
*/
function isInteger( x ) {
return (floor(x) === x);
}
// EXPORTS //
module.exports = isInteger;
},{"@stdlib/math/base/special/floor":262}],258:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a double-precision floating-point numeric value is `NaN`.
*
* @module @stdlib/math/base/assert/is-nan
*
* @example
* var isnan = require( '@stdlib/math/base/assert/is-nan' );
*
* var bool = isnan( NaN );
* // returns true
*
* bool = isnan( 7.0 );
* // returns false
*/
// MODULES //
var isnan = require( './main.js' );
// EXPORTS //
module.exports = isnan;
},{"./main.js":259}],259:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Tests if a double-precision floating-point numeric value is `NaN`.
*
* @param {number} x - value to test
* @returns {boolean} boolean indicating whether the value is `NaN`
*
* @example
* var bool = isnan( NaN );
* // returns true
*
* @example
* var bool = isnan( 7.0 );
* // returns false
*/
function isnan( x ) {
return ( x !== x );
}
// EXPORTS //
module.exports = isnan;
},{}],260:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a double-precision floating-point numeric value is positive zero.
*
* @module @stdlib/math/base/assert/is-positive-zero
*
* @example
* var isPositiveZero = require( '@stdlib/math/base/assert/is-positive-zero' );
*
* var bool = isPositiveZero( 0.0 );
* // returns true
*
* bool = isPositiveZero( -0.0 );
* // returns false
*/
// MODULES //
var isPositiveZero = require( './main.js' );
// EXPORTS //
module.exports = isPositiveZero;
},{"./main.js":261}],261:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var PINF = require( '@stdlib/constants/float64/pinf' );
// MAIN //
/**
* Tests if a double-precision floating-point numeric value is positive zero.
*
* @param {number} x - value to test
* @returns {boolean} boolean indicating whether the value is positive zero
*
* @example
* var bool = isPositiveZero( 0.0 );
* // returns true
*
* @example
* var bool = isPositiveZero( -0.0 );
* // returns false
*/
function isPositiveZero( x ) {
return (x === 0.0 && 1.0/x === PINF);
}
// EXPORTS //
module.exports = isPositiveZero;
},{"@stdlib/constants/float64/pinf":244}],262:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Round a double-precision floating-point number toward negative infinity.
*
* @module @stdlib/math/base/special/floor
*
* @example
* var floor = require( '@stdlib/math/base/special/floor' );
*
* var v = floor( -4.2 );
* // returns -5.0
*
* v = floor( 9.99999 );
* // returns 9.0
*
* v = floor( 0.0 );
* // returns 0.0
*
* v = floor( NaN );
* // returns NaN
*/
// MODULES //
var floor = require( './main.js' );
// EXPORTS //
module.exports = floor;
},{"./main.js":263}],263:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// TODO: implementation (?)
/**
* Rounds a double-precision floating-point number toward negative infinity.
*
* @param {number} x - input value
* @returns {number} rounded value
*
* @example
* var v = floor( -4.2 );
* // returns -5.0
*
* @example
* var v = floor( 9.99999 );
* // returns 9.0
*
* @example
* var v = floor( 0.0 );
* // returns 0.0
*
* @example
* var v = floor( NaN );
* // returns NaN
*/
var floor = Math.floor; // eslint-disable-line stdlib/no-builtin-math
// EXPORTS //
module.exports = floor;
},{}],264:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Return the maximum value.
*
* @module @stdlib/math/base/special/max
*
* @example
* var max = require( '@stdlib/math/base/special/max' );
*
* var v = max( 3.14, 4.2 );
* // returns 4.2
*
* v = max( 5.9, 3.14, 4.2 );
* // returns 5.9
*
* v = max( 3.14, NaN );
* // returns NaN
*
* v = max( +0.0, -0.0 );
* // returns +0.0
*/
// MODULES //
var max = require( './max.js' );
// EXPORTS //
module.exports = max;
},{"./max.js":265}],265:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isPositiveZero = require( '@stdlib/math/base/assert/is-positive-zero' );
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var NINF = require( '@stdlib/constants/float64/ninf' );
var PINF = require( '@stdlib/constants/float64/pinf' );
// MAIN //
/**
* Returns the maximum value.
*
* @param {number} [x] - first number
* @param {number} [y] - second number
* @param {...number} [args] - numbers
* @returns {number} maximum value
*
* @example
* var v = max( 3.14, 4.2 );
* // returns 4.2
*
* @example
* var v = max( 5.9, 3.14, 4.2 );
* // returns 5.9
*
* @example
* var v = max( 3.14, NaN );
* // returns NaN
*
* @example
* var v = max( +0.0, -0.0 );
* // returns +0.0
*/
function max( x, y ) {
var len;
var m;
var v;
var i;
len = arguments.length;
if ( len === 2 ) {
if ( isnan( x ) || isnan( y ) ) {
return NaN;
}
if ( x === PINF || y === PINF ) {
return PINF;
}
if ( x === y && x === 0.0 ) {
if ( isPositiveZero( x ) ) {
return x;
}
return y;
}
if ( x > y ) {
return x;
}
return y;
}
m = NINF;
for ( i = 0; i < len; i++ ) {
v = arguments[ i ];
if ( isnan( v ) || v === PINF ) {
return v;
}
if ( v > m ) {
m = v;
} else if (
v === m &&
v === 0.0 &&
isPositiveZero( v )
) {
m = v;
}
}
return m;
}
// EXPORTS //
module.exports = max;
},{"@stdlib/constants/float64/ninf":243,"@stdlib/constants/float64/pinf":244,"@stdlib/math/base/assert/is-nan":258,"@stdlib/math/base/assert/is-positive-zero":260}],266:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Decompose a double-precision floating-point number into integral and fractional parts.
*
* @module @stdlib/math/base/special/modf
*
* @example
* var modf = require( '@stdlib/math/base/special/modf' );
*
* var parts = modf( 3.14 );
* // returns [ 3.0, 0.14000000000000012 ]
*
* @example
* var Float64Array = require( '@stdlib/array/float64' );
* var modf = require( '@stdlib/math/base/special/modf' );
*
* var out = new Float64Array( 2 );
*
* var parts = modf( out, 3.14 );
* // returns [ 3.0, 0.14000000000000012 ]
*
* var bool = ( parts === out );
* // returns true
*/
// MODULES //
var modf = require( './main.js' );
// EXPORTS //
module.exports = modf;
},{"./main.js":267}],267:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var fcn = require( './modf.js' );
// MAIN //
/**
* Decomposes a double-precision floating-point number into integral and fractional parts, each having the same type and sign as the input value.
*
* @param {(Array|TypedArray|Object)} [out] - output array
* @param {number} x - input value
* @returns {(Array|TypedArray|Object)} output array
*
* @example
* var parts = modf( 3.14 );
* // returns [ 3.0, 0.14000000000000012 ]
*
* @example
* var Float64Array = require( '@stdlib/array/float64' );
*
* var out = new Float64Array( 2 );
*
* var parts = modf( out, 3.14 );
* // returns <Float64Array>[ 3.0, 0.14000000000000012 ]
*
* var bool = ( parts === out );
* // returns true
*/
function modf( out, x ) {
if ( arguments.length === 1 ) {
return fcn( [ 0.0, 0.0 ], out );
}
return fcn( out, x );
}
// EXPORTS //
module.exports = modf;
},{"./modf.js":268}],268:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var toWords = require( '@stdlib/number/float64/base/to-words' );
var fromWords = require( '@stdlib/number/float64/base/from-words' );
var PINF = require( '@stdlib/constants/float64/pinf' );
var FLOAT64_EXPONENT_BIAS = require( '@stdlib/constants/float64/exponent-bias' );
var FLOAT64_HIGH_WORD_EXPONENT_MASK = require( '@stdlib/constants/float64/high-word-exponent-mask' ); // eslint-disable-line id-length
var FLOAT64_HIGH_WORD_SIGNIFICAND_MASK = require( '@stdlib/constants/float64/high-word-significand-mask' ); // eslint-disable-line id-length
// VARIABLES //
// 4294967295 => 0xffffffff => 11111111111111111111111111111111
var ALL_ONES = 4294967295>>>0; // asm type annotation
// High/low words workspace:
var WORDS = [ 0|0, 0|0 ]; // WARNING: not thread safe
// MAIN //
/**
* Decomposes a double-precision floating-point number into integral and fractional parts, each having the same type and sign as the input value.
*
* @private
* @param {(Array|TypedArray|Object)} out - output array
* @param {number} x - input value
* @returns {(Array|TypedArray|Object)} output array
*
* @example
* var parts = modf( [ 0.0, 0.0 ], 3.14 );
* // returns [ 3.0, 0.14000000000000012 ]
*/
function modf( out, x ) {
var high;
var low;
var exp;
var i;
// Special cases...
if ( x < 1.0 ) {
if ( x < 0.0 ) {
modf( out, -x );
out[ 0 ] *= -1.0;
out[ 1 ] *= -1.0;
return out;
}
if ( x === 0.0 ) { // [ +-0, +-0 ]
out[ 0 ] = x;
out[ 1 ] = x;
return out;
}
out[ 0 ] = 0.0;
out[ 1 ] = x;
return out;
}
if ( isnan( x ) ) {
out[ 0 ] = NaN;
out[ 1 ] = NaN;
return out;
}
if ( x === PINF ) {
out[ 0 ] = PINF;
out[ 1 ] = 0.0;
return out;
}
// Decompose |x|...
// Extract the high and low words:
toWords( WORDS, x );
high = WORDS[ 0 ];
low = WORDS[ 1 ];
// Extract the unbiased exponent from the high word:
exp = ((high & FLOAT64_HIGH_WORD_EXPONENT_MASK) >> 20)|0; // asm type annotation
exp -= FLOAT64_EXPONENT_BIAS|0; // asm type annotation
// Handle smaller values (x < 2**20 = 1048576)...
if ( exp < 20 ) {
i = (FLOAT64_HIGH_WORD_SIGNIFICAND_MASK >> exp)|0; // asm type annotation
// Determine if `x` is integral by checking for significand bits which cannot be exponentiated away...
if ( ((high&i)|low) === 0 ) {
out[ 0 ] = x;
out[ 1 ] = 0.0;
return out;
}
// Turn off all the bits which cannot be exponentiated away:
high &= (~i);
// Generate the integral part:
i = fromWords( high, 0 );
// The fractional part is whatever is leftover:
out[ 0 ] = i;
out[ 1 ] = x - i;
return out;
}
// Check if `x` can even have a fractional part...
if ( exp > 51 ) {
// `x` is integral:
out[ 0 ] = x;
out[ 1 ] = 0.0;
return out;
}
i = ALL_ONES >>> (exp-20);
// Determine if `x` is integral by checking for less significant significand bits which cannot be exponentiated away...
if ( (low&i) === 0 ) {
out[ 0 ] = x;
out[ 1 ] = 0.0;
return out;
}
// Turn off all the bits which cannot be exponentiated away:
low &= (~i);
// Generate the integral part:
i = fromWords( high, low );
// The fractional part is whatever is leftover:
out[ 0 ] = i;
out[ 1 ] = x - i;
return out;
}
// EXPORTS //
module.exports = modf;
},{"@stdlib/constants/float64/exponent-bias":238,"@stdlib/constants/float64/high-word-exponent-mask":239,"@stdlib/constants/float64/high-word-significand-mask":240,"@stdlib/constants/float64/pinf":244,"@stdlib/math/base/assert/is-nan":258,"@stdlib/number/float64/base/from-words":275,"@stdlib/number/float64/base/to-words":278}],269:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// TODO: implementation
/**
* Round a numeric value to the nearest integer.
*
* @module @stdlib/math/base/special/round
*
* @example
* var round = require( '@stdlib/math/base/special/round' );
*
* var v = round( -4.2 );
* // returns -4.0
*
* v = round( -4.5 );
* // returns -4.0
*
* v = round( -4.6 );
* // returns -5.0
*
* v = round( 9.99999 );
* // returns 10.0
*
* v = round( 9.5 );
* // returns 10.0
*
* v = round( 9.2 );
* // returns 9.0
*
* v = round( 0.0 );
* // returns 0.0
*
* v = round( -0.0 );
* // returns -0.0
*
* v = round( Infinity );
* // returns Infinity
*
* v = round( -Infinity );
* // returns -Infinity
*
* v = round( NaN );
* // returns NaN
*/
// MODULES //
var round = require( './round.js' );
// EXPORTS //
module.exports = round;
},{"./round.js":270}],270:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// TODO: implementation
/**
* Rounds a numeric value to the nearest integer.
*
* @param {number} x - input value
* @returns {number} function value
*
* @example
* var v = round( -4.2 );
* // returns -4.0
*
* @example
* var v = round( -4.5 );
* // returns -4.0
*
* @example
* var v = round( -4.6 );
* // returns -5.0
*
* @example
* var v = round( 9.99999 );
* // returns 10.0
*
* @example
* var v = round( 9.5 );
* // returns 10.0
*
* @example
* var v = round( 9.2 );
* // returns 9.0
*
* @example
* var v = round( 0.0 );
* // returns 0.0
*
* @example
* var v = round( -0.0 );
* // returns -0.0
*
* @example
* var v = round( Infinity );
* // returns Infinity
*
* @example
* var v = round( -Infinity );
* // returns -Infinity
*
* @example
* var v = round( NaN );
* // returns NaN
*/
var round = Math.round; // eslint-disable-line stdlib/no-builtin-math
// EXPORTS //
module.exports = round;
},{}],271:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Perform C-like multiplication of two unsigned 32-bit integers.
*
* @module @stdlib/math/base/special/uimul
*
* @example
* var uimul = require( '@stdlib/math/base/special/uimul' );
*
* var v = uimul( 10>>>0, 4>>>0 );
* // returns 40
*/
// MODULES //
var uimul = require( './main.js' );
// EXPORTS //
module.exports = uimul;
},{"./main.js":272}],272:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// VARIABLES //
// Define a mask for the least significant 16 bits (low word): 65535 => 0x0000ffff => 00000000000000001111111111111111
var LOW_WORD_MASK = 0x0000ffff>>>0; // asm type annotation
// MAIN //
/**
* Performs C-like multiplication of two unsigned 32-bit integers.
*
* ## Method
*
* - To emulate C-like multiplication without the aid of 64-bit integers, we recognize that a 32-bit integer can be split into two 16-bit words
*
* ```tex
* a = w_h*2^{16} + w_l
* ```
*
* where \\( w_h \\) is the most significant 16 bits and \\( w_l \\) is the least significant 16 bits. For example, consider the maximum unsigned 32-bit integer \\( 2^{32}-1 \\)
*
* ```binarystring
* 11111111111111111111111111111111
* ```
*
* The 16-bit high word is then
*
* ```binarystring
* 1111111111111111
* ```
*
* and the 16-bit low word
*
* ```binarystring
* 1111111111111111
* ```
*
* If we cast the high word to 32-bit precision and multiply by \\( 2^{16} \\) (equivalent to a 16-bit left shift), then the bit sequence is
*
* ```binarystring
* 11111111111111110000000000000000
* ```
*
* Similarly, upon casting the low word to 32-bit precision, the bit sequence is
*
* ```binarystring
* 00000000000000001111111111111111
* ```
*
* From the rules of binary addition, we recognize that adding the two 32-bit values for the high and low words will return our original value \\( 2^{32}-1 \\).
*
* - Accordingly, the multiplication of two 32-bit integers can be expressed
*
* ```tex
* \begin{align*}
* a \cdot b &= ( a_h \cdot 2^{16} + a_l) \cdot ( b_h \cdot 2^{16} + b_l) \\
* &= a_l \cdot b_l + a_h \cdot b_l \cdot 2^{16} + a_l \cdot b_h \cdot 2^{16} + (a_h \cdot b_h) \cdot 2^{32} \\
* &= a_l \cdot b_l + (a_h \cdot b_l + a_l \cdot b_h) \cdot 2^{16} + (a_h \cdot b_h) \cdot 2^{32}
* \end{align*}
* ```
*
* - We note that multiplying (dividing) an integer by \\( 2^n \\) is equivalent to performing a left (right) shift of \\( n \\) bits.
*
* - Further, as we want to return an integer of the same precision, for a 32-bit integer, the return value will be modulo \\( 2^{32} \\). Stated another way, we only care about the low word of a 64-bit result.
*
* - Accordingly, the last term, being evenly divisible by \\( 2^{32} \\), drops from the equation leaving the remaining two terms as the remainder.
*
* ```tex
* a \cdot b = a_l \cdot b_l + (a_h \cdot b_l + a_l \cdot b_h) << 16
* ```
*
* - Lastly, the second term in the above equation contributes to the middle bits and may cause the product to "overflow". However, we can disregard (`>>>0`) overflow bits due modulo arithmetic, as discussed earlier with regard to the term involving the partial product of high words.
*
*
* @param {uinteger32} a - integer
* @param {uinteger32} b - integer
* @returns {uinteger32} product
*
* @example
* var v = uimul( 10>>>0, 4>>>0 );
* // returns 40
*/
function uimul( a, b ) {
var lbits;
var mbits;
var ha;
var hb;
var la;
var lb;
a >>>= 0; // asm type annotation
b >>>= 0; // asm type annotation
// Isolate the most significant 16-bits:
ha = ( a>>>16 )>>>0; // asm type annotation
hb = ( b>>>16 )>>>0; // asm type annotation
// Isolate the least significant 16-bits:
la = ( a&LOW_WORD_MASK )>>>0; // asm type annotation
lb = ( b&LOW_WORD_MASK )>>>0; // asm type annotation
// Compute partial sums:
lbits = ( la*lb )>>>0; // asm type annotation; no integer overflow possible
mbits = ( ((ha*lb) + (la*hb))<<16 )>>>0; // asm type annotation; possible integer overflow
// The final `>>>0` converts the intermediate sum to an unsigned integer (possible integer overflow during sum):
return ( lbits + mbits )>>>0; // asm type annotation
}
// EXPORTS //
module.exports = uimul;
},{}],273:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Constructor which returns a `Number` object.
*
* @module @stdlib/number/ctor
*
* @example
* var Number = require( '@stdlib/number/ctor' );
*
* var v = new Number( 10.0 );
* // returns <Number>
*/
// MODULES //
var Number = require( './number.js' );
// EXPORTS //
module.exports = Number;
},{"./number.js":274}],274:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// EXPORTS //
module.exports = Number; // eslint-disable-line stdlib/require-globals
},{}],275:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Create a double-precision floating-point number from a higher order word (unsigned 32-bit integer) and a lower order word (unsigned 32-bit integer).
*
* @module @stdlib/number/float64/base/from-words
*
* @example
* var fromWords = require( '@stdlib/number/float64/base/from-words' );
*
* var v = fromWords( 1774486211, 2479577218 );
* // returns 3.14e201
*
* v = fromWords( 3221823995, 1413754136 );
* // returns -3.141592653589793
*
* v = fromWords( 0, 0 );
* // returns 0.0
*
* v = fromWords( 2147483648, 0 );
* // returns -0.0
*
* v = fromWords( 2146959360, 0 );
* // returns NaN
*
* v = fromWords( 2146435072, 0 );
* // returns Infinity
*
* v = fromWords( 4293918720, 0 );
* // returns -Infinity
*/
// MODULES //
var fromWords = require( './main.js' );
// EXPORTS //
module.exports = fromWords;
},{"./main.js":277}],276:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isLittleEndian = require( '@stdlib/assert/is-little-endian' );
// MAIN //
var indices;
var HIGH;
var LOW;
if ( isLittleEndian === true ) {
HIGH = 1; // second index
LOW = 0; // first index
} else {
HIGH = 0; // first index
LOW = 1; // second index
}
indices = {
'HIGH': HIGH,
'LOW': LOW
};
// EXPORTS //
module.exports = indices;
},{"@stdlib/assert/is-little-endian":116}],277:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var Uint32Array = require( '@stdlib/array/uint32' );
var Float64Array = require( '@stdlib/array/float64' );
var indices = require( './indices.js' );
// VARIABLES //
var FLOAT64_VIEW = new Float64Array( 1 );
var UINT32_VIEW = new Uint32Array( FLOAT64_VIEW.buffer );
var HIGH = indices.HIGH;
var LOW = indices.LOW;
// MAIN //
/**
* Creates a double-precision floating-point number from a higher order word (unsigned 32-bit integer) and a lower order word (unsigned 32-bit integer).
*
* ## Notes
*
* ```text
* float64 (64 bits)
* f := fraction (significand/mantissa) (52 bits)
* e := exponent (11 bits)
* s := sign bit (1 bit)
*
* |-------- -------- -------- -------- -------- -------- -------- --------|
* | Float64 |
* |-------- -------- -------- -------- -------- -------- -------- --------|
* | Uint32 | Uint32 |
* |-------- -------- -------- -------- -------- -------- -------- --------|
* ```
*
* If little endian (more significant bits last):
*
* ```text
* <-- lower higher -->
* | f7 f6 f5 f4 f3 f2 e2 | f1 |s| e1 |
* ```
*
* If big endian (more significant bits first):
*
* ```text
* <-- higher lower -->
* |s| e1 e2 | f1 f2 f3 f4 f5 f6 f7 |
* ```
*
*
* In which Uint32 should we place the higher order bits? If little endian, the second; if big endian, the first.
*
*
* ## References
*
* - [Open Group][1]
*
* [1]: http://pubs.opengroup.org/onlinepubs/9629399/chap14.htm
*
* @param {uinteger32} high - higher order word (unsigned 32-bit integer)
* @param {uinteger32} low - lower order word (unsigned 32-bit integer)
* @returns {number} floating-point number
*
* @example
* var v = fromWords( 1774486211, 2479577218 );
* // returns 3.14e201
*
* @example
* var v = fromWords( 3221823995, 1413754136 );
* // returns -3.141592653589793
*
* @example
* var v = fromWords( 0, 0 );
* // returns 0.0
*
* @example
* var v = fromWords( 2147483648, 0 );
* // returns -0.0
*
* @example
* var v = fromWords( 2146959360, 0 );
* // returns NaN
*
* @example
* var v = fromWords( 2146435072, 0 );
* // returns Infinity
*
* @example
* var v = fromWords( 4293918720, 0 );
* // returns -Infinity
*/
function fromWords( high, low ) {
UINT32_VIEW[ HIGH ] = high;
UINT32_VIEW[ LOW ] = low;
return FLOAT64_VIEW[ 0 ];
}
// EXPORTS //
module.exports = fromWords;
},{"./indices.js":276,"@stdlib/array/float64":5,"@stdlib/array/uint32":23}],278:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Split a double-precision floating-point number into a higher order word (unsigned 32-bit integer) and a lower order word (unsigned 32-bit integer).
*
* @module @stdlib/number/float64/base/to-words
*
* @example
* var toWords = require( '@stdlib/number/float64/base/to-words' );
*
* var w = toWords( 3.14e201 );
* // returns [ 1774486211, 2479577218 ]
*
* @example
* var Uint32Array = require( '@stdlib/array/uint32' );
* var toWords = require( '@stdlib/number/float64/base/to-words' );
*
* var out = new Uint32Array( 2 );
*
* var w = toWords( out, 3.14e201 );
* // returns <Uint32Array>[ 1774486211, 2479577218 ]
*
* var bool = ( w === out );
* // returns true
*/
// MODULES //
var toWords = require( './main.js' );
// EXPORTS //
module.exports = toWords;
},{"./main.js":280}],279:[function(require,module,exports){
arguments[4][276][0].apply(exports,arguments)
},{"@stdlib/assert/is-little-endian":116,"dup":276}],280:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var fcn = require( './to_words.js' );
// MAIN //
/**
* Splits a double-precision floating-point number into a higher order word (unsigned 32-bit integer) and a lower order word (unsigned 32-bit integer).
*
* @param {(Array|TypedArray|Object)} [out] - output array
* @param {number} x - input value
* @returns {(Array|TypedArray|Object)} output array
*
* @example
* var w = toWords( 3.14e201 );
* // returns [ 1774486211, 2479577218 ]
*
* @example
* var Uint32Array = require( '@stdlib/array/uint32' );
*
* var out = new Uint32Array( 2 );
*
* var w = toWords( out, 3.14e201 );
* // returns <Uint32Array>[ 1774486211, 2479577218 ]
*
* var bool = ( w === out );
* // returns true
*/
function toWords( out, x ) {
if ( arguments.length === 1 ) {
return fcn( [ 0, 0 ], out );
}
return fcn( out, x );
}
// EXPORTS //
module.exports = toWords;
},{"./to_words.js":281}],281:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var Uint32Array = require( '@stdlib/array/uint32' );
var Float64Array = require( '@stdlib/array/float64' );
var indices = require( './indices.js' );
// VARIABLES //
var FLOAT64_VIEW = new Float64Array( 1 );
var UINT32_VIEW = new Uint32Array( FLOAT64_VIEW.buffer );
var HIGH = indices.HIGH;
var LOW = indices.LOW;
// MAIN //
/**
* Splits a double-precision floating-point number into a higher order word (unsigned 32-bit integer) and a lower order word (unsigned 32-bit integer).
*
* ## Notes
*
* ```text
* float64 (64 bits)
* f := fraction (significand/mantissa) (52 bits)
* e := exponent (11 bits)
* s := sign bit (1 bit)
*
* |-------- -------- -------- -------- -------- -------- -------- --------|
* | Float64 |
* |-------- -------- -------- -------- -------- -------- -------- --------|
* | Uint32 | Uint32 |
* |-------- -------- -------- -------- -------- -------- -------- --------|
* ```
*
* If little endian (more significant bits last):
*
* ```text
* <-- lower higher -->
* | f7 f6 f5 f4 f3 f2 e2 | f1 |s| e1 |
* ```
*
* If big endian (more significant bits first):
*
* ```text
* <-- higher lower -->
* |s| e1 e2 | f1 f2 f3 f4 f5 f6 f7 |
* ```
*
* In which Uint32 can we find the higher order bits? If little endian, the second; if big endian, the first.
*
*
* ## References
*
* - [Open Group][1]
*
* [1]: http://pubs.opengroup.org/onlinepubs/9629399/chap14.htm
*
*
* @private
* @param {(Array|TypedArray|Object)} out - output array
* @param {number} x - input value
* @returns {(Array|TypedArray|Object)} output array
*
* @example
* var Uint32Array = require( '@stdlib/array/uint32' );
*
* var out = new Uint32Array( 2 );
*
* var w = toWords( out, 3.14e201 );
* // returns <Uint32Array>[ 1774486211, 2479577218 ]
*
* var bool = ( w === out );
* // returns true
*/
function toWords( out, x ) {
FLOAT64_VIEW[ 0 ] = x;
out[ 0 ] = UINT32_VIEW[ HIGH ];
out[ 1 ] = UINT32_VIEW[ LOW ];
return out;
}
// EXPORTS //
module.exports = toWords;
},{"./indices.js":279,"@stdlib/array/float64":5,"@stdlib/array/uint32":23}],282:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isnan = require( '@stdlib/math/base/assert/is-nan' );
// VARIABLES //
var NUM_WARMUPS = 8;
// MAIN //
/**
* Initializes a shuffle table.
*
* @private
* @param {PRNG} rand - pseudorandom number generator
* @param {Int32Array} table - table
* @param {PositiveInteger} N - table size
* @throws {Error} PRNG returned `NaN`
* @returns {NumberArray} shuffle table
*/
function createTable( rand, table, N ) {
var v;
var i;
// "warm-up" the PRNG...
for ( i = 0; i < NUM_WARMUPS; i++ ) {
v = rand();
// Prevent the above loop from being discarded by the compiler...
if ( isnan( v ) ) {
throw new Error( 'unexpected error. PRNG returned `NaN`.' );
}
}
// Initialize the shuffle table...
for ( i = N-1; i >= 0; i-- ) {
table[ i ] = rand();
}
return table;
}
// EXPORTS //
module.exports = createTable;
},{"@stdlib/math/base/assert/is-nan":258}],283:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
/* eslint-disable max-len */
'use strict';
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var setReadOnlyAccessor = require( '@stdlib/utils/define-nonenumerable-read-only-accessor' );
var setReadWriteAccessor = require( '@stdlib/utils/define-nonenumerable-read-write-accessor' );
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var isObject = require( '@stdlib/assert/is-plain-object' );
var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive;
var isCollection = require( '@stdlib/assert/is-collection' );
var isPositiveInteger = require( '@stdlib/assert/is-positive-integer' ).isPrimitive;
var isInt32Array = require( '@stdlib/assert/is-int32array' );
var gcopy = require( '@stdlib/blas/base/gcopy' );
var floor = require( '@stdlib/math/base/special/floor' );
var Int32Array = require( '@stdlib/array/int32' );
var INT32_MAX = require( '@stdlib/constants/int32/max' );
var typedarray2json = require( '@stdlib/array/to-json' );
var createTable = require( './create_table.js' );
var randint32 = require( './rand_int32.js' );
// VARIABLES //
var NORMALIZATION_CONSTANT = (INT32_MAX - 1)|0; // asm type annotation
var MAX_SEED = (INT32_MAX - 1)|0; // asm type annotation
var A = 16807|0; // asm type annotation
// Define the number of elements in the shuffle table:
var TABLE_LENGTH = 32;
// Define the state array schema version:
var STATE_ARRAY_VERSION = 1; // NOTE: anytime the state array schema changes, this value should be incremented!!!
// Define the number of sections in the state array:
var NUM_STATE_SECTIONS = 3; // table, other, seed
// Define the index offset of the "table" section in the state array:
var TABLE_SECTION_OFFSET = 2; // | version | num_sections | table_length | ...table | other_length | shuffle_state | prng_state | seed_length | ...seed |
// Define the index offset of the "state" section in the state array:
var STATE_SECTION_OFFSET = TABLE_LENGTH + 3; // | version | num_sections | table_length | ...table | state_length | shuffle_state | prng_state | seed_length | ...seed |
// Define the index offset of the seed section in the state array:
var SEED_SECTION_OFFSET = TABLE_LENGTH + 6; // | version | num_sections | table_length | ...table | state_length | shuffle_state | prng_state | seed_length | ...seed |
// Define the length of the "fixed" length portion of the state array:
var STATE_FIXED_LENGTH = TABLE_LENGTH + 7; // 1 (version) + 1 (num_sections) + 1 (table_length) + TABLE_LENGTH (table) + 1 (state_length) + 1 (shuffle_state) + 1 (prng_state) + 1 (seed_length)
// Define the indices for the shuffle table and PRNG states:
var SHUFFLE_STATE = STATE_SECTION_OFFSET + 1;
var PRNG_STATE = STATE_SECTION_OFFSET + 2;
// FUNCTIONS //
/**
* Verifies state array integrity.
*
* @private
* @param {Int32Array} state - state array
* @param {boolean} FLG - flag indicating whether the state array was provided as an option (true) or an argument (false)
* @returns {(Error|null)} an error or `null`
*/
function verifyState( state, FLG ) {
var s1;
if ( FLG ) {
s1 = 'option';
} else {
s1 = 'argument';
}
// The state array must have a minimum length...
if ( state.length < STATE_FIXED_LENGTH+1 ) {
return new RangeError( 'invalid '+s1+'. `state` array has insufficient length.' );
}
// The first element of the state array must equal the supported state array schema version...
if ( state[ 0 ] !== STATE_ARRAY_VERSION ) {
return new RangeError( 'invalid '+s1+'. `state` array has an incompatible schema version. Expected: '+STATE_ARRAY_VERSION+'. Actual: '+state[ 0 ]+'.' );
}
// The second element of the state array must contain the number of sections...
if ( state[ 1 ] !== NUM_STATE_SECTIONS ) {
return new RangeError( 'invalid '+s1+'. `state` array has an incompatible number of sections. Expected: '+NUM_STATE_SECTIONS+'. Actual: '+state[ 1 ]+'.' );
}
// The length of the "table" section must equal `TABLE_LENGTH`...
if ( state[ TABLE_SECTION_OFFSET ] !== TABLE_LENGTH ) {
return new RangeError( 'invalid '+s1+'. `state` array has an incompatible table length. Expected: '+TABLE_LENGTH+'. Actual: '+state[ TABLE_SECTION_OFFSET ]+'.' );
}
// The length of the "state" section must equal `2`...
if ( state[ STATE_SECTION_OFFSET ] !== 2 ) {
return new RangeError( 'invalid '+s1+'. `state` array has an incompatible state length. Expected: '+(2).toString()+'. Actual: '+state[ STATE_SECTION_OFFSET ]+'.' );
}
// The length of the "seed" section much match the empirical length...
if ( state[ SEED_SECTION_OFFSET ] !== state.length-STATE_FIXED_LENGTH ) {
return new RangeError( 'invalid '+s1+'. `state` array length is incompatible with seed section length. Expected: '+(state.length-STATE_FIXED_LENGTH)+'. Actual: '+state[ SEED_SECTION_OFFSET ]+'.' );
}
return null;
}
// MAIN //
/**
* Returns a linear congruential pseudorandom number generator (LCG) whose output is shuffled.
*
* @param {Options} [options] - options
* @param {PRNGSeedMINSTD} [options.seed] - pseudorandom number generator seed
* @param {PRNGStateMINSTD} [options.state] - pseudorandom number generator state
* @param {boolean} [options.copy=true] - boolean indicating whether to copy a provided pseudorandom number generator state
* @throws {TypeError} options argument must be an object
* @throws {TypeError} a seed must be either a positive integer less than the maximum signed 32-bit integer or an array-like object containing integers less than the maximum signed 32-bit integer
* @throws {RangeError} a numeric seed must be a positive integer less than the maximum signed 32-bit integer
* @throws {TypeError} state must be an `Int32Array`
* @throws {Error} must provide a valid state
* @throws {TypeError} `copy` option must be a boolean
* @returns {PRNG} shuffled LCG PRNG
*
* @example
* var minstd = factory();
*
* var v = minstd();
* // returns <number>
*
* @example
* // Return a seeded LCG:
* var minstd = factory({
* 'seed': 1234
* });
*
* var v = minstd();
* // returns 1421600654
*/
function factory( options ) {
var STATE;
var state;
var opts;
var seed;
var slen;
var err;
opts = {};
if ( arguments.length ) {
if ( !isObject( options ) ) {
throw new TypeError( 'invalid argument. Options argument must be an object. Value: `' + options + '`.' );
}
if ( hasOwnProp( options, 'copy' ) ) {
opts.copy = options.copy;
if ( !isBoolean( options.copy ) ) {
throw new TypeError( 'invalid option. `copy` option must be a boolean. Option: `' + options.copy + '`.' );
}
}
if ( hasOwnProp( options, 'state' ) ) {
state = options.state;
opts.state = true;
if ( !isInt32Array( state ) ) {
throw new TypeError( 'invalid option. `state` option must be an Int32Array. Option: `' + state + '`.' );
}
err = verifyState( state, true );
if ( err ) {
throw err;
}
if ( opts.copy === false ) {
STATE = state;
} else {
STATE = new Int32Array( state.length );
gcopy( state.length, state, 1, STATE, 1 );
}
// Create a state (table) "view":
state = new Int32Array( STATE.buffer, STATE.byteOffset+((TABLE_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), TABLE_LENGTH );
// Create a seed "view":
seed = new Int32Array( STATE.buffer, STATE.byteOffset+((SEED_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), state[ SEED_SECTION_OFFSET ] );
}
// If provided a PRNG state, we ignore the `seed` option...
if ( seed === void 0 ) {
if ( hasOwnProp( options, 'seed' ) ) {
seed = options.seed;
opts.seed = true;
if ( isPositiveInteger( seed ) ) {
if ( seed > MAX_SEED ) {
throw new RangeError( 'invalid option. `seed` option must be a positive integer less than the maximum signed 32-bit integer. Option: `' + seed + '`.' );
}
seed |= 0; // asm type annotation
} else if ( isCollection( seed ) && seed.length > 0 ) {
slen = seed.length;
STATE = new Int32Array( STATE_FIXED_LENGTH+slen );
// Initialize sections:
STATE[ 0 ] = STATE_ARRAY_VERSION;
STATE[ 1 ] = NUM_STATE_SECTIONS;
STATE[ TABLE_SECTION_OFFSET ] = TABLE_LENGTH;
STATE[ STATE_SECTION_OFFSET ] = 2;
STATE[ PRNG_STATE ] = seed[ 0 ];
STATE[ SEED_SECTION_OFFSET ] = slen;
// Copy the provided seed array to prevent external mutation, as mutation would lead to an inability to reproduce PRNG values according to the PRNG's stated seed:
gcopy.ndarray( slen, seed, 1, 0, STATE, 1, SEED_SECTION_OFFSET+1 );
// Create a state (table) "view":
state = new Int32Array( STATE.buffer, STATE.byteOffset+((TABLE_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), TABLE_LENGTH );
// Create a seed "view":
seed = new Int32Array( STATE.buffer, STATE.byteOffset+((SEED_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), slen );
// Initialize the internal PRNG state:
state = createTable( minstd, state, TABLE_LENGTH );
STATE[ SHUFFLE_STATE ] = state[ 0 ];
} else {
throw new TypeError( 'invalid option. `seed` option must be either a positive integer less than the maximum signed 32-bit integer or an array-like object containing integer values less than the maximum signed 32-bit integer. Option: `' + seed + '`.' );
}
} else {
seed = randint32()|0; // asm type annotation
}
}
} else {
seed = randint32()|0; // asm type annotation
}
if ( state === void 0 ) {
STATE = new Int32Array( STATE_FIXED_LENGTH+1 );
// Initialize sections:
STATE[ 0 ] = STATE_ARRAY_VERSION;
STATE[ 1 ] = NUM_STATE_SECTIONS;
STATE[ TABLE_SECTION_OFFSET ] = TABLE_LENGTH;
STATE[ STATE_SECTION_OFFSET ] = 2;
STATE[ PRNG_STATE ] = seed;
STATE[ SEED_SECTION_OFFSET ] = 1;
STATE[ SEED_SECTION_OFFSET+1 ] = seed;
// Create a state (table) "view":
state = new Int32Array( STATE.buffer, STATE.byteOffset+((TABLE_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), TABLE_LENGTH );
// Create a seed "view":
seed = new Int32Array( STATE.buffer, STATE.byteOffset+((SEED_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), 1 );
// Initialize the internal PRNG state:
state = createTable( minstd, state, TABLE_LENGTH );
STATE[ SHUFFLE_STATE ] = state[ 0 ];
}
setReadOnly( minstdShuffle, 'NAME', 'minstd-shuffle' );
setReadOnlyAccessor( minstdShuffle, 'seed', getSeed );
setReadOnlyAccessor( minstdShuffle, 'seedLength', getSeedLength );
setReadWriteAccessor( minstdShuffle, 'state', getState, setState );
setReadOnlyAccessor( minstdShuffle, 'stateLength', getStateLength );
setReadOnlyAccessor( minstdShuffle, 'byteLength', getStateSize );
setReadOnly( minstdShuffle, 'toJSON', toJSON );
setReadOnly( minstdShuffle, 'MIN', 1 );
setReadOnly( minstdShuffle, 'MAX', INT32_MAX-1 );
setReadOnly( minstdShuffle, 'normalized', normalized );
setReadOnly( normalized, 'NAME', minstdShuffle.NAME );
setReadOnlyAccessor( normalized, 'seed', getSeed );
setReadOnlyAccessor( normalized, 'seedLength', getSeedLength );
setReadWriteAccessor( normalized, 'state', getState, setState );
setReadOnlyAccessor( normalized, 'stateLength', getStateLength );
setReadOnlyAccessor( normalized, 'byteLength', getStateSize );
setReadOnly( normalized, 'toJSON', toJSON );
setReadOnly( normalized, 'MIN', (minstdShuffle.MIN-1.0) / NORMALIZATION_CONSTANT );
setReadOnly( normalized, 'MAX', (minstdShuffle.MAX-1.0) / NORMALIZATION_CONSTANT );
return minstdShuffle;
/**
* Returns the PRNG seed.
*
* @private
* @returns {PRNGSeedMINSTD} seed
*/
function getSeed() {
var len = STATE[ SEED_SECTION_OFFSET ];
return gcopy( len, seed, 1, new Int32Array( len ), 1 );
}
/**
* Returns the PRNG seed length.
*
* @private
* @returns {PositiveInteger} seed length
*/
function getSeedLength() {
return STATE[ SEED_SECTION_OFFSET ];
}
/**
* Returns the PRNG state length.
*
* @private
* @returns {PositiveInteger} state length
*/
function getStateLength() {
return STATE.length;
}
/**
* Returns the PRNG state size (in bytes).
*
* @private
* @returns {PositiveInteger} state size (in bytes)
*/
function getStateSize() {
return STATE.byteLength;
}
/**
* Returns the current PRNG state.
*
* ## Notes
*
* - The PRNG state array is comprised of a preamble followed by `3` sections:
*
* 0. preamble (version + number of sections)
* 1. shuffle table
* 2. internal PRNG state
* 3. PRNG seed
*
* - The first element of the PRNG state array preamble is the state array schema version.
*
* - The second element of the PRNG state array preamble is the number of state array sections (i.e., `3`).
*
* - The first element of each section following the preamble specifies the section length. The remaining section elements comprise the section contents.
*
* @private
* @returns {PRNGStateMINSTD} current state
*/
function getState() {
var len = STATE.length;
return gcopy( len, STATE, 1, new Int32Array( len ), 1 );
}
/**
* Sets the PRNG state.
*
* ## Notes
*
* - If PRNG state is "shared" (meaning a state array was provided during PRNG creation and **not** copied) and one sets the generator state to a state array having a different length, the PRNG does **not** update the existing shared state and, instead, points to the newly provided state array. In order to synchronize PRNG output according to the new shared state array, the state array for **each** relevant PRNG must be **explicitly** set.
* - If PRNG state is "shared" and one sets the generator state to a state array of the same length, the PRNG state is updated (along with the state of all other PRNGs sharing the PRNG's state array).
*
* @private
* @param {PRNGStateMINSTD} s - generator state
* @throws {TypeError} must provide an `Int32Array`
* @throws {Error} must provide a valid state
*/
function setState( s ) {
var err;
if ( !isInt32Array( s ) ) {
throw new TypeError( 'invalid argument. Must provide an Int32Array. Value: `' + s + '`.' );
}
err = verifyState( s, false );
if ( err ) {
throw err;
}
if ( opts.copy === false ) {
if ( opts.state && s.length === STATE.length ) {
gcopy( s.length, s, 1, STATE, 1 ); // update current shared state
} else {
STATE = s; // point to new shared state
opts.state = true; // setting this flag allows updating a shared state even if a state array was not provided at PRNG creation
}
} else {
// Check if we can reuse allocated memory...
if ( s.length !== STATE.length ) {
STATE = new Int32Array( s.length ); // reallocate
}
gcopy( s.length, s, 1, STATE, 1 );
}
// Create a new state (table) "view":
state = new Int32Array( STATE.buffer, STATE.byteOffset+((TABLE_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), TABLE_LENGTH );
// Create a new seed "view":
seed = new Int32Array( STATE.buffer, STATE.byteOffset+((SEED_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), STATE[ SEED_SECTION_OFFSET ] );
}
/**
* Serializes the pseudorandom number generator as a JSON object.
*
* ## Notes
*
* - `JSON.stringify()` implicitly calls this method when stringifying a PRNG.
*
* @private
* @returns {Object} JSON representation
*/
function toJSON() {
var out = {};
out.type = 'PRNG';
out.name = minstdShuffle.NAME;
out.state = typedarray2json( STATE );
out.params = [];
return out;
}
/**
* Generates a pseudorandom integer on the interval \\( [1,2^{31}-1) \\).
*
* @private
* @returns {integer32} pseudorandom integer
*/
function minstd() {
var s = STATE[ PRNG_STATE ]|0; // asm type annotation
s = ( (A*s)%INT32_MAX )|0; // asm type annotation
STATE[ PRNG_STATE ] = s;
return s|0; // asm type annotation
}
/**
* Generates a pseudorandom integer on the interval \\( [1,2^{31}-1) \\).
*
* @private
* @returns {integer32} pseudorandom integer
*
* @example
* var v = minstd();
* // returns <number>
*/
function minstdShuffle() {
var s;
var i;
s = STATE[ SHUFFLE_STATE ];
i = floor( TABLE_LENGTH * (s/INT32_MAX) );
// Pull a state from the table:
s = state[ i ];
// Update the PRNG state:
STATE[ SHUFFLE_STATE ] = s;
// Replace the pulled state:
state[ i ] = minstd();
return s;
}
/**
* Generates a pseudorandom number on the interval \\( [0,1) \\).
*
* @private
* @returns {number} pseudorandom number
*
* @example
* var v = normalized();
* // returns <number>
*/
function normalized() {
return (minstdShuffle()-1) / NORMALIZATION_CONSTANT;
}
}
// EXPORTS //
module.exports = factory;
},{"./create_table.js":282,"./rand_int32.js":286,"@stdlib/array/int32":10,"@stdlib/array/to-json":17,"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-boolean":81,"@stdlib/assert/is-collection":90,"@stdlib/assert/is-int32array":106,"@stdlib/assert/is-plain-object":147,"@stdlib/assert/is-positive-integer":149,"@stdlib/blas/base/gcopy":225,"@stdlib/constants/int32/max":247,"@stdlib/math/base/special/floor":262,"@stdlib/utils/define-nonenumerable-read-only-accessor":342,"@stdlib/utils/define-nonenumerable-read-only-property":344,"@stdlib/utils/define-nonenumerable-read-write-accessor":346}],284:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* A linear congruential pseudorandom number generator (LCG) whose output is shuffled.
*
* @module @stdlib/random/base/minstd-shuffle
*
* @example
* var minstd = require( '@stdlib/random/base/minstd-shuffle' );
*
* var v = minstd();
* // returns <number>
*
* @example
* var factory = require( '@stdlib/random/base/minstd-shuffle' ).factory;
*
* var minstd = factory({
* 'seed': 1234
* });
*
* var v = minstd();
* // returns 1421600654
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var minstd = require( './main.js' );
var factory = require( './factory.js' );
// MAIN //
setReadOnly( minstd, 'factory', factory );
// EXPORTS //
module.exports = minstd;
},{"./factory.js":283,"./main.js":285,"@stdlib/utils/define-nonenumerable-read-only-property":344}],285:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var factory = require( './factory.js' );
var randint32 = require( './rand_int32.js' );
// MAIN //
/**
* Generates a pseudorandom integer on the interval \\( [1,2^{31}-1) \\).
*
* ## Method
*
* Linear congruential generators (LCGs) use the recurrence relation
*
* ```tex
* X_{n+1} = ( a \cdot X_n + c ) \operatorname{mod}(m)
* ```
*
* where the modulus \\( m \\) is a prime number or power of a prime number and \\( a \\) is a primitive root modulo \\( m \\).
*
* <!-- <note> -->
*
* For an LCG to be a Lehmer RNG, the seed \\( X_0 \\) must be coprime to \\( m \\).
*
* <!-- </note> -->
*
* In this implementation, the constants \\( a \\), \\( c \\), and \\( m \\) have the values
*
* ```tex
* \begin{align*}
* a &= 7^5 = 16807 \\
* c &= 0 \\
* m &= 2^{31} - 1 = 2147483647
* \end{align*}
* ```
*
* <!-- <note> -->
*
* The constant \\( m \\) is a Mersenne prime (modulo \\(31\\)).
*
* <!-- </note> -->
*
* <!-- <note> -->
*
* The constant \\( a \\) is a primitive root (modulo \\(31\\)).
*
* <!-- </note> -->
*
* Accordingly, the maximum possible product is
*
* ```tex
* 16807 \cdot (m - 1) \approx 2^{46}
* ```
*
* The values for \\( a \\), \\( c \\), and \\( m \\) are taken from Park and Miller, "Random Number Generators: Good Ones Are Hard To Find". Park's and Miller's article is also the basis for a recipe in the second edition of _Numerical Recipes in C_.
*
* This implementation subsequently shuffles the output of a linear congruential pseudorandom number generator (LCG) using a shuffle table in accordance with the Bays-Durham algorithm.
*
*
* ## Notes
*
* - The generator has a period of approximately \\(2.1\mbox{e}9\\) (see [Numerical Recipes in C, 2nd Edition](#references), p. 279).
*
*
* ## References
*
* - Bays, Carter, and S. D. Durham. 1976. "Improving a Poor Random Number Generator." _ACM Transactions on Mathematical Software_ 2 (1). New York, NY, USA: ACM: 59–64. doi:[10.1145/355666.355670](http://dx.doi.org/10.1145/355666.355670).
* - Herzog, T.N., and G. Lord. 2002. _Applications of Monte Carlo Methods to Finance and Insurance_. ACTEX Publications. [https://books.google.com/books?id=vC7I\\\_gdX-A0C](https://books.google.com/books?id=vC7I\_gdX-A0C).
* - Press, William H., Brian P. Flannery, Saul A. Teukolsky, and William T. Vetterling. 1992. _Numerical Recipes in C: The Art of Scientific Computing, Second Edition_. Cambridge University Press.
*
*
* @function minstd
* @type {PRNG}
* @returns {PositiveInteger} pseudorandom integer
*
* @example
* var v = minstd();
* // returns <number>
*/
var minstd = factory({
'seed': randint32()
});
// EXPORTS //
module.exports = minstd;
},{"./factory.js":283,"./rand_int32.js":286}],286:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var INT32_MAX = require( '@stdlib/constants/int32/max' );
var floor = require( '@stdlib/math/base/special/floor' );
// VARIABLES //
var MAX = INT32_MAX - 1;
// MAIN //
/**
* Returns a pseudorandom integer on the interval \\([1, 2^{31}-1)\\).
*
* @private
* @returns {PositiveInteger} pseudorandom integer
*
* @example
* var v = randint32();
* // returns <number>
*/
function randint32() {
var v = floor( 1.0 + (MAX*Math.random()) ); // eslint-disable-line stdlib/no-builtin-math
return v|0; // asm type annotation
}
// EXPORTS //
module.exports = randint32;
},{"@stdlib/constants/int32/max":247,"@stdlib/math/base/special/floor":262}],287:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
/* eslint-disable max-len */
'use strict';
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var setReadOnlyAccessor = require( '@stdlib/utils/define-nonenumerable-read-only-accessor' );
var setReadWriteAccessor = require( '@stdlib/utils/define-nonenumerable-read-write-accessor' );
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var isObject = require( '@stdlib/assert/is-plain-object' );
var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive;
var isCollection = require( '@stdlib/assert/is-collection' );
var isPositiveInteger = require( '@stdlib/assert/is-positive-integer' ).isPrimitive;
var isInt32Array = require( '@stdlib/assert/is-int32array' );
var INT32_MAX = require( '@stdlib/constants/int32/max' );
var Int32Array = require( '@stdlib/array/int32' );
var gcopy = require( '@stdlib/blas/base/gcopy' );
var typedarray2json = require( '@stdlib/array/to-json' );
var randint32 = require( './rand_int32.js' );
// VARIABLES //
var NORMALIZATION_CONSTANT = (INT32_MAX - 1)|0; // asm type annotation
var MAX_SEED = (INT32_MAX - 1)|0; // asm type annotation
var A = 16807|0; // asm type annotation
// Define the state array schema version:
var STATE_ARRAY_VERSION = 1; // NOTE: anytime the state array schema changes, this value should be incremented!!!
// Define the number of sections in the state array:
var NUM_STATE_SECTIONS = 2; // state, seed
// Define the index offset of the "state" section in the state array:
var STATE_SECTION_OFFSET = 2; // | version | num_sections | state_length | ...state | seed_length | ...seed |
// Define the index offset of the seed section in the state array:
var SEED_SECTION_OFFSET = 4; // | version | num_sections | state_length | ...state | seed_length | ...seed |
// Define the length of the "fixed" length portion of the state array:
var STATE_FIXED_LENGTH = 5; // 1 (version) + 1 (num_sections) + 1 (state_length) + 1 (state) + 1 (seed_length)
// FUNCTIONS //
/**
* Verifies state array integrity.
*
* @private
* @param {Int32Array} state - state array
* @param {boolean} FLG - flag indicating whether the state array was provided as an option (true) or an argument (false)
* @returns {(Error|null)} an error or `null`
*/
function verifyState( state, FLG ) {
var s1;
if ( FLG ) {
s1 = 'option';
} else {
s1 = 'argument';
}
// The state array must have a minimum length...
if ( state.length < STATE_FIXED_LENGTH+1 ) {
return new RangeError( 'invalid '+s1+'. `state` array has insufficient length.' );
}
// The first element of the state array must equal the supported state array schema version...
if ( state[ 0 ] !== STATE_ARRAY_VERSION ) {
return new RangeError( 'invalid '+s1+'. `state` array has an incompatible schema version. Expected: '+STATE_ARRAY_VERSION+'. Actual: '+state[ 0 ]+'.' );
}
// The second element of the state array must contain the number of sections...
if ( state[ 1 ] !== NUM_STATE_SECTIONS ) {
return new RangeError( 'invalid '+s1+'. `state` array has an incompatible number of sections. Expected: '+NUM_STATE_SECTIONS+'. Actual: '+state[ 1 ]+'.' );
}
// The length of the "state" section must equal `1`...
if ( state[ STATE_SECTION_OFFSET ] !== 1 ) {
return new RangeError( 'invalid '+s1+'. `state` array has an incompatible state length. Expected: '+(1).toString()+'. Actual: '+state[ STATE_SECTION_OFFSET ]+'.' );
}
// The length of the "seed" section much match the empirical length...
if ( state[ SEED_SECTION_OFFSET ] !== state.length-STATE_FIXED_LENGTH ) {
return new RangeError( 'invalid '+s1+'. `state` array length is incompatible with seed section length. Expected: '+(state.length-STATE_FIXED_LENGTH)+'. Actual: '+state[ SEED_SECTION_OFFSET ]+'.' );
}
return null;
}
// MAIN //
/**
* Returns a linear congruential pseudorandom number generator (LCG) based on Park and Miller.
*
* @param {Options} [options] - options
* @param {PRNGSeedMINSTD} [options.seed] - pseudorandom number generator seed
* @param {PRNGStateMINSTD} [options.state] - pseudorandom number generator state
* @param {boolean} [options.copy=true] - boolean indicating whether to copy a provided pseudorandom number generator state
* @throws {TypeError} options argument must be an object
* @throws {TypeError} a seed must be either a positive integer less than the maximum signed 32-bit integer or an array-like object containing integers less than the maximum signed 32-bit integer
* @throws {RangeError} a numeric seed must be a positive integer less than the maximum signed 32-bit integer
* @throws {TypeError} state must be an `Int32Array`
* @throws {Error} must provide a valid state
* @throws {TypeError} `copy` option must be a boolean
* @returns {PRNG} LCG PRNG
*
* @example
* var minstd = factory();
*
* var v = minstd();
* // returns <number>
*
* @example
* // Return a seeded LCG:
* var minstd = factory({
* 'seed': 1234
* });
*
* var v = minstd();
* // returns 20739838
*/
function factory( options ) {
var STATE;
var state;
var opts;
var seed;
var slen;
var err;
opts = {};
if ( arguments.length ) {
if ( !isObject( options ) ) {
throw new TypeError( 'invalid argument. Options argument must be an object. Value: `' + options + '`.' );
}
if ( hasOwnProp( options, 'copy' ) ) {
opts.copy = options.copy;
if ( !isBoolean( options.copy ) ) {
throw new TypeError( 'invalid option. `copy` option must be a boolean. Option: `' + options.copy + '`.' );
}
}
if ( hasOwnProp( options, 'state' ) ) {
state = options.state;
opts.state = true;
if ( !isInt32Array( state ) ) {
throw new TypeError( 'invalid option. `state` option must be an Int32Array. Option: `' + state + '`.' );
}
err = verifyState( state, true );
if ( err ) {
throw err;
}
if ( opts.copy === false ) {
STATE = state;
} else {
STATE = new Int32Array( state.length );
gcopy( state.length, state, 1, STATE, 1 );
}
// Create a state "view":
state = new Int32Array( STATE.buffer, STATE.byteOffset+((STATE_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), 1 );
// Create a seed "view":
seed = new Int32Array( STATE.buffer, STATE.byteOffset+((SEED_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), state[ SEED_SECTION_OFFSET ] );
}
// If provided a PRNG state, we ignore the `seed` option...
if ( seed === void 0 ) {
if ( hasOwnProp( options, 'seed' ) ) {
seed = options.seed;
opts.seed = true;
if ( isPositiveInteger( seed ) ) {
if ( seed > MAX_SEED ) {
throw new RangeError( 'invalid option. `seed` option must be a positive integer less than the maximum signed 32-bit integer. Option: `' + seed + '`.' );
}
seed |= 0; // asm type annotation
} else if ( isCollection( seed ) && seed.length > 0 ) {
slen = seed.length;
STATE = new Int32Array( STATE_FIXED_LENGTH+slen );
// Initialize sections:
STATE[ 0 ] = STATE_ARRAY_VERSION;
STATE[ 1 ] = NUM_STATE_SECTIONS;
STATE[ STATE_SECTION_OFFSET ] = 1;
STATE[ SEED_SECTION_OFFSET ] = slen;
// Copy the provided seed array to prevent external mutation, as mutation would lead to an inability to reproduce PRNG values according to the PRNG's stated seed:
gcopy.ndarray( slen, seed, 1, 0, STATE, 1, SEED_SECTION_OFFSET+1 );
// Create a state "view":
state = new Int32Array( STATE.buffer, STATE.byteOffset+((STATE_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), 1 );
// Create a seed "view":
seed = new Int32Array( STATE.buffer, STATE.byteOffset+((SEED_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), slen );
// Initialize the internal PRNG state:
state[ 0 ] = seed[ 0 ];
} else {
throw new TypeError( 'invalid option. `seed` option must be either a positive integer less than the maximum signed 32-bit integer or an array-like object containing integer values less than the maximum signed 32-bit integer. Option: `' + seed + '`.' );
}
} else {
seed = randint32()|0; // asm type annotation
}
}
} else {
seed = randint32()|0; // asm type annotation
}
if ( state === void 0 ) {
STATE = new Int32Array( STATE_FIXED_LENGTH+1 );
// Initialize sections:
STATE[ 0 ] = STATE_ARRAY_VERSION;
STATE[ 1 ] = NUM_STATE_SECTIONS;
STATE[ STATE_SECTION_OFFSET ] = 1;
STATE[ SEED_SECTION_OFFSET ] = 1;
STATE[ SEED_SECTION_OFFSET+1 ] = seed;
// Create a state "view":
state = new Int32Array( STATE.buffer, STATE.byteOffset+((STATE_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), 1 );
// Create a seed "view":
seed = new Int32Array( STATE.buffer, STATE.byteOffset+((SEED_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), 1 );
// Initialize the internal PRNG state:
state[ 0 ] = seed[ 0 ];
}
setReadOnly( minstd, 'NAME', 'minstd' );
setReadOnlyAccessor( minstd, 'seed', getSeed );
setReadOnlyAccessor( minstd, 'seedLength', getSeedLength );
setReadWriteAccessor( minstd, 'state', getState, setState );
setReadOnlyAccessor( minstd, 'stateLength', getStateLength );
setReadOnlyAccessor( minstd, 'byteLength', getStateSize );
setReadOnly( minstd, 'toJSON', toJSON );
setReadOnly( minstd, 'MIN', 1 );
setReadOnly( minstd, 'MAX', INT32_MAX-1 );
setReadOnly( minstd, 'normalized', normalized );
setReadOnly( normalized, 'NAME', minstd.NAME );
setReadOnlyAccessor( normalized, 'seed', getSeed );
setReadOnlyAccessor( normalized, 'seedLength', getSeedLength );
setReadWriteAccessor( normalized, 'state', getState, setState );
setReadOnlyAccessor( normalized, 'stateLength', getStateLength );
setReadOnlyAccessor( normalized, 'byteLength', getStateSize );
setReadOnly( normalized, 'toJSON', toJSON );
setReadOnly( normalized, 'MIN', (minstd.MIN-1.0) / NORMALIZATION_CONSTANT );
setReadOnly( normalized, 'MAX', (minstd.MAX-1.0) / NORMALIZATION_CONSTANT );
return minstd;
/**
* Returns the PRNG seed.
*
* @private
* @returns {PRNGSeedMINSTD} seed
*/
function getSeed() {
var len = STATE[ SEED_SECTION_OFFSET ];
return gcopy( len, seed, 1, new Int32Array( len ), 1 );
}
/**
* Returns the PRNG seed length.
*
* @private
* @returns {PositiveInteger} seed length
*/
function getSeedLength() {
return STATE[ SEED_SECTION_OFFSET ];
}
/**
* Returns the PRNG state length.
*
* @private
* @returns {PositiveInteger} state length
*/
function getStateLength() {
return STATE.length;
}
/**
* Returns the PRNG state size (in bytes).
*
* @private
* @returns {PositiveInteger} state size (in bytes)
*/
function getStateSize() {
return STATE.byteLength;
}
/**
* Returns the current PRNG state.
*
* ## Notes
*
* - The PRNG state array is comprised of a preamble followed by `2` sections:
*
* 0. preamble (version + number of sections)
* 1. internal PRNG state
* 2. PRNG seed
*
* - The first element of the PRNG state array preamble is the state array schema version.
*
* - The second element of the PRNG state array preamble is the number of state array sections (i.e., `2`).
*
* - The first element of each section following the preamble specifies the section length. The remaining section elements comprise the section contents.
*
* @private
* @returns {PRNGStateMINSTD} current state
*/
function getState() {
var len = STATE.length;
return gcopy( len, STATE, 1, new Int32Array( len ), 1 );
}
/**
* Sets the PRNG state.
*
* ## Notes
*
* - If PRNG state is "shared" (meaning a state array was provided during PRNG creation and **not** copied) and one sets the generator state to a state array having a different length, the PRNG does **not** update the existing shared state and, instead, points to the newly provided state array. In order to synchronize PRNG output according to the new shared state array, the state array for **each** relevant PRNG must be **explicitly** set.
* - If PRNG state is "shared" and one sets the generator state to a state array of the same length, the PRNG state is updated (along with the state of all other PRNGs sharing the PRNG's state array).
*
* @private
* @param {PRNGStateMINSTD} s - generator state
* @throws {TypeError} must provide an `Int32Array`
* @throws {Error} must provide a valid state
*/
function setState( s ) {
var err;
if ( !isInt32Array( s ) ) {
throw new TypeError( 'invalid argument. Must provide an Int32Array. Value: `' + s + '`.' );
}
err = verifyState( s, false );
if ( err ) {
throw err;
}
if ( opts.copy === false ) {
if ( opts.state && s.length === STATE.length ) {
gcopy( s.length, s, 1, STATE, 1 ); // update current shared state
} else {
STATE = s; // point to new shared state
opts.state = true; // setting this flag allows updating a shared state even if a state array was not provided at PRNG creation
}
} else {
// Check if we can reuse allocated memory...
if ( s.length !== STATE.length ) {
STATE = new Int32Array( s.length ); // reallocate
}
gcopy( s.length, s, 1, STATE, 1 );
}
// Create a new state "view":
state = new Int32Array( STATE.buffer, STATE.byteOffset+((STATE_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), 1 );
// Create a new seed "view":
seed = new Int32Array( STATE.buffer, STATE.byteOffset+((SEED_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), STATE[ SEED_SECTION_OFFSET ] );
}
/**
* Serializes the pseudorandom number generator as a JSON object.
*
* ## Notes
*
* - `JSON.stringify()` implicitly calls this method when stringifying a PRNG.
*
* @private
* @returns {Object} JSON representation
*/
function toJSON() {
var out = {};
out.type = 'PRNG';
out.name = minstd.NAME;
out.state = typedarray2json( STATE );
out.params = [];
return out;
}
/**
* Generates a pseudorandom integer on the interval \\( [1,2^{31}-1) \\).
*
* @private
* @returns {integer32} pseudorandom integer
*/
function minstd() {
var s = state[ 0 ]|0; // asm type annotation
s = ( (A*s)%INT32_MAX )|0; // asm type annotation
state[ 0 ] = s;
return s|0; // asm type annotation
}
/**
* Generates a pseudorandom number on the interval \\( [0,1) \\).
*
* @private
* @returns {number} pseudorandom number
*/
function normalized() {
return (minstd()-1) / NORMALIZATION_CONSTANT;
}
}
// EXPORTS //
module.exports = factory;
},{"./rand_int32.js":290,"@stdlib/array/int32":10,"@stdlib/array/to-json":17,"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-boolean":81,"@stdlib/assert/is-collection":90,"@stdlib/assert/is-int32array":106,"@stdlib/assert/is-plain-object":147,"@stdlib/assert/is-positive-integer":149,"@stdlib/blas/base/gcopy":225,"@stdlib/constants/int32/max":247,"@stdlib/utils/define-nonenumerable-read-only-accessor":342,"@stdlib/utils/define-nonenumerable-read-only-property":344,"@stdlib/utils/define-nonenumerable-read-write-accessor":346}],288:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* A linear congruential pseudorandom number generator (LCG) based on Park and Miller.
*
* @module @stdlib/random/base/minstd
*
* @example
* var minstd = require( '@stdlib/random/base/minstd' );
*
* var v = minstd();
* // returns <number>
*
* @example
* var factory = require( '@stdlib/random/base/minstd' ).factory;
*
* var minstd = factory({
* 'seed': 1234
* });
*
* var v = minstd();
* // returns 20739838
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var minstd = require( './main.js' );
var factory = require( './factory.js' );
// MAIN //
setReadOnly( minstd, 'factory', factory );
// EXPORTS //
module.exports = minstd;
},{"./factory.js":287,"./main.js":289,"@stdlib/utils/define-nonenumerable-read-only-property":344}],289:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var factory = require( './factory.js' );
var randint32 = require( './rand_int32.js' );
// MAIN //
/**
* Generates a pseudorandom integer on the interval \\( [1,2^{31}-1) \\).
*
* ## Method
*
* Linear congruential generators (LCGs) use the recurrence relation
*
* ```tex
* X_{n+1} = ( a \cdot X_n + c ) \operatorname{mod}(m)
* ```
*
* where the modulus \\( m \\) is a prime number or power of a prime number and \\( a \\) is a primitive root modulo \\( m \\).
*
* <!-- <note> -->
*
* For an LCG to be a Lehmer RNG, the seed \\( X_0 \\) must be coprime to \\( m \\).
*
* <!-- </note> -->
*
* In this implementation, the constants \\( a \\), \\( c \\), and \\( m \\) have the values
*
* ```tex
* \begin{align*}
* a &= 7^5 = 16807 \\
* c &= 0 \\
* m &= 2^{31} - 1 = 2147483647
* \end{align*}
* ```
*
* <!-- <note> -->
*
* The constant \\( m \\) is a Mersenne prime (modulo \\(31\\)).
*
* <!-- </note> -->
*
* <!-- <note> -->
*
* The constant \\( a \\) is a primitive root (modulo \\(31\\)).
*
* <!-- </note> -->
*
* Accordingly, the maximum possible product is
*
* ```tex
* 16807 \cdot (m - 1) \approx 2^{46}
* ```
*
* The values for \\( a \\), \\( c \\), and \\( m \\) are taken from Park and Miller, "Random Number Generators: Good Ones Are Hard To Find". Park's and Miller's article is also the basis for a recipe in the second edition of _Numerical Recipes in C_.
*
*
* ## Notes
*
* - The generator has a period of approximately \\(2.1\mbox{e}9\\) (see [Numerical Recipes in C, 2nd Edition](#references), p. 279).
*
*
* ## References
*
* - Park, S. K., and K. W. Miller. 1988. "Random Number Generators: Good Ones Are Hard to Find." _Communications of the ACM_ 31 (10). New York, NY, USA: ACM: 1192–1201. doi:[10.1145/63039.63042](http://dx.doi.org/10.1145/63039.63042).
* - Press, William H., Brian P. Flannery, Saul A. Teukolsky, and William T. Vetterling. 1992. _Numerical Recipes in C: The Art of Scientific Computing, Second Edition_. Cambridge University Press.
*
*
* @function minstd
* @type {PRNG}
* @returns {PositiveInteger} pseudorandom integer
*
* @example
* var v = minstd();
* // returns <number>
*/
var minstd = factory({
'seed': randint32()
});
// EXPORTS //
module.exports = minstd;
},{"./factory.js":287,"./rand_int32.js":290}],290:[function(require,module,exports){
arguments[4][286][0].apply(exports,arguments)
},{"@stdlib/constants/int32/max":247,"@stdlib/math/base/special/floor":262,"dup":286}],291:[function(require,module,exports){
/* eslint-disable max-lines, max-len */
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*
*
* ## Notice
*
* The original C code and copyright notice are from the [source implementation]{@link http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/CODES/mt19937ar.c}. The implementation has been modified for JavaScript.
*
* ```text
* Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. The names of its contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* ```
*/
'use strict';
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var setReadOnlyAccessor = require( '@stdlib/utils/define-nonenumerable-read-only-accessor' );
var setReadWriteAccessor = require( '@stdlib/utils/define-nonenumerable-read-write-accessor' );
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var isObject = require( '@stdlib/assert/is-plain-object' );
var isCollection = require( '@stdlib/assert/is-collection' );
var isUint32Array = require( '@stdlib/assert/is-uint32array' );
var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive;
var isPositiveInteger = require( '@stdlib/assert/is-positive-integer' ).isPrimitive;
var FLOAT64_MAX_SAFE_INTEGER = require( '@stdlib/constants/float64/max-safe-integer' );
var UINT32_MAX = require( '@stdlib/constants/uint32/max' );
var Uint32Array = require( '@stdlib/array/uint32' );
var max = require( '@stdlib/math/base/special/max' );
var uimul = require( '@stdlib/math/base/special/uimul' );
var gcopy = require( '@stdlib/blas/base/gcopy' );
var typedarray2json = require( '@stdlib/array/to-json' );
var randuint32 = require( './rand_uint32.js' );
// VARIABLES //
// Define the size of the state array (see refs):
var N = 624;
// Define a (magic) constant used for indexing into the state array:
var M = 397;
// Define the maximum seed: 11111111111111111111111111111111
var MAX_SEED = UINT32_MAX >>> 0; // asm type annotation
// For seed arrays, define an initial state (magic) constant: 19650218 => 00000001001010111101011010101010
var SEED_ARRAY_INIT_STATE = 19650218 >>> 0; // asm type annotation
// Define a mask for the most significant `w-r` bits, where `w` is the word size (32 bits) and `r` is the separation point of one word (see refs): 2147483648 => 0x80000000 => 10000000000000000000000000000000
var UPPER_MASK = 0x80000000 >>> 0; // asm type annotation
// Define a mask for the least significant `r` bits (see refs): 2147483647 => 0x7fffffff => 01111111111111111111111111111111
var LOWER_MASK = 0x7fffffff >>> 0; // asm type annotation
// Define a multiplier (see Knuth TAOCP Vol2. 3rd Ed. P.106): 1812433253 => 01101100000001111000100101100101
var KNUTH_MULTIPLIER = 1812433253 >>> 0; // asm type annotation
// Define a (magic) multiplier: 1664525 => 00000000000110010110011000001101
var MAGIC_MULTIPLIER_1 = 1664525 >>> 0; // asm type annotation
// Define a (magic) multiplier: 1566083941 => 01011101010110001000101101100101
var MAGIC_MULTIPLIER_2 = 1566083941 >>> 0; // asm type annotation
// Define a tempering coefficient: 2636928640 => 0x9d2c5680 => 10011101001011000101011010000000
var TEMPERING_COEFFICIENT_1 = 0x9d2c5680 >>> 0; // asm type annotation
// Define a tempering coefficient: 4022730752 => 0xefc60000 => 11101111110001100000000000000000
var TEMPERING_COEFFICIENT_2 = 0xefc60000 >>> 0; // asm type annotation
// Define a constant vector `a` (see refs): 2567483615 => 0x9908b0df => 10011001000010001011000011011111
var MATRIX_A = 0x9908b0df >>> 0; // asm type annotation
// MAG01[x] = x * MATRIX_A; for x = {0,1}
var MAG01 = [ 0x0 >>> 0, MATRIX_A >>> 0 ]; // asm type annotation
// Define a normalization constant when generating double-precision floating-point numbers: 2^53 => 9007199254740992
var FLOAT64_NORMALIZATION_CONSTANT = 1.0 / ( FLOAT64_MAX_SAFE_INTEGER+1.0 ); // eslint-disable-line id-length
// 2^26: 67108864
var TWO_26 = 67108864 >>> 0; // asm type annotation
// 2^32: 2147483648 => 0x80000000 => 10000000000000000000000000000000
var TWO_32 = 0x80000000 >>> 0; // asm type annotation
// 1 (as a 32-bit unsigned integer): 1 => 0x1 => 00000000000000000000000000000001
var ONE = 0x1 >>> 0; // asm type annotation
// Define the maximum normalized pseudorandom double-precision floating-point number: ( (((2^32-1)>>>5)*2^26)+( (2^32-1)>>>6) ) / 2^53
var MAX_NORMALIZED = FLOAT64_MAX_SAFE_INTEGER * FLOAT64_NORMALIZATION_CONSTANT;
// Define the state array schema version:
var STATE_ARRAY_VERSION = 1; // NOTE: anytime the state array schema changes, this value should be incremented!!!
// Define the number of sections in the state array:
var NUM_STATE_SECTIONS = 3; // state, other, seed
// Define the index offset of the "state" section in the state array:
var STATE_SECTION_OFFSET = 2; // | version | num_sections | state_length | ...state | other_length | state_index | seed_length | ...seed |
// Define the index offset of the "other" section in the state array:
var OTHER_SECTION_OFFSET = N + 3; // | version | num_sections | state_length | ...state | other_length | state_index | seed_length | ...seed |
// Define the index offset of the seed section in the state array:
var SEED_SECTION_OFFSET = N + 5; // | version | num_sections | state_length | ...state | other_length | state_index | seed_length | ...seed |
// Define the length of the "fixed" length portion of the state array:
var STATE_FIXED_LENGTH = N + 6; // 1 (version) + 1 (num_sections) + 1 (state_length) + N (state) + 1 (other_length) + 1 (state_index) + 1 (seed_length)
// FUNCTIONS //
/**
* Verifies state array integrity.
*
* @private
* @param {Uint32Array} state - state array
* @param {boolean} FLG - flag indicating whether the state array was provided as an option (true) or an argument (false)
* @returns {(Error|null)} an error or `null`
*/
function verifyState( state, FLG ) {
var s1;
if ( FLG ) {
s1 = 'option';
} else {
s1 = 'argument';
}
// The state array must have a minimum length...
if ( state.length < STATE_FIXED_LENGTH+1 ) {
return new RangeError( 'invalid '+s1+'. `state` array has insufficient length.' );
}
// The first element of the state array must equal the supported state array schema version...
if ( state[ 0 ] !== STATE_ARRAY_VERSION ) {
return new RangeError( 'invalid '+s1+'. `state` array has an incompatible schema version. Expected: '+STATE_ARRAY_VERSION+'. Actual: '+state[ 0 ]+'.' );
}
// The second element of the state array must contain the number of sections...
if ( state[ 1 ] !== NUM_STATE_SECTIONS ) {
return new RangeError( 'invalid '+s1+'. `state` array has an incompatible number of sections. Expected: '+NUM_STATE_SECTIONS+'. Actual: '+state[ 1 ]+'.' );
}
// The length of the "state" section must equal `N`...
if ( state[ STATE_SECTION_OFFSET ] !== N ) {
return new RangeError( 'invalid '+s1+'. `state` array has an incompatible state length. Expected: '+N+'. Actual: '+state[ STATE_SECTION_OFFSET ]+'.' );
}
// The length of the "other" section must equal `1`...
if ( state[ OTHER_SECTION_OFFSET ] !== 1 ) {
return new RangeError( 'invalid '+s1+'. `state` array has an incompatible section length. Expected: '+(1).toString()+'. Actual: '+state[ OTHER_SECTION_OFFSET ]+'.' );
}
// The length of the "seed" section much match the empirical length...
if ( state[ SEED_SECTION_OFFSET ] !== state.length-STATE_FIXED_LENGTH ) {
return new RangeError( 'invalid '+s1+'. `state` array length is incompatible with seed section length. Expected: '+(state.length-STATE_FIXED_LENGTH)+'. Actual: '+state[ SEED_SECTION_OFFSET ]+'.' );
}
return null;
}
/**
* Returns an initial PRNG state.
*
* @private
* @param {Uint32Array} state - state array
* @param {PositiveInteger} N - state size
* @param {uinteger32} s - seed
* @returns {Uint32Array} state array
*/
function createState( state, N, s ) {
var i;
// Set the first element of the state array to the provided seed:
state[ 0 ] = s >>> 0; // equivalent to `s & 0xffffffffUL` in original C implementation
// Initialize the remaining state array elements:
for ( i = 1; i < N; i++ ) {
/*
* In the original C implementation (see `init_genrand()`),
*
* ```c
* mt[i] = (KNUTH_MULTIPLIER * (mt[i-1] ^ (mt[i-1] >> 30)) + i)
* ```
*
* In order to replicate this in JavaScript, we must emulate C-like multiplication of unsigned 32-bit integers.
*/
s = state[ i-1 ]>>>0; // asm type annotation
s = ( s^(s>>>30) )>>>0; // asm type annotation
state[ i ] = ( uimul( s, KNUTH_MULTIPLIER ) + i )>>>0; // asm type annotation
}
return state;
}
/**
* Initializes a PRNG state array according to a seed array.
*
* @private
* @param {Uint32Array} state - state array
* @param {NonNegativeInteger} N - state array length
* @param {Collection} seed - seed array
* @param {NonNegativeInteger} M - seed array length
* @returns {Uint32Array} state array
*/
function initState( state, N, seed, M ) {
var s;
var i;
var j;
var k;
i = 1;
j = 0;
for ( k = max( N, M ); k > 0; k-- ) {
/*
* In the original C implementation (see `init_by_array()`),
*
* ```c
* mt[i] = (mt[i]^((mt[i-1]^(mt[i-1]>>30))*1664525UL)) + seed[j] + j;
* ```
*
* In order to replicate this in JavaScript, we must emulate C-like multiplication of unsigned 32-bit integers.
*/
s = state[ i-1 ]>>>0; // asm type annotation
s = ( s^(s>>>30) )>>>0; // asm type annotation
s = ( uimul( s, MAGIC_MULTIPLIER_1 ) )>>>0; // asm type annotation
state[ i ] = ( ((state[i]>>>0)^s) + seed[j] + j )>>>0; /* non-linear */ // asm type annotation
i += 1;
j += 1;
if ( i >= N ) {
state[ 0 ] = state[ N-1 ];
i = 1;
}
if ( j >= M ) {
j = 0;
}
}
for ( k = N-1; k > 0; k-- ) {
/*
* In the original C implementation (see `init_by_array()`),
*
* ```c
* mt[i] = (mt[i]^((mt[i-1]^(mt[i-1]>>30))*1566083941UL)) - i;
* ```
*
* In order to replicate this in JavaScript, we must emulate C-like multiplication of unsigned 32-bit integers.
*/
s = state[ i-1 ]>>>0; // asm type annotation
s = ( s^(s>>>30) )>>>0; // asm type annotation
s = ( uimul( s, MAGIC_MULTIPLIER_2 ) )>>>0; // asm type annotation
state[ i ] = ( ((state[i]>>>0)^s) - i )>>>0; /* non-linear */ // asm type annotation
i += 1;
if ( i >= N ) {
state[ 0 ] = state[ N-1 ];
i = 1;
}
}
// Ensure a non-zero initial state array:
state[ 0 ] = TWO_32; // MSB (most significant bit) is 1
return state;
}
/**
* Updates a PRNG's internal state by generating the next `N` words.
*
* @private
* @param {Uint32Array} state - state array
* @returns {Uint32Array} state array
*/
function twist( state ) {
var w;
var i;
var j;
var k;
k = N - M;
for ( i = 0; i < k; i++ ) {
w = ( state[i]&UPPER_MASK ) | ( state[i+1]&LOWER_MASK );
state[ i ] = state[ i+M ] ^ ( w>>>1 ) ^ MAG01[ w&ONE ];
}
j = N - 1;
for ( ; i < j; i++ ) {
w = ( state[i]&UPPER_MASK ) | ( state[i+1]&LOWER_MASK );
state[ i ] = state[ i-k ] ^ ( w>>>1 ) ^ MAG01[ w&ONE ];
}
w = ( state[j]&UPPER_MASK ) | ( state[0]&LOWER_MASK );
state[ j ] = state[ M-1 ] ^ ( w>>>1 ) ^ MAG01[ w&ONE ];
return state;
}
// MAIN //
/**
* Returns a 32-bit Mersenne Twister pseudorandom number generator.
*
* ## Notes
*
* - In contrast to the original C implementation, array seeds of length `1` are considered integer seeds. This ensures that the seed `[ 1234 ]` generates the same output as the seed `1234`. In the original C implementation, the two seeds would yield different output, which is **not** obvious from a user perspective.
*
* @param {Options} [options] - options
* @param {PRNGSeedMT19937} [options.seed] - pseudorandom number generator seed
* @param {PRNGStateMT19937} [options.state] - pseudorandom number generator state
* @param {boolean} [options.copy=true] - boolean indicating whether to copy a provided pseudorandom number generator state
* @throws {TypeError} options argument must be an object
* @throws {TypeError} a seed must be either a positive integer less than or equal to the maximum unsigned 32-bit integer or an array-like object containing integers less than or equal to the maximum unsigned 32-bit integer
* @throws {RangeError} a numeric seed must be a positive integer less than or equal to the maximum unsigned 32-bit integer
* @throws {TypeError} state must be a `Uint32Array`
* @throws {Error} must provide a valid state
* @throws {TypeError} `copy` option must be a boolean
* @returns {PRNG} Mersenne Twister PRNG
*
* @example
* var mt19937 = factory();
*
* var v = mt19937();
* // returns <number>
*
* @example
* // Return a seeded Mersenne Twister PRNG:
* var mt19937 = factory({
* 'seed': 1234
* });
*
* var v = mt19937();
* // returns 822569775
*/
function factory( options ) {
var STATE;
var state;
var opts;
var seed;
var slen;
var err;
opts = {};
if ( arguments.length ) {
if ( !isObject( options ) ) {
throw new TypeError( 'invalid argument. Options argument must be an object. Value: `' + options + '`.' );
}
if ( hasOwnProp( options, 'copy' ) ) {
opts.copy = options.copy;
if ( !isBoolean( options.copy ) ) {
throw new TypeError( 'invalid option. `copy` option must be a boolean. Option: `' + options.copy + '`.' );
}
}
if ( hasOwnProp( options, 'state' ) ) {
state = options.state;
opts.state = true;
if ( !isUint32Array( state ) ) {
throw new TypeError( 'invalid option. `state` option must be a Uint32Array. Option: `' + state + '`.' );
}
err = verifyState( state, true );
if ( err ) {
throw err;
}
if ( opts.copy === false ) {
STATE = state;
} else {
STATE = new Uint32Array( state.length );
gcopy( state.length, state, 1, STATE, 1 );
}
// Create a state "view":
state = new Uint32Array( STATE.buffer, STATE.byteOffset+((STATE_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), N );
// Create a seed "view":
seed = new Uint32Array( STATE.buffer, STATE.byteOffset+((SEED_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), state[ SEED_SECTION_OFFSET ] );
}
// If provided a PRNG state, we ignore the `seed` option...
if ( seed === void 0 ) {
if ( hasOwnProp( options, 'seed' ) ) {
seed = options.seed;
opts.seed = true;
if ( isPositiveInteger( seed ) ) {
if ( seed > MAX_SEED ) {
throw new RangeError( 'invalid option. `seed` option must be a positive integer less than or equal to the maximum unsigned 32-bit integer. Option: `' + seed + '`.' );
}
seed >>>= 0; // asm type annotation
} else if ( isCollection( seed ) === false || seed.length < 1 ) {
throw new TypeError( 'invalid option. `seed` option must be either a positive integer less than or equal to the maximum unsigned 32-bit integer or an array-like object containing integer values less than or equal to the maximum unsigned 32-bit integer. Option: `' + seed + '`.' );
} else if ( seed.length === 1 ) {
seed = seed[ 0 ];
if ( !isPositiveInteger( seed ) ) {
throw new TypeError( 'invalid option. `seed` option must be either a positive integer less than or equal to the maximum unsigned 32-bit integer or an array-like object containing integer values less than or equal to the maximum unsigned 32-bit integer. Option: `' + seed + '`.' );
}
if ( seed > MAX_SEED ) {
throw new RangeError( 'invalid option. `seed` option must be either a positive integer less than or equal to the maximum unsigned 32-bit integer or an array-like object containing integer values less than or equal to the maximum unsigned 32-bit integer. Option: `' + seed + '`.' );
}
seed >>>= 0; // asm type annotation
} else {
slen = seed.length;
STATE = new Uint32Array( STATE_FIXED_LENGTH+slen );
// Initialize sections:
STATE[ 0 ] = STATE_ARRAY_VERSION;
STATE[ 1 ] = NUM_STATE_SECTIONS;
STATE[ STATE_SECTION_OFFSET ] = N;
STATE[ OTHER_SECTION_OFFSET ] = 1;
STATE[ OTHER_SECTION_OFFSET+1 ] = N; // state index
STATE[ SEED_SECTION_OFFSET ] = slen;
// Copy the provided seed array to prevent external mutation, as mutation would lead to an inability to reproduce PRNG values according to the PRNG's stated seed:
gcopy.ndarray( slen, seed, 1, 0, STATE, 1, SEED_SECTION_OFFSET+1 );
// Create a state "view":
state = new Uint32Array( STATE.buffer, STATE.byteOffset+((STATE_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), N );
// Create a seed "view":
seed = new Uint32Array( STATE.buffer, STATE.byteOffset+((SEED_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), slen );
// Initialize the internal PRNG state:
state = createState( state, N, SEED_ARRAY_INIT_STATE );
state = initState( state, N, seed, slen );
}
} else {
seed = randuint32() >>> 0; // asm type annotation
}
}
} else {
seed = randuint32() >>> 0; // asm type annotation
}
if ( state === void 0 ) {
STATE = new Uint32Array( STATE_FIXED_LENGTH+1 );
// Initialize sections:
STATE[ 0 ] = STATE_ARRAY_VERSION;
STATE[ 1 ] = NUM_STATE_SECTIONS;
STATE[ STATE_SECTION_OFFSET ] = N;
STATE[ OTHER_SECTION_OFFSET ] = 1;
STATE[ OTHER_SECTION_OFFSET+1 ] = N; // state index
STATE[ SEED_SECTION_OFFSET ] = 1;
STATE[ SEED_SECTION_OFFSET+1 ] = seed;
// Create a state "view":
state = new Uint32Array( STATE.buffer, STATE.byteOffset+((STATE_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), N );
// Create a seed "view":
seed = new Uint32Array( STATE.buffer, STATE.byteOffset+((SEED_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), 1 );
// Initialize the internal PRNG state:
state = createState( state, N, seed );
}
// Note: property order matters in order to maintain consistency of PRNG "shape" (hidden classes).
setReadOnly( mt19937, 'NAME', 'mt19937' );
setReadOnlyAccessor( mt19937, 'seed', getSeed );
setReadOnlyAccessor( mt19937, 'seedLength', getSeedLength );
setReadWriteAccessor( mt19937, 'state', getState, setState );
setReadOnlyAccessor( mt19937, 'stateLength', getStateLength );
setReadOnlyAccessor( mt19937, 'byteLength', getStateSize );
setReadOnly( mt19937, 'toJSON', toJSON );
setReadOnly( mt19937, 'MIN', 1 );
setReadOnly( mt19937, 'MAX', UINT32_MAX );
setReadOnly( mt19937, 'normalized', normalized );
setReadOnly( normalized, 'NAME', mt19937.NAME );
setReadOnlyAccessor( normalized, 'seed', getSeed );
setReadOnlyAccessor( normalized, 'seedLength', getSeedLength );
setReadWriteAccessor( normalized, 'state', getState, setState );
setReadOnlyAccessor( normalized, 'stateLength', getStateLength );
setReadOnlyAccessor( normalized, 'byteLength', getStateSize );
setReadOnly( normalized, 'toJSON', toJSON );
setReadOnly( normalized, 'MIN', 0.0 );
setReadOnly( normalized, 'MAX', MAX_NORMALIZED );
return mt19937;
/**
* Returns the PRNG seed.
*
* @private
* @returns {PRNGSeedMT19937} seed
*/
function getSeed() {
var len = STATE[ SEED_SECTION_OFFSET ];
return gcopy( len, seed, 1, new Uint32Array( len ), 1 );
}
/**
* Returns the PRNG seed length.
*
* @private
* @returns {PositiveInteger} seed length
*/
function getSeedLength() {
return STATE[ SEED_SECTION_OFFSET ];
}
/**
* Returns the PRNG state length.
*
* @private
* @returns {PositiveInteger} state length
*/
function getStateLength() {
return STATE.length;
}
/**
* Returns the PRNG state size (in bytes).
*
* @private
* @returns {PositiveInteger} state size (in bytes)
*/
function getStateSize() {
return STATE.byteLength;
}
/**
* Returns the current PRNG state.
*
* ## Notes
*
* - The PRNG state array is comprised of a preamble followed by `3` sections:
*
* 0. preamble (version + number of sections)
* 1. internal PRNG state
* 2. auxiliary state information
* 3. PRNG seed
*
* - The first element of the PRNG state array preamble is the state array schema version.
*
* - The second element of the PRNG state array preamble is the number of state array sections (i.e., `3`).
*
* - The first element of each section following the preamble specifies the section length. The remaining section elements comprise the section contents.
*
* @private
* @returns {PRNGStateMT19937} current state
*/
function getState() {
var len = STATE.length;
return gcopy( len, STATE, 1, new Uint32Array( len ), 1 );
}
/**
* Sets the PRNG state.
*
* ## Notes
*
* - If PRNG state is "shared" (meaning a state array was provided during PRNG creation and **not** copied) and one sets the generator state to a state array having a different length, the PRNG does **not** update the existing shared state and, instead, points to the newly provided state array. In order to synchronize PRNG output according to the new shared state array, the state array for **each** relevant PRNG must be **explicitly** set.
* - If PRNG state is "shared" and one sets the generator state to a state array of the same length, the PRNG state is updated (along with the state of all other PRNGs sharing the PRNG's state array).
*
* @private
* @param {PRNGStateMT19937} s - generator state
* @throws {TypeError} must provide a `Uint32Array`
* @throws {Error} must provide a valid state
*/
function setState( s ) {
var err;
if ( !isUint32Array( s ) ) {
throw new TypeError( 'invalid argument. Must provide a Uint32Array. Value: `' + s + '`.' );
}
err = verifyState( s, false );
if ( err ) {
throw err;
}
if ( opts.copy === false ) {
if ( opts.state && s.length === STATE.length ) {
gcopy( s.length, s, 1, STATE, 1 ); // update current shared state
} else {
STATE = s; // point to new shared state
opts.state = true; // setting this flag allows updating a shared state even if a state array was not provided at PRNG creation
}
} else {
// Check if we can reuse allocated memory...
if ( s.length !== STATE.length ) {
STATE = new Uint32Array( s.length ); // reallocate
}
gcopy( s.length, s, 1, STATE, 1 );
}
// Create a new state "view":
state = new Uint32Array( STATE.buffer, STATE.byteOffset+((STATE_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), N );
// Create a new seed "view":
seed = new Uint32Array( STATE.buffer, STATE.byteOffset+((SEED_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), STATE[ SEED_SECTION_OFFSET ] );
}
/**
* Serializes the pseudorandom number generator as a JSON object.
*
* ## Notes
*
* - `JSON.stringify()` implicitly calls this method when stringifying a PRNG.
*
* @private
* @returns {Object} JSON representation
*/
function toJSON() {
var out = {};
out.type = 'PRNG';
out.name = mt19937.NAME;
out.state = typedarray2json( STATE );
out.params = [];
return out;
}
/**
* Generates a pseudorandom integer on the interval \\( [1,2^{32}-1) \\).
*
* @private
* @returns {uinteger32} pseudorandom integer
*
* @example
* var r = mt19937();
* // returns <number>
*/
function mt19937() {
var r;
var i;
// Retrieve the current state index:
i = STATE[ OTHER_SECTION_OFFSET+1 ];
// Determine whether we need to update the PRNG state:
if ( i >= N ) {
state = twist( state );
i = 0;
}
// Get the next word of "raw"/untempered state:
r = state[ i ];
// Update the state index:
STATE[ OTHER_SECTION_OFFSET+1 ] = i + 1;
// Tempering transform to compensate for the reduced dimensionality of equidistribution:
r ^= r >>> 11;
r ^= ( r << 7 ) & TEMPERING_COEFFICIENT_1;
r ^= ( r << 15 ) & TEMPERING_COEFFICIENT_2;
r ^= r >>> 18;
return r >>> 0;
}
/**
* Generates a pseudorandom number on the interval \\( [0,1) \\).
*
* ## Notes
*
* - The original C implementation credits Isaku Wada for this algorithm (2002/01/09).
*
* @private
* @returns {number} pseudorandom number
*
* @example
* var r = normalized();
* // returns <number>
*/
function normalized() {
var x = mt19937() >>> 5;
var y = mt19937() >>> 6;
return ( (x*TWO_26)+y ) * FLOAT64_NORMALIZATION_CONSTANT;
}
}
// EXPORTS //
module.exports = factory;
},{"./rand_uint32.js":294,"@stdlib/array/to-json":17,"@stdlib/array/uint32":23,"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-boolean":81,"@stdlib/assert/is-collection":90,"@stdlib/assert/is-plain-object":147,"@stdlib/assert/is-positive-integer":149,"@stdlib/assert/is-uint32array":170,"@stdlib/blas/base/gcopy":225,"@stdlib/constants/float64/max-safe-integer":242,"@stdlib/constants/uint32/max":252,"@stdlib/math/base/special/max":264,"@stdlib/math/base/special/uimul":271,"@stdlib/utils/define-nonenumerable-read-only-accessor":342,"@stdlib/utils/define-nonenumerable-read-only-property":344,"@stdlib/utils/define-nonenumerable-read-write-accessor":346}],292:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* A 32-bit Mersenne Twister pseudorandom number generator.
*
* @module @stdlib/random/base/mt19937
*
* @example
* var mt19937 = require( '@stdlib/random/base/mt19937' );
*
* var v = mt19937();
* // returns <number>
*
* @example
* var factory = require( '@stdlib/random/base/mt19937' ).factory;
*
* var mt19937 = factory({
* 'seed': 1234
* });
*
* var v = mt19937();
* // returns 822569775
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var mt19937 = require( './main.js' );
var factory = require( './factory.js' );
// MAIN //
setReadOnly( mt19937, 'factory', factory );
// EXPORTS //
module.exports = mt19937;
},{"./factory.js":291,"./main.js":293,"@stdlib/utils/define-nonenumerable-read-only-property":344}],293:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var factory = require( './factory.js' );
var randuint32 = require( './rand_uint32.js' );
// MAIN //
/**
* Generates a pseudorandom integer on the interval \\( [1,2^{32}-1) \\).
*
* ## Method
*
* - When generating normalized double-precision floating-point numbers, we first generate two pseudorandom integers \\( x \\) and \\( y \\) on the interval \\( [1,2^{32}-1) \\) for a combined \\( 64 \\) random bits.
*
* - We would like \\( 53 \\) random bits to generate a 53-bit precision integer and, thus, want to discard \\( 11 \\) of the generated bits.
*
* - We do so by discarding \\( 5 \\) bits from \\( x \\) and \\( 6 \\) bits from \\( y \\).
*
* - Accordingly, \\( x \\) contains \\( 27 \\) random bits, which are subsequently shifted left \\( 26 \\) bits (multiplied by \\( 2^{26} \\), and \\( y \\) contains \\( 26 \\) random bits to fill in the lower \\( 26 \\) bits. When summed, they combine to comprise \\( 53 \\) random bits of a double-precision floating-point integer.
*
* - As an example, suppose, for the sake of argument, the 32-bit PRNG generates the maximum unsigned 32-bit integer \\( 2^{32}-1 \\) twice in a row. Then,
*
* ```javascript
* x = 4294967295 >>> 5; // 00000111111111111111111111111111
* y = 4294967295 >>> 6; // 00000011111111111111111111111111
* ```
*
* Multiplying \\( x \\) by \\( 2^{26} \\) returns \\( 9007199187632128 \\), which, in binary, is
*
* ```binarystring
* 0 10000110011 11111111111111111111 11111100000000000000000000000000
* ```
*
* Adding \\( y \\) yields \\( 9007199254740991 \\) (the maximum "safe" double-precision floating-point integer value), which, in binary, is
*
* ```binarystring
* 0 10000110011 11111111111111111111 11111111111111111111111111111111
* ```
*
* - Similarly, suppose the 32-bit PRNG generates the following values
*
* ```javascript
* x = 1 >>> 5; // 0 => 00000000000000000000000000000000
* y = 64 >>> 6; // 1 => 00000000000000000000000000000001
* ```
*
* Multiplying \\( x \\) by \\( 2^{26} \\) returns \\( 0 \\), which, in binary, is
*
* ```binarystring
* 0 00000000000 00000000000000000000 00000000000000000000000000000000
* ```
*
* Adding \\( y \\) yields \\( 1 \\), which, in binary, is
*
* ```binarystring
* 0 01111111111 00000000000000000000 00000000000000000000000000000000
* ```
*
* - As different combinations of \\( x \\) and \\( y \\) are generated, different combinations of double-precision floating-point exponent and significand bits will be toggled, thus generating pseudorandom double-precision floating-point numbers.
*
*
* ## References
*
* - Matsumoto, Makoto, and Takuji Nishimura. 1998. "Mersenne Twister: A 623-dimensionally Equidistributed Uniform Pseudo-random Number Generator." _ACM Transactions on Modeling and Computer Simulation_ 8 (1). New York, NY, USA: ACM: 3–30. doi:[10.1145/272991.272995][@matsumoto:1998a].
* - Harase, Shin. 2017. "Conversion of Mersenne Twister to double-precision floating-point numbers." _ArXiv_ abs/1708.06018 (September). <https://arxiv.org/abs/1708.06018>.
*
* [@matsumoto:1998a]: https://doi.org/10.1145/272991.272995
*
*
* @function mt19937
* @type {PRNG}
* @returns {PositiveInteger} pseudorandom integer
*
* @example
* var v = mt19937();
* // returns <number>
*/
var mt19937 = factory({
'seed': randuint32()
});
// EXPORTS //
module.exports = mt19937;
},{"./factory.js":291,"./rand_uint32.js":294}],294:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var UINT32_MAX = require( '@stdlib/constants/uint32/max' );
var floor = require( '@stdlib/math/base/special/floor' );
// VARIABLES //
var MAX = UINT32_MAX - 1;
// MAIN //
/**
* Returns a pseudorandom integer on the interval \\([1, 2^{32}-1)\\).
*
* @private
* @returns {PositiveInteger} pseudorandom integer
*
* @example
* var v = randuint32();
* // returns <number>
*/
function randuint32() {
var v = floor( 1.0 + (MAX*Math.random()) ); // eslint-disable-line stdlib/no-builtin-math
return v >>> 0; // asm type annotation
}
// EXPORTS //
module.exports = randuint32;
},{"@stdlib/constants/uint32/max":252,"@stdlib/math/base/special/floor":262}],295:[function(require,module,exports){
module.exports={
"name": "mt19937",
"copy": true
}
},{}],296:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var setReadOnlyAccessor = require( '@stdlib/utils/define-nonenumerable-read-only-accessor' );
var setReadWriteAccessor = require( '@stdlib/utils/define-nonenumerable-read-write-accessor' );
var isObject = require( '@stdlib/assert/is-plain-object' );
var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive;
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var typedarray2json = require( '@stdlib/array/to-json' );
var defaults = require( './defaults.json' );
var PRNGS = require( './prngs.js' );
// MAIN //
/**
* Returns a pseudorandom number generator for generating uniformly distributed random numbers on the interval \\( [0,1) \\).
*
* @param {Options} [options] - function options
* @param {string} [options.name='mt19937'] - name of pseudorandom number generator
* @param {*} [options.seed] - pseudorandom number generator seed
* @param {*} [options.state] - pseudorandom number generator state
* @param {boolean} [options.copy=true] - boolean indicating whether to copy a provided pseudorandom number generator state
* @throws {TypeError} must provide an object
* @throws {TypeError} must provide valid options
* @throws {Error} must provide the name of a supported pseudorandom number generator
* @returns {PRNG} pseudorandom number generator
*
* @example
* var uniform = factory();
* var v = uniform();
* // returns <number>
*
* @example
* var uniform = factory({
* 'name': 'minstd'
* });
* var v = uniform();
* // returns <number>
*
* @example
* var uniform = factory({
* 'seed': 12345
* });
* var v = uniform();
* // returns <number>
*
* @example
* var uniform = factory({
* 'name': 'minstd',
* 'seed': 12345
* });
* var v = uniform();
* // returns <number>
*/
function factory( options ) {
var opts;
var rand;
var prng;
opts = {
'name': defaults.name,
'copy': defaults.copy
};
if ( arguments.length ) {
if ( !isObject( options ) ) {
throw new TypeError( 'invalid argument. Must provide an object. Value: `' + options + '`.' );
}
if ( hasOwnProp( options, 'name' ) ) {
opts.name = options.name;
}
if ( hasOwnProp( options, 'state' ) ) {
opts.state = options.state;
if ( opts.state === void 0 ) {
throw new TypeError( 'invalid option. `state` option cannot be undefined. Option: `' + opts.state + '`.' );
}
} else if ( hasOwnProp( options, 'seed' ) ) {
opts.seed = options.seed;
if ( opts.seed === void 0 ) {
throw new TypeError( 'invalid option. `seed` option cannot be undefined. Option: `' + opts.seed + '`.' );
}
}
if ( hasOwnProp( options, 'copy' ) ) {
opts.copy = options.copy;
if ( !isBoolean( opts.copy ) ) {
throw new TypeError( 'invalid option. `copy` option must be a boolean. Option: `' + opts.copy + '`.' );
}
}
}
prng = PRNGS[ opts.name ];
if ( prng === void 0 ) {
throw new Error( 'invalid option. Unrecognized/unsupported PRNG. Option: `' + opts.name + '`.' );
}
if ( opts.state === void 0 ) {
if ( opts.seed === void 0 ) {
rand = prng.factory();
} else {
rand = prng.factory({
'seed': opts.seed
});
}
} else {
rand = prng.factory({
'state': opts.state,
'copy': opts.copy
});
}
setReadOnly( uniform, 'NAME', 'randu' );
setReadOnlyAccessor( uniform, 'seed', getSeed );
setReadOnlyAccessor( uniform, 'seedLength', getSeedLength );
setReadWriteAccessor( uniform, 'state', getState, setState );
setReadOnlyAccessor( uniform, 'stateLength', getStateLength );
setReadOnlyAccessor( uniform, 'byteLength', getStateSize );
setReadOnly( uniform, 'toJSON', toJSON );
setReadOnly( uniform, 'PRNG', rand );
setReadOnly( uniform, 'MIN', rand.normalized.MIN );
setReadOnly( uniform, 'MAX', rand.normalized.MAX );
return uniform;
/**
* Returns the PRNG seed.
*
* @private
* @returns {*} seed
*/
function getSeed() {
return rand.seed;
}
/**
* Returns the PRNG seed length.
*
* @private
* @returns {PositiveInteger} seed length
*/
function getSeedLength() {
return rand.seedLength;
}
/**
* Returns the PRNG state length.
*
* @private
* @returns {PositiveInteger} state length
*/
function getStateLength() {
return rand.stateLength;
}
/**
* Returns the PRNG state size (in bytes).
*
* @private
* @returns {PositiveInteger} state size (in bytes)
*/
function getStateSize() {
return rand.byteLength;
}
/**
* Returns the current pseudorandom number generator state.
*
* @private
* @returns {*} current state
*/
function getState() {
return rand.state;
}
/**
* Sets the pseudorandom number generator state.
*
* @private
* @param {*} s - generator state
* @throws {Error} must provide a valid state
*/
function setState( s ) {
rand.state = s;
}
/**
* Serializes the pseudorandom number generator as a JSON object.
*
* ## Notes
*
* - `JSON.stringify()` implicitly calls this method when stringifying a PRNG.
*
* @private
* @returns {Object} JSON representation
*/
function toJSON() {
var out = {};
out.type = 'PRNG';
out.name = uniform.NAME + '-' + rand.NAME;
out.state = typedarray2json( rand.state );
out.params = [];
return out;
}
/**
* Returns a uniformly distributed pseudorandom number on the interval \\( [0,1) \\).
*
* @private
* @returns {number} pseudorandom number
*
* @example
* var v = uniform();
* // returns <number>
*/
function uniform() {
return rand.normalized();
}
}
// EXPORTS //
module.exports = factory;
},{"./defaults.json":295,"./prngs.js":299,"@stdlib/array/to-json":17,"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-boolean":81,"@stdlib/assert/is-plain-object":147,"@stdlib/utils/define-nonenumerable-read-only-accessor":342,"@stdlib/utils/define-nonenumerable-read-only-property":344,"@stdlib/utils/define-nonenumerable-read-write-accessor":346}],297:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Uniformly distributed pseudorandom numbers on the interval \\( [0,1) \\).
*
* @module @stdlib/random/base/randu
*
* @example
* var randu = require( '@stdlib/random/base/randu' );
*
* var v = randu();
* // returns <number>
*
* @example
* var factory = require( '@stdlib/random/base/randu' ).factory;
*
* var randu = factory({
* 'name': 'minstd',
* 'seed': 12345
* });
*
* var v = randu();
* // returns <number>
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var randu = require( './main.js' );
var factory = require( './factory.js' );
// MAIN //
setReadOnly( randu, 'factory', factory );
// EXPORTS //
module.exports = randu;
},{"./factory.js":296,"./main.js":298,"@stdlib/utils/define-nonenumerable-read-only-property":344}],298:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var factory = require( './factory.js' );
// MAIN //
/**
* Returns a uniformly distributed random number on the interval \\( [0,1) \\).
*
* @name randu
* @type {PRNG}
* @returns {number} pseudorandom number
*
* @example
* var v = randu();
* // returns <number>
*/
var randu = factory();
// EXPORTS //
module.exports = randu;
},{"./factory.js":296}],299:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var prngs = {};
prngs[ 'minstd' ] = require( '@stdlib/random/base/minstd' );
prngs[ 'minstd-shuffle' ] = require( '@stdlib/random/base/minstd-shuffle' );
prngs[ 'mt19937' ] = require( '@stdlib/random/base/mt19937' );
// EXPORTS //
module.exports = prngs;
},{"@stdlib/random/base/minstd":288,"@stdlib/random/base/minstd-shuffle":284,"@stdlib/random/base/mt19937":292}],300:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Regular expression to match a newline character sequence.
*
* @module @stdlib/regexp/eol
*
* @example
* var reEOL = require( '@stdlib/regexp/eol' );
* var RE_EOL = reEOL();
*
* var bool = RE_EOL.test( '\n' );
* // returns true
*
* bool = RE_EOL.test( '\\r\\n' );
* // returns false
*
* @example
* var reEOL = require( '@stdlib/regexp/eol' );
* var replace = require( '@stdlib/string/replace' );
*
* var RE_EOL = reEOL({
* 'flags': 'g'
* });
* var str = '1\n2\n3';
* var out = replace( str, RE_EOL, '' );
*
* @example
* var reEOL = require( '@stdlib/regexp/eol' );
* var bool = reEOL.REGEXP.test( '\r\n' );
* // returns true
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var reEOL = require( './main.js' );
var REGEXP_CAPTURE = require( './regexp_capture.js' );
var REGEXP = require( './regexp.js' );
// MAIN //
setReadOnly( reEOL, 'REGEXP', REGEXP );
setReadOnly( reEOL, 'REGEXP_CAPTURE', REGEXP_CAPTURE );
// EXPORTS //
module.exports = reEOL;
},{"./main.js":301,"./regexp.js":302,"./regexp_capture.js":303,"@stdlib/utils/define-nonenumerable-read-only-property":344}],301:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var validate = require( './validate.js' );
// VARIABLES //
var REGEXP_STRING = '\\r?\\n';
// MAIN //
/**
* Returns a regular expression to match a newline character sequence.
*
* @param {Options} [options] - function options
* @param {string} [options.flags=''] - regular expression flags
* @param {boolean} [options.capture=false] - boolean indicating whether to create a capture group for the match
* @throws {TypeError} options argument must be an object
* @throws {TypeError} must provide valid options
* @returns {RegExp} regular expression
*
* @example
* var RE_EOL = reEOL();
* var bool = RE_EOL.test( '\r\n' );
* // returns true
*
* @example
* var replace = require( '@stdlib/string/replace' );
*
* var RE_EOL = reEOL({
* 'flags': 'g'
* });
* var str = '1\n2\n3';
* var out = replace( str, RE_EOL, '' );
*/
function reEOL( options ) {
var opts;
var err;
if ( arguments.length > 0 ) {
opts = {};
err = validate( opts, options );
if ( err ) {
throw err;
}
if ( opts.capture ) {
return new RegExp( '('+REGEXP_STRING+')', opts.flags );
}
return new RegExp( REGEXP_STRING, opts.flags );
}
return /\r?\n/;
}
// EXPORTS //
module.exports = reEOL;
},{"./validate.js":304}],302:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var reEOL = require( './main.js' );
// MAIN //
/**
* Matches a newline character sequence.
*
* Regular expression: `/\r?\n/`
*
* - `\r?`
* - match a carriage return character (optional)
*
* - `\n`
* - match a line feed character
*
* @constant
* @type {RegExp}
* @default /\r?\n/
*/
var REGEXP = reEOL();
// EXPORTS //
module.exports = REGEXP;
},{"./main.js":301}],303:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var reEOL = require( './main.js' );
// MAIN //
/**
* Captures a newline character sequence.
*
* Regular expression: `/\r?\n/`
*
* - `()`
* - capture
*
* - `\r?`
* - match a carriage return character (optional)
*
* - `\n`
* - match a line feed character
*
* @constant
* @type {RegExp}
* @default /(\r?\n)/
*/
var REGEXP_CAPTURE = reEOL({
'capture': true
});
// EXPORTS //
module.exports = REGEXP_CAPTURE;
},{"./main.js":301}],304:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isObject = require( '@stdlib/assert/is-plain-object' );
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive;
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
// MAIN //
/**
* Validates function options.
*
* @private
* @param {Object} opts - destination object
* @param {Options} options - function options
* @param {string} [options.flags] - regular expression flags
* @param {boolean} [options.capture] - boolean indicating whether to wrap a regular expression matching a decimal number with a capture group
* @returns {(Error|null)} null or an error object
*
* @example
* var opts = {};
* var options = {
* 'flags': 'gm'
* };
* var err = validate( opts, options );
* if ( err ) {
* throw err;
* }
*/
function validate( opts, options ) {
if ( !isObject( options ) ) {
return new TypeError( 'invalid argument. Options must be an object. Value: `' + options + '`.' );
}
if ( hasOwnProp( options, 'flags' ) ) {
opts.flags = options.flags;
if ( !isString( opts.flags ) ) {
return new TypeError( 'invalid option. `flags` option must be a string primitive. Option: `' + opts.flags + '`.' );
}
}
if ( hasOwnProp( options, 'capture' ) ) {
opts.capture = options.capture;
if ( !isBoolean( opts.capture ) ) {
return new TypeError( 'invalid option. `capture` option must be a boolean primitive. Option: `' + opts.capture + '`.' );
}
}
return null;
}
// EXPORTS //
module.exports = validate;
},{"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-boolean":81,"@stdlib/assert/is-plain-object":147,"@stdlib/assert/is-string":158}],305:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Regular expression to capture everything that is not a space immediately after the `function` keyword and before the first left parenthesis.
*
* @module @stdlib/regexp/function-name
*
* @example
* var reFunctionName = require( '@stdlib/regexp/function-name' );
* var RE_FUNCTION_NAME = reFunctionName();
*
* function fname( fcn ) {
* return RE_FUNCTION_NAME.exec( fcn.toString() )[ 1 ];
* }
*
* var fn = fname( Math.sqrt );
* // returns 'sqrt'
*
* fn = fname( Int8Array );
* // returns 'Int8Array'
*
* fn = fname( Object.prototype.toString );
* // returns 'toString'
*
* fn = fname( function(){} );
* // returns ''
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var reFunctionName = require( './main.js' );
var REGEXP = require( './regexp.js' );
// MAIN //
setReadOnly( reFunctionName, 'REGEXP', REGEXP );
// EXPORTS //
module.exports = reFunctionName;
},{"./main.js":306,"./regexp.js":307,"@stdlib/utils/define-nonenumerable-read-only-property":344}],306:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Returns a regular expression to capture everything that is not a space immediately after the `function` keyword and before the first left parenthesis.
*
* @returns {RegExp} regular expression
*
* @example
* var RE_FUNCTION_NAME = reFunctionName();
*
* function fname( fcn ) {
* return RE_FUNCTION_NAME.exec( fcn.toString() )[ 1 ];
* }
*
* var fn = fname( Math.sqrt );
* // returns 'sqrt'
*
* fn = fname( Int8Array );
* // returns 'Int8Array'
*
* fn = fname( Object.prototype.toString );
* // returns 'toString'
*
* fn = fname( function(){} );
* // returns ''
*/
function reFunctionName() {
return /^\s*function\s*([^(]*)/i;
}
// EXPORTS //
module.exports = reFunctionName;
},{}],307:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var reFunctionName = require( './main.js' );
// MAIN //
/**
* Captures everything that is not a space immediately after the `function` keyword and before the first left parenthesis.
*
* Regular expression: `/^\s*function\s*([^(]*)/i`
*
* - `/^\s*`
* - Match zero or more spaces at beginning
*
* - `function`
* - Match the word `function`
*
* - `\s*`
* - Match zero or more spaces after the word `function`
*
* - `()`
* - Capture
*
* - `[^(]*`
* - Match anything except a left parenthesis `(` zero or more times
*
* - `/i`
* - ignore case
*
* @constant
* @type {RegExp}
* @default /^\s*function\s*([^(]*)/i
*/
var RE_FUNCTION_NAME = reFunctionName();
// EXPORTS //
module.exports = RE_FUNCTION_NAME;
},{"./main.js":306}],308:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Return a regular expression to parse a regular expression string.
*
* @module @stdlib/regexp/regexp
*
* @example
* var reRegExp = require( '@stdlib/regexp/regexp' );
*
* var RE_REGEXP = reRegExp();
*
* var bool = RE_REGEXP.test( '/^beep$/' );
* // returns true
*
* bool = RE_REGEXP.test( '' );
* // returns false
*
* @example
* var reRegExp = require( '@stdlib/regexp/regexp' );
*
* var RE_REGEXP = reRegExp();
*
* var parts = RE_REGEXP.exec( '/^.*$/ig' );
* // returns [ '/^.*$/ig', '^.*$', 'ig', 'index': 0, 'input': '/^.*$/ig' ]
*/
// MAIN //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var reRegExp = require( './main.js' );
var REGEXP = require( './regexp.js' );
// MAIN //
setReadOnly( reRegExp, 'REGEXP', REGEXP );
// EXPORTS //
module.exports = reRegExp;
// EXPORTS //
module.exports = reRegExp;
},{"./main.js":309,"./regexp.js":310,"@stdlib/utils/define-nonenumerable-read-only-property":344}],309:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Returns a regular expression to parse a regular expression string.
*
* @returns {RegExp} regular expression
*
* @example
* var RE_REGEXP = reRegExp();
*
* var bool = RE_REGEXP.test( '/^beep$/' );
* // returns true
*
* bool = RE_REGEXP.test( '' );
* // returns false
*/
function reRegExp() {
return /^\/((?:\\\/|[^\/])+)\/([imgy]*)$/; // eslint-disable-line no-useless-escape
}
// EXPORTS //
module.exports = reRegExp;
},{}],310:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var reRegExp = require( './main.js' );
// MAIN //
/**
* Matches parts of a regular expression string.
*
* Regular expression: `/^\/((?:\\\/|[^\/])+)\/([imgy]*)$/`
*
* - `/^\/`
* - match a string that begins with a `/`
*
* - `()`
* - capture
*
* - `(?:)+`
* - capture, but do not remember, a group of characters which occur one or more times
*
* - `\\\/`
* - match the literal `\/`
*
* - `|`
* - OR
*
* - `[^\/]`
* - anything which is not the literal `\/`
*
* - `\/`
* - match the literal `/`
*
* - `([imgy]*)`
* - capture any characters matching `imgy` occurring zero or more times
*
* - `$/`
* - string end
*
*
* @constant
* @type {RegExp}
* @default /^\/((?:\\\/|[^\/])+)\/([imgy]*)$/
*/
var RE_REGEXP = reRegExp();
// EXPORTS //
module.exports = RE_REGEXP;
},{"./main.js":309}],311:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var bench = require( '@stdlib/bench' );
var randu = require( '@stdlib/random/base/randu' );
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var EPS = require( '@stdlib/constants/float64/eps' );
var pkg = require( './../package.json' ).name;
var median = require( './../lib' );
// MAIN //
bench( pkg, function benchmark( b ) {
var lambda;
var y;
var i;
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
lambda = ( randu()*20.0 ) + EPS;
y = median( lambda );
if ( isnan( y ) ) {
b.fail( 'should not return NaN' );
}
}
b.toc();
if ( isnan( y ) ) {
b.fail( 'should not return NaN' );
}
b.pass( 'benchmark finished' );
b.end();
});
},{"./../lib":312,"./../package.json":314,"@stdlib/bench":224,"@stdlib/constants/float64/eps":237,"@stdlib/math/base/assert/is-nan":258,"@stdlib/random/base/randu":297}],312:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Exponential distribution median.
*
* @module @stdlib/stats/base/dists/exponential/median
*
* @example
* var median = require( '@stdlib/stats/base/dists/exponential/median' );
*
* var v = median( 11.0 );
* // returns ~0.063
*
* v = median( 4.5 );
* // returns ~0.154
*/
// MODULES //
var median = require( './median.js' );
// EXPORTS //
module.exports = median;
},{"./median.js":313}],313:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var LN2 = require( '@stdlib/constants/float64/ln-two' );
// MAIN //
/**
* Returns the median of an exponential distribution.
*
* @param {NonNegativeNumber} lambda - rate parameter
* @returns {NonNegativeNumber} median
*
* @example
* var v = median( 9.0 );
* // returns ~0.077
*
* @example
* var v = median( 1.0 );
* // returns ~0.693
*
* @example
* var v = median( -0.2 );
* // returns NaN
*
* @example
* var v = median( NaN );
* // returns NaN
*/
function median( lambda ) {
if ( isnan( lambda ) || lambda < 0.0 ) {
return NaN;
}
return ( 1.0 / lambda ) * LN2;
}
// EXPORTS //
module.exports = median;
},{"@stdlib/constants/float64/ln-two":241,"@stdlib/math/base/assert/is-nan":258}],314:[function(require,module,exports){
module.exports={
"name": "@stdlib/stats/base/dists/exponential/median",
"version": "0.0.0",
"description": "Exponential distribution median.",
"license": "Apache-2.0",
"author": {
"name": "The Stdlib Authors",
"url": "https://github.com/stdlib-js/stdlib/graphs/contributors"
},
"contributors": [
{
"name": "The Stdlib Authors",
"url": "https://github.com/stdlib-js/stdlib/graphs/contributors"
}
],
"main": "./lib",
"directories": {
"benchmark": "./benchmark",
"doc": "./docs",
"example": "./examples",
"lib": "./lib",
"test": "./test"
},
"types": "./docs/types",
"scripts": {},
"homepage": "https://github.com/stdlib-js/stdlib",
"repository": {
"type": "git",
"url": "git://github.com/stdlib-js/stdlib.git"
},
"bugs": {
"url": "https://github.com/stdlib-js/stdlib/issues"
},
"dependencies": {},
"devDependencies": {},
"engines": {
"node": ">=0.10.0",
"npm": ">2.7.0"
},
"os": [
"aix",
"darwin",
"freebsd",
"linux",
"macos",
"openbsd",
"sunos",
"win32",
"windows"
],
"keywords": [
"stdlib",
"stdmath",
"statistics",
"stats",
"distribution",
"dist",
"exponential",
"parameter",
"continuous",
"median",
"location",
"center",
"percentile",
"order",
"univariate"
]
}
},{}],315:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var logger = require( 'debug' );
// VARIABLES //
var debug = logger( 'transform-stream:transform' );
// MAIN //
/**
* Implements the `_transform` method as a pass through.
*
* @private
* @param {(Uint8Array|Buffer|string)} chunk - streamed chunk
* @param {string} encoding - Buffer encoding
* @param {Callback} clbk - callback to invoke after transforming the streamed chunk
*/
function transform( chunk, encoding, clbk ) {
debug( 'Received a new chunk. Chunk: %s. Encoding: %s.', chunk.toString(), encoding );
clbk( null, chunk );
}
// EXPORTS //
module.exports = transform;
},{"debug":428}],316:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var logger = require( 'debug' );
var Transform = require( 'readable-stream' ).Transform;
var inherit = require( '@stdlib/utils/inherit' );
var copy = require( '@stdlib/utils/copy' );
var DEFAULTS = require( './defaults.json' );
var validate = require( './validate.js' );
var destroy = require( './destroy.js' );
var _transform = require( './_transform.js' ); // eslint-disable-line no-underscore-dangle
// VARIABLES //
var debug = logger( 'transform-stream:ctor' );
// MAIN //
/**
* Transform stream constructor factory.
*
* @param {Options} [options] - stream options
* @param {Function} [options.transform] - callback to invoke upon receiving a new chunk
* @param {Function} [options.flush] - callback to invoke after receiving all chunks and prior to the stream closing
* @param {boolean} [options.objectMode=false] - specifies whether a stream should operate in object mode
* @param {(string|null)} [options.encoding=null] - specifies how `Buffer` objects should be decoded to `strings`
* @param {NonNegativeNumber} [options.highWaterMark] - specifies the `Buffer` level for when `write()` starts returning `false`
* @param {boolean} [options.allowHalfOpen=false] - specifies whether the stream should remain open even if one side ends
* @param {boolean} [options.decodeStrings=true] - specifies whether to decode `strings` into `Buffer` objects when writing
* @throws {TypeError} options argument must be an object
* @throws {TypeError} must provide valid options
* @returns {Function} Transform stream constructor
*
* @example
* var stdout = require( '@stdlib/streams/node/stdout' );
*
* function transform( chunk, enc, clbk ) {
* clbk( null, chunk.toString()+'\n' );
* }
*
* var opts = {
* 'transform': transform
* };
*
* var TransformStream = ctor( opts );
*
* var stream = new TransformStream();
*
* stream.pipe( stdout );
*
* stream.write( '1' );
* stream.write( '2' );
* stream.write( '3' );
*
* stream.end();
*
* // prints: '1\n2\n3\n'
*/
function ctor( options ) {
var transform;
var copts;
var err;
copts = copy( DEFAULTS );
if ( arguments.length ) {
err = validate( copts, options );
if ( err ) {
throw err;
}
}
if ( copts.transform ) {
transform = copts.transform;
} else {
transform = _transform;
}
/**
* Transform stream constructor.
*
* @private
* @constructor
* @param {Options} [options] - stream options
* @param {boolean} [options.objectMode=false] - specifies whether a stream should operate in object mode
* @param {(string|null)} [options.encoding=null] - specifies how `Buffer` objects should be decoded to `strings`
* @param {NonNegativeNumber} [options.highWaterMark] - specifies the `Buffer` level for when `write()` starts returning `false`
* @param {boolean} [options.allowHalfOpen=false] - specifies whether the stream should remain open even if one side ends
* @param {boolean} [options.decodeStrings=true] - specifies whether to decode `strings` into `Buffer` objects when writing
* @throws {TypeError} options argument must be an object
* @throws {TypeError} must provide valid options
* @returns {TransformStream} transform stream
*
* @example
* var stdout = require( '@stdlib/streams/node/stdout' );
*
* var stream = new TransformStream();
*
* stream.pipe( stdout );
*
* stream.write( '1' );
* stream.write( '2' );
* stream.write( '3' );
*
* stream.end();
*
* // prints: '1\n2\n3\n'
*/
function TransformStream( options ) {
var opts;
var err;
if ( !( this instanceof TransformStream ) ) {
if ( arguments.length ) {
return new TransformStream( options );
}
return new TransformStream();
}
opts = copy( copts );
if ( arguments.length ) {
err = validate( opts, options );
if ( err ) {
throw err;
}
}
debug( 'Creating a transform stream configured with the following options: %s.', JSON.stringify( opts ) );
Transform.call( this, opts );
this._destroyed = false;
return this;
}
/**
* Inherit from the `Transform` prototype.
*/
inherit( TransformStream, Transform );
/**
* Implements the `_transform` method.
*
* @private
* @name _transform
* @memberof TransformStream.prototype
* @type {Function}
* @param {(Buffer|string)} chunk - streamed chunk
* @param {string} encoding - Buffer encoding
* @param {Callback} clbk - callback to invoke after transforming the streamed chunk
*/
TransformStream.prototype._transform = transform; // eslint-disable-line no-underscore-dangle
if ( copts.flush ) {
/**
* Implements the `_flush` method.
*
* @private
* @name _flush
* @memberof TransformStream.prototype
* @type {Function}
* @param {Callback} callback to invoke after performing flush tasks
*/
TransformStream.prototype._flush = copts.flush; // eslint-disable-line no-underscore-dangle
}
/**
* Gracefully destroys a stream, providing backward compatibility.
*
* @private
* @name destroy
* @memberof TransformStream.prototype
* @type {Function}
* @param {Object} [error] - optional error message
* @returns {TransformStream} stream instance
*/
TransformStream.prototype.destroy = destroy;
return TransformStream;
}
// EXPORTS //
module.exports = ctor;
},{"./_transform.js":315,"./defaults.json":317,"./destroy.js":318,"./validate.js":323,"@stdlib/utils/copy":340,"@stdlib/utils/inherit":372,"debug":428,"readable-stream":445}],317:[function(require,module,exports){
module.exports={
"objectMode": false,
"encoding": null,
"allowHalfOpen": false,
"decodeStrings": true
}
},{}],318:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var logger = require( 'debug' );
var nextTick = require( '@stdlib/utils/next-tick' );
// VARIABLES //
var debug = logger( 'transform-stream:destroy' );
// MAIN //
/**
* Gracefully destroys a stream, providing backward compatibility.
*
* @private
* @param {Object} [error] - optional error message
* @returns {Stream} stream instance
*/
function destroy( error ) {
/* eslint-disable no-invalid-this */
var self;
if ( this._destroyed ) {
debug( 'Attempted to destroy an already destroyed stream.' );
return this;
}
self = this;
this._destroyed = true;
nextTick( close );
return this;
/**
* Closes a stream.
*
* @private
*/
function close() {
if ( error ) {
debug( 'Stream was destroyed due to an error. Error: %s.', JSON.stringify( error ) );
self.emit( 'error', error );
}
debug( 'Closing the stream...' );
self.emit( 'close' );
}
}
// EXPORTS //
module.exports = destroy;
},{"@stdlib/utils/next-tick":398,"debug":428}],319:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isObject = require( '@stdlib/assert/is-plain-object' );
var copy = require( '@stdlib/utils/copy' );
var Stream = require( './main.js' );
// MAIN //
/**
* Creates a reusable transform stream factory.
*
* @param {Options} [options] - stream options
* @param {boolean} [options.objectMode=false] - specifies whether a stream should operate in object mode
* @param {(string|null)} [options.encoding=null] - specifies how `Buffer` objects should be decoded to `strings`
* @param {NonNegativeNumber} [options.highWaterMark] - specifies the `Buffer` level for when `write()` starts returning `false`
* @param {boolean} [options.allowHalfOpen=false] - specifies whether the stream should remain open even if one side ends
* @param {boolean} [options.decodeStrings=true] - specifies whether to decode `strings` into `Buffer` objects when writing
* @throws {TypeError} options argument must be an object
* @returns {Function} transform stream factory
*
* @example
* function transform( chunk, enc, clbk ) {
* clbk( null, chunk.toString()+'\n' );
* }
*
* var opts = {
* 'objectMode': true,
* 'encoding': 'utf8',
* 'highWaterMark': 64,
* 'decodeStrings': false
* };
*
* var factory = streamFactory( opts );
*
* // Create 10 identically configured streams...
* var streams = [];
* var i;
* for ( i = 0; i < 10; i++ ) {
* streams.push( factory( transform ) );
* }
*/
function streamFactory( options ) {
var opts;
if ( arguments.length ) {
if ( !isObject( options ) ) {
throw new TypeError( 'invalid argument. Options argument must be an object. Value: `' + options + '`.' );
}
opts = copy( options );
} else {
opts = {};
}
return createStream;
/**
* Creates a transform stream.
*
* @private
* @param {Function} transform - callback to invoke upon receiving a new chunk
* @param {Function} [flush] - callback to invoke after receiving all chunks and prior to the stream closing
* @throws {TypeError} must provide valid options
* @throws {TypeError} transform callback must be a function
* @throws {TypeError} flush callback must be a function
* @returns {TransformStream} transform stream
*/
function createStream( transform, flush ) {
opts.transform = transform;
if ( arguments.length > 1 ) {
opts.flush = flush;
} else {
delete opts.flush; // clear any previous `flush`
}
return new Stream( opts );
}
}
// EXPORTS //
module.exports = streamFactory;
},{"./main.js":321,"@stdlib/assert/is-plain-object":147,"@stdlib/utils/copy":340}],320:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Transform stream.
*
* @module @stdlib/streams/node/transform
*
* @example
* var stdout = require( '@stdlib/streams/node/stdout' );
* var transformStream = require( '@stdlib/streams/node/transform' );
*
* function transform( chunk, enc, clbk ) {
* clbk( null, chunk.toString()+'\n' );
* }
*
* var opts = {
* 'transform': transform
* };
* var stream = transformStream( opts );
*
* stream.pipe( stdout );
*
* stream.write( '1' );
* stream.write( '2' );
* stream.write( '3' );
*
* stream.end();
* // => '1\n2\n3\n'
*
*
* @example
* var transformStream = require( '@stdlib/streams/node/transform' );
*
* function transform( chunk, enc, clbk ) {
* clbk( null, chunk.toString()+'\n' );
* }
*
* var opts = {
* 'objectMode': true,
* 'encoding': 'utf8',
* 'highWaterMark': 64,
* 'decodeStrings': false
* };
*
* var factory = transformStream.factory( opts );
*
* // Create 10 identically configured streams...
* var streams = [];
* var i;
* for ( i = 0; i < 10; i++ ) {
* streams.push( factory( transform ) );
* }
*
*
* @example
* var stdout = require( '@stdlib/streams/node/stdout' );
* var transformStream = require( '@stdlib/streams/node/transform' );
*
* function stringify( chunk, enc, clbk ) {
* clbk( null, JSON.stringify( chunk ) );
* }
*
* function newline( chunk, enc, clbk ) {
* clbk( null, chunk+'\n' );
* }
*
* var s1 = transformStream.objectMode({
* 'transform': stringify
* });
*
* var s2 = transformStream.objectMode({
* 'transform': newline
* });
*
* s1.pipe( s2 ).pipe( stdout );
*
* s1.write( {'value': 'a'} );
* s1.write( {'value': 'b'} );
* s1.write( {'value': 'c'} );
*
* s1.end();
* // => '{"value":"a"}\n{"value":"b"}\n{"value":"c"}\n'
*
*
* @example
* var stdout = require( '@stdlib/streams/node/stdout' );
* var transformStream = require( '@stdlib/streams/node/transform' );
*
* function transform( chunk, enc, clbk ) {
* clbk( null, chunk.toString()+'\n' );
* }
*
* var opts = {
* 'transform': transform
* };
*
* var Stream = transformStream.ctor( opts );
*
* var stream = new Stream();
*
* stream.pipe( stdout );
*
* stream.write( '1' );
* stream.write( '2' );
* stream.write( '3' );
*
* stream.end();
* // => '1\n2\n3\n'
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var transform = require( './main.js' );
var objectMode = require( './object_mode.js' );
var factory = require( './factory.js' );
var ctor = require( './ctor.js' );
// MAIN //
setReadOnly( transform, 'objectMode', objectMode );
setReadOnly( transform, 'factory', factory );
setReadOnly( transform, 'ctor', ctor );
// EXPORTS //
module.exports = transform;
},{"./ctor.js":316,"./factory.js":319,"./main.js":321,"./object_mode.js":322,"@stdlib/utils/define-nonenumerable-read-only-property":344}],321:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var logger = require( 'debug' );
var Transform = require( 'readable-stream' ).Transform;
var inherit = require( '@stdlib/utils/inherit' );
var copy = require( '@stdlib/utils/copy' );
var DEFAULTS = require( './defaults.json' );
var validate = require( './validate.js' );
var destroy = require( './destroy.js' );
var _transform = require( './_transform.js' ); // eslint-disable-line no-underscore-dangle
// VARIABLES //
var debug = logger( 'transform-stream:main' );
// MAIN //
/**
* Transform stream constructor.
*
* @constructor
* @param {Options} [options] - stream options
* @param {Function} [options.transform] - callback to invoke upon receiving a new chunk
* @param {Function} [options.flush] - callback to invoke after receiving all chunks and prior to the stream closing
* @param {boolean} [options.objectMode=false] - specifies whether stream should operate in object mode
* @param {(string|null)} [options.encoding=null] - specifies how `Buffer` objects should be decoded to `strings`
* @param {NonNegativeNumber} [options.highWaterMark] - specifies the `Buffer` level for when `write()` starts returning `false`
* @param {boolean} [options.allowHalfOpen=false] - specifies whether the stream should remain open even if one side ends
* @param {boolean} [options.decodeStrings=true] - specifies whether to decode `strings` into `Buffer` objects when writing
* @throws {TypeError} must provide valid options
* @returns {TransformStream} transform stream
*
* @example
* var stdout = require( '@stdlib/streams/node/stdout' );
*
* function transform( chunk, enc, clbk ) {
* clbk( null, chunk.toString()+'\n' );
* }
*
* var opts = {
* 'transform': transform
* };
* var stream = new TransformStream( opts );
*
* stream.pipe( stdout );
*
* stream.write( '1' );
* stream.write( '2' );
* stream.write( '3' );
*
* stream.end();
*
* // prints: '1\n2\n3\n'
*/
function TransformStream( options ) {
var opts;
var err;
if ( !( this instanceof TransformStream ) ) {
if ( arguments.length ) {
return new TransformStream( options );
}
return new TransformStream();
}
opts = copy( DEFAULTS );
if ( arguments.length ) {
err = validate( opts, options );
if ( err ) {
throw err;
}
}
debug( 'Creating a transform stream configured with the following options: %s.', JSON.stringify( opts ) );
Transform.call( this, opts );
this._destroyed = false;
if ( opts.transform ) {
this._transform = opts.transform;
} else {
this._transform = _transform;
}
if ( opts.flush ) {
this._flush = opts.flush;
}
return this;
}
/*
* Inherit from the `Transform` prototype.
*/
inherit( TransformStream, Transform );
/**
* Gracefully destroys a stream, providing backward compatibility.
*
* @name destroy
* @memberof TransformStream.prototype
* @type {Function}
* @param {Object} [error] - optional error message
* @returns {TransformStream} stream instance
*/
TransformStream.prototype.destroy = destroy;
// EXPORTS //
module.exports = TransformStream;
},{"./_transform.js":315,"./defaults.json":317,"./destroy.js":318,"./validate.js":323,"@stdlib/utils/copy":340,"@stdlib/utils/inherit":372,"debug":428,"readable-stream":445}],322:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isObject = require( '@stdlib/assert/is-plain-object' );
var copy = require( '@stdlib/utils/copy' );
var Stream = require( './main.js' );
// MAIN //
/**
* Returns a transform stream with `objectMode` set to `true`.
*
* @param {Options} [options] - stream options
* @param {Function} [options.transform] - callback to invoke upon receiving a new chunk
* @param {Function} [options.flush] - callback to invoke after receiving all chunks and prior to the stream closing
* @param {(string|null)} [options.encoding=null] - specifies how `Buffer` objects should be decoded to `strings`
* @param {NonNegativeNumber} [options.highWaterMark] - specifies the `Buffer` level for when `write()` starts returning `false`
* @param {boolean} [options.allowHalfOpen=false] - specifies whether the stream should remain open even if one side ends
* @param {boolean} [options.decodeStrings=true] - specifies whether to decode `strings` into `Buffer` objects when writing
* @throws {TypeError} options argument must be an object
* @throws {TypeError} must provide valid options
* @returns {TransformStream} transform stream
*
* @example
* var stdout = require( '@stdlib/streams/node/stdout' );
*
* function stringify( chunk, enc, clbk ) {
* clbk( null, JSON.stringify( chunk ) );
* }
*
* function newline( chunk, enc, clbk ) {
* clbk( null, chunk+'\n' );
* }
*
* var s1 = objectMode({
* 'transform': stringify
* });
*
* var s2 = objectMode({
* 'transform': newline
* });
*
* s1.pipe( s2 ).pipe( stdout );
*
* s1.write( {'value': 'a'} );
* s1.write( {'value': 'b'} );
* s1.write( {'value': 'c'} );
*
* s1.end();
*
* // prints: '{"value":"a"}\n{"value":"b"}\n{"value":"c"}\n'
*/
function objectMode( options ) {
var opts;
if ( arguments.length ) {
if ( !isObject( options ) ) {
throw new TypeError( 'invalid argument. Options argument must be an object. Value: `' + options + '`.' );
}
opts = copy( options );
} else {
opts = {};
}
opts.objectMode = true;
return new Stream( opts );
}
// EXPORTS //
module.exports = objectMode;
},{"./main.js":321,"@stdlib/assert/is-plain-object":147,"@stdlib/utils/copy":340}],323:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isObject = require( '@stdlib/assert/is-plain-object' );
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var isFunction = require( '@stdlib/assert/is-function' );
var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive;
var isNonNegative = require( '@stdlib/assert/is-nonnegative-number' ).isPrimitive;
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
// MAIN //
/**
* Validates function options.
*
* @private
* @param {Object} opts - destination object
* @param {Options} options - function options
* @param {Function} [options.transform] - callback to invoke upon receiving a new chunk
* @param {Function} [options.flush] - callback to invoke after receiving all chunks and prior to the stream closing
* @param {boolean} [options.objectMode] - specifies whether a stream should operate in object mode
* @param {(string|null)} [options.encoding] - specifies how `Buffer` objects should be decoded to `strings`
* @param {NonNegativeNumber} [options.highWaterMark] - specifies the `Buffer` level for when `write()` starts returning `false`
* @param {boolean} [options.allowHalfOpen] - specifies whether the stream should remain open even if one side ends
* @param {boolean} [options.decodeStrings] - specifies whether to decode `strings` into `Buffer` objects when writing
* @returns {(Error|null)} null or an error object
*/
function validate( opts, options ) {
if ( !isObject( options ) ) {
return new TypeError( 'invalid argument. Options must be an object. Value: `' + options + '`.' );
}
if ( hasOwnProp( options, 'transform' ) ) {
opts.transform = options.transform;
if ( !isFunction( opts.transform ) ) {
return new TypeError( 'invalid option. `transform` option must be a function. Option: `' + opts.transform + '`.' );
}
}
if ( hasOwnProp( options, 'flush' ) ) {
opts.flush = options.flush;
if ( !isFunction( opts.flush ) ) {
return new TypeError( 'invalid option. `flush` option must be a function. Option: `' + opts.flush + '`.' );
}
}
if ( hasOwnProp( options, 'objectMode' ) ) {
opts.objectMode = options.objectMode;
if ( !isBoolean( opts.objectMode ) ) {
return new TypeError( 'invalid option. `objectMode` option must be a primitive boolean. Option: `' + opts.objectMode + '`.' );
}
}
if ( hasOwnProp( options, 'encoding' ) ) {
opts.encoding = options.encoding;
if ( !isString( opts.encoding ) ) {
return new TypeError( 'invalid option. `encoding` option must be a primitive string. Option: `' + opts.encoding + '`.' );
}
}
if ( hasOwnProp( options, 'allowHalfOpen' ) ) {
opts.allowHalfOpen = options.allowHalfOpen;
if ( !isBoolean( opts.allowHalfOpen ) ) {
return new TypeError( 'invalid option. `allowHalfOpen` option must be a primitive boolean. Option: `' + opts.allowHalfOpen + '`.' );
}
}
if ( hasOwnProp( options, 'highWaterMark' ) ) {
opts.highWaterMark = options.highWaterMark;
if ( !isNonNegative( opts.highWaterMark ) ) {
return new TypeError( 'invalid option. `highWaterMark` option must be a nonnegative number. Option: `' + opts.highWaterMark + '`.' );
}
}
if ( hasOwnProp( options, 'decodeStrings' ) ) {
opts.decodeStrings = options.decodeStrings;
if ( !isBoolean( opts.decodeStrings ) ) {
return new TypeError( 'invalid option. `decodeStrings` option must be a primitive boolean. Option: `' + opts.decodeStrings + '`.' );
}
}
return null;
}
// EXPORTS //
module.exports = validate;
},{"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-boolean":81,"@stdlib/assert/is-function":102,"@stdlib/assert/is-nonnegative-number":131,"@stdlib/assert/is-plain-object":147,"@stdlib/assert/is-string":158}],324:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Create a string from a sequence of Unicode code points.
*
* @module @stdlib/string/from-code-point
*
* @example
* var fromCodePoint = require( '@stdlib/string/from-code-point' );
*
* var str = fromCodePoint( 9731 );
* // returns '☃'
*/
// MODULES //
var fromCodePoint = require( './main.js' );
// EXPORTS //
module.exports = fromCodePoint;
},{"./main.js":325}],325:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ).isPrimitive;
var isCollection = require( '@stdlib/assert/is-collection' );
var UNICODE_MAX = require( '@stdlib/constants/unicode/max' );
var UNICODE_MAX_BMP = require( '@stdlib/constants/unicode/max-bmp' );
// VARIABLES //
var fromCharCode = String.fromCharCode;
// Factor to rescale a code point from a supplementary plane:
var Ox10000 = 0x10000|0; // 65536
// Factor added to obtain a high surrogate:
var OxD800 = 0xD800|0; // 55296
// Factor added to obtain a low surrogate:
var OxDC00 = 0xDC00|0; // 56320
// 10-bit mask: 2^10-1 = 1023 => 0x3ff => 00000000 00000000 00000011 11111111
var Ox3FF = 1023|0;
// MAIN //
/**
* Creates a string from a sequence of Unicode code points.
*
* ## Notes
*
* - UTF-16 encoding uses one 16-bit unit for non-surrogates (U+0000 to U+D7FF and U+E000 to U+FFFF).
* - UTF-16 encoding uses two 16-bit units (surrogate pairs) for U+10000 to U+10FFFF and encodes U+10000-U+10FFFF by subtracting 0x10000 from the code point, expressing the result as a 20-bit binary, and splitting the 20 bits of 0x0-0xFFFFF as upper and lower 10-bits. The respective 10-bits are stored in two 16-bit words: a high and a low surrogate.
*
*
* @param {...NonNegativeInteger} args - sequence of code points
* @throws {Error} must provide either an array-like object of code points or one or more code points as separate arguments
* @throws {TypeError} a code point must be a nonnegative integer
* @throws {RangeError} must provide a valid Unicode code point
* @returns {string} created string
*
* @example
* var str = fromCodePoint( 9731 );
* // returns '☃'
*/
function fromCodePoint( args ) {
var len;
var str;
var arr;
var low;
var hi;
var pt;
var i;
len = arguments.length;
if ( len === 1 && isCollection( args ) ) {
arr = arguments[ 0 ];
len = arr.length;
} else {
arr = [];
for ( i = 0; i < len; i++ ) {
arr.push( arguments[ i ] );
}
}
if ( len === 0 ) {
throw new Error( 'insufficient input arguments. Must provide either an array of code points or one or more code points as separate arguments.' );
}
str = '';
for ( i = 0; i < len; i++ ) {
pt = arr[ i ];
if ( !isNonNegativeInteger( pt ) ) {
throw new TypeError( 'invalid argument. Must provide valid code points (nonnegative integers). Value: `'+pt+'`.' );
}
if ( pt > UNICODE_MAX ) {
throw new RangeError( 'invalid argument. Must provide a valid code point (cannot exceed max). Value: `'+pt+'`.' );
}
if ( pt <= UNICODE_MAX_BMP ) {
str += fromCharCode( pt );
} else {
// Code point from a supplementary plane. Split into two 16-bit code units (surrogate pair).
pt -= Ox10000;
hi = (pt >> 10) + OxD800;
low = (pt & Ox3FF) + OxDC00;
str += fromCharCode( hi, low );
}
}
return str;
}
// EXPORTS //
module.exports = fromCodePoint;
},{"@stdlib/assert/is-collection":90,"@stdlib/assert/is-nonnegative-integer":127,"@stdlib/constants/unicode/max":255,"@stdlib/constants/unicode/max-bmp":254}],326:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Replace search occurrences with a replacement string.
*
* @module @stdlib/string/replace
*
* @example
* var replace = require( '@stdlib/string/replace' );
*
* var str = 'beep';
* var out = replace( str, 'e', 'o' );
* // returns 'boop'
*
* str = 'Hello World';
* out = replace( str, /world/i, 'Mr. President' );
* // returns 'Hello Mr. President'
*/
// MODULES //
var replace = require( './replace.js' );
// EXPORTS //
module.exports = replace;
},{"./replace.js":327}],327:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var rescape = require( '@stdlib/utils/escape-regexp-string' );
var isFunction = require( '@stdlib/assert/is-function' );
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var isRegExp = require( '@stdlib/assert/is-regexp' );
// MAIN //
/**
* Replace search occurrences with a replacement string.
*
* @param {string} str - input string
* @param {(string|RegExp)} search - search expression
* @param {(string|Function)} newval - replacement value or function
* @throws {TypeError} first argument must be a string primitive
* @throws {TypeError} second argument argument must be a string primitive or regular expression
* @throws {TypeError} third argument must be a string primitive or function
* @returns {string} new string containing replacement(s)
*
* @example
* var str = 'beep';
* var out = replace( str, 'e', 'o' );
* // returns 'boop'
*
* @example
* var str = 'Hello World';
* var out = replace( str, /world/i, 'Mr. President' );
* // returns 'Hello Mr. President'
*
* @example
* var capitalize = require( '@stdlib/string/capitalize' );
*
* var str = 'Oranges and lemons say the bells of St. Clement\'s';
*
* function replacer( match, p1 ) {
* return capitalize( p1 );
* }
*
* var out = replace( str, /([^\s]*)/gi, replacer);
* // returns 'Oranges And Lemons Say The Bells Of St. Clement\'s'
*/
function replace( str, search, newval ) {
if ( !isString( str ) ) {
throw new TypeError( 'invalid argument. First argument must be a string primitive. Value: `' + str + '`.' );
}
if ( isString( search ) ) {
search = rescape( search );
search = new RegExp( search, 'g' );
}
else if ( !isRegExp( search ) ) {
throw new TypeError( 'invalid argument. Second argument must be a string primitive or regular expression. Value: `' + search + '`.' );
}
if ( !isString( newval ) && !isFunction( newval ) ) {
throw new TypeError( 'invalid argument. Third argument must be a string primitive or replacement function. Value: `' + newval + '`.' );
}
return str.replace( search, newval );
}
// EXPORTS //
module.exports = replace;
},{"@stdlib/assert/is-function":102,"@stdlib/assert/is-regexp":154,"@stdlib/assert/is-string":158,"@stdlib/utils/escape-regexp-string":353}],328:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Trim whitespace characters from the beginning and end of a string.
*
* @module @stdlib/string/trim
*
* @example
* var trim = require( '@stdlib/string/trim' );
*
* var out = trim( ' Whitespace ' );
* // returns 'Whitespace'
*
* out = trim( '\t\t\tTabs\t\t\t' );
* // returns 'Tabs'
*
* out = trim( '\n\n\nNew Lines\n\n\n' );
* // returns 'New Lines'
*/
// MODULES //
var trim = require( './trim.js' );
// EXPORTS //
module.exports = trim;
},{"./trim.js":329}],329:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var replace = require( '@stdlib/string/replace' );
// VARIABLES //
// The following regular expression should suffice to polyfill (most?) all environments.
var RE = /^[\u0020\f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]*([\S\s]*?)[\u0020\f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]*$/;
// MAIN //
/**
* Trim whitespace characters from beginning and end of a string.
*
* @param {string} str - input string
* @throws {TypeError} must provide a string primitive
* @returns {string} trimmed string
*
* @example
* var out = trim( ' Whitespace ' );
* // returns 'Whitespace'
*
* @example
* var out = trim( '\t\t\tTabs\t\t\t' );
* // returns 'Tabs'
*
* @example
* var out = trim( '\n\n\nNew Lines\n\n\n' );
* // returns 'New Lines'
*/
function trim( str ) {
if ( !isString( str ) ) {
throw new TypeError( 'invalid argument. Must provide a string primitive. Value: `' + str + '`.' );
}
return replace( str, RE, '$1' );
}
// EXPORTS //
module.exports = trim;
},{"@stdlib/assert/is-string":158,"@stdlib/string/replace":326}],330:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var getGlobal = require( '@stdlib/utils/global' );
var isObject = require( '@stdlib/assert/is-object' );
var modf = require( '@stdlib/math/base/special/modf' );
var round = require( '@stdlib/math/base/special/round' );
var now = require( './now.js' );
// VARIABLES //
var Global = getGlobal();
var ts;
var ns;
if ( isObject( Global.performance ) ) {
ns = Global.performance;
} else {
ns = {};
}
if ( ns.now ) {
ts = ns.now.bind( ns );
} else if ( ns.mozNow ) {
ts = ns.mozNow.bind( ns );
} else if ( ns.msNow ) {
ts = ns.msNow.bind( ns );
} else if ( ns.oNow ) {
ts = ns.oNow.bind( ns );
} else if ( ns.webkitNow ) {
ts = ns.webkitNow.bind( ns );
} else {
ts = now;
}
// MAIN //
/**
* Returns a high-resolution time.
*
* ## Notes
*
* - Output format: `[seconds, nanoseconds]`.
*
*
* @private
* @returns {NumberArray} high-resolution time
*
* @example
* var t = tic();
* // returns [<number>,<number>]
*/
function tic() {
var parts;
var t;
// Get a millisecond timestamp and convert to seconds:
t = ts() / 1000;
// Decompose the timestamp into integer (seconds) and fractional parts:
parts = modf( t );
// Convert the fractional part to nanoseconds:
parts[ 1 ] = round( parts[1] * 1.0e9 );
// Return the high-resolution time:
return parts;
}
// EXPORTS //
module.exports = tic;
},{"./now.js":332,"@stdlib/assert/is-object":145,"@stdlib/math/base/special/modf":266,"@stdlib/math/base/special/round":269,"@stdlib/utils/global":365}],331:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isFunction = require( '@stdlib/assert/is-function' );
// MAIN //
var bool = isFunction( Date.now );
// EXPORTS //
module.exports = bool;
},{"@stdlib/assert/is-function":102}],332:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var bool = require( './detect.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var now;
if ( bool ) {
now = Date.now;
} else {
now = polyfill;
}
// EXPORTS //
module.exports = now;
},{"./detect.js":331,"./polyfill.js":333}],333:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Returns the time in milliseconds since the epoch.
*
* @private
* @returns {number} time
*
* @example
* var ts = now();
* // returns <number>
*/
function now() {
var d = new Date();
return d.getTime();
}
// EXPORTS //
module.exports = now;
},{}],334:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Return a high-resolution time difference.
*
* @module @stdlib/time/toc
*
* @example
* var tic = require( '@stdlib/time/tic' );
* var toc = require( '@stdlib/time/toc' );
*
* var start = tic();
* var delta = toc( start );
* // returns [<number>,<number>]
*/
// MODULES //
var toc = require( './toc.js' );
// EXPORTS //
module.exports = toc;
},{"./toc.js":335}],335:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isNonNegativeIntegerArray = require( '@stdlib/assert/is-nonnegative-integer-array' ).primitives;
var tic = require( '@stdlib/time/tic' );
// MAIN //
/**
* Returns a high-resolution time difference.
*
* ## Notes
*
* - Output format: `[seconds, nanoseconds]`.
*
*
* @param {NonNegativeIntegerArray} time - high-resolution time
* @throws {TypeError} must provide a nonnegative integer array
* @throws {RangeError} input array must have length `2`
* @returns {NumberArray} high resolution time difference
*
* @example
* var tic = require( '@stdlib/time/tic' );
*
* var start = tic();
* var delta = toc( start );
* // returns [<number>,<number>]
*/
function toc( time ) {
var now = tic();
var sec;
var ns;
if ( !isNonNegativeIntegerArray( time ) ) {
throw new TypeError( 'invalid argument. Must provide an array of nonnegative integers. Value: `' + time + '`.' );
}
if ( time.length !== 2 ) {
throw new RangeError( 'invalid argument. Input array must have length `2`.' );
}
sec = now[ 0 ] - time[ 0 ];
ns = now[ 1 ] - time[ 1 ];
if ( sec > 0 && ns < 0 ) {
sec -= 1;
ns += 1e9;
}
else if ( sec < 0 && ns > 0 ) {
sec += 1;
ns -= 1e9;
}
return [ sec, ns ];
}
// EXPORTS //
module.exports = toc;
},{"@stdlib/assert/is-nonnegative-integer-array":126,"@stdlib/time/tic":330}],336:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Determine the name of a value's constructor.
*
* @module @stdlib/utils/constructor-name
*
* @example
* var constructorName = require( '@stdlib/utils/constructor-name' );
*
* var v = constructorName( 'a' );
* // returns 'String'
*
* v = constructorName( {} );
* // returns 'Object'
*
* v = constructorName( true );
* // returns 'Boolean'
*/
// MODULES //
var constructorName = require( './main.js' );
// EXPORTS //
module.exports = constructorName;
},{"./main.js":337}],337:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var nativeClass = require( '@stdlib/utils/native-class' );
var RE = require( '@stdlib/regexp/function-name' ).REGEXP;
var isBuffer = require( '@stdlib/assert/is-buffer' );
// MAIN //
/**
* Determines the name of a value's constructor.
*
* @param {*} v - input value
* @returns {string} name of a value's constructor
*
* @example
* var v = constructorName( 'a' );
* // returns 'String'
*
* @example
* var v = constructorName( 5 );
* // returns 'Number'
*
* @example
* var v = constructorName( null );
* // returns 'Null'
*
* @example
* var v = constructorName( undefined );
* // returns 'Undefined'
*
* @example
* var v = constructorName( function noop() {} );
* // returns 'Function'
*/
function constructorName( v ) {
var match;
var name;
var ctor;
name = nativeClass( v ).slice( 8, -1 );
if ( (name === 'Object' || name === 'Error') && v.constructor ) {
ctor = v.constructor;
if ( typeof ctor.name === 'string' ) {
return ctor.name;
}
match = RE.exec( ctor.toString() );
if ( match ) {
return match[ 1 ];
}
}
if ( isBuffer( v ) ) {
return 'Buffer';
}
return name;
}
// EXPORTS //
module.exports = constructorName;
},{"@stdlib/assert/is-buffer":88,"@stdlib/regexp/function-name":305,"@stdlib/utils/native-class":393}],338:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isArray = require( '@stdlib/assert/is-array' );
var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ).isPrimitive;
var PINF = require( '@stdlib/constants/float64/pinf' );
var deepCopy = require( './deep_copy.js' );
// MAIN //
/**
* Copies or deep clones a value to an arbitrary depth.
*
* @param {*} value - value to copy
* @param {NonNegativeInteger} [level=+infinity] - copy depth
* @throws {TypeError} `level` must be a nonnegative integer
* @returns {*} value copy
*
* @example
* var out = copy( 'beep' );
* // returns 'beep'
*
* @example
* var value = [
* {
* 'a': 1,
* 'b': true,
* 'c': [ 1, 2, 3 ]
* }
* ];
* var out = copy( value );
* // returns [ { 'a': 1, 'b': true, 'c': [ 1, 2, 3 ] } ]
*
* var bool = ( value[0].c === out[0].c );
* // returns false
*/
function copy( value, level ) {
var out;
if ( arguments.length > 1 ) {
if ( !isNonNegativeInteger( level ) ) {
throw new TypeError( 'invalid argument. `level` must be a nonnegative integer. Value: `' + level + '`.' );
}
if ( level === 0 ) {
return value;
}
} else {
level = PINF;
}
out = ( isArray( value ) ) ? new Array( value.length ) : {};
return deepCopy( value, out, [value], [out], level );
}
// EXPORTS //
module.exports = copy;
},{"./deep_copy.js":339,"@stdlib/assert/is-array":79,"@stdlib/assert/is-nonnegative-integer":127,"@stdlib/constants/float64/pinf":244}],339:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var isArray = require( '@stdlib/assert/is-array' );
var isBuffer = require( '@stdlib/assert/is-buffer' );
var isError = require( '@stdlib/assert/is-error' );
var typeOf = require( '@stdlib/utils/type-of' );
var regexp = require( '@stdlib/utils/regexp-from-string' );
var indexOf = require( '@stdlib/utils/index-of' );
var objectKeys = require( '@stdlib/utils/keys' );
var propertyNames = require( '@stdlib/utils/property-names' );
var propertyDescriptor = require( '@stdlib/utils/property-descriptor' );
var getPrototypeOf = require( '@stdlib/utils/get-prototype-of' );
var defineProperty = require( '@stdlib/utils/define-property' );
var copyBuffer = require( '@stdlib/buffer/from-buffer' );
var typedArrays = require( './typed_arrays.js' );
// FUNCTIONS //
/**
* Clones a class instance.
*
* ## Notes
*
* - This should **only** be used for simple cases. Any instances with privileged access to variables (e.g., within closures) cannot be cloned. This approach should be considered **fragile**.
* - The function is greedy, disregarding the notion of a `level`. Instead, the function deep copies all properties, as we assume the concept of `level` applies only to the class instance reference but not to its internal state. This prevents, in theory, two instances from sharing state.
*
*
* @private
* @param {Object} val - class instance
* @returns {Object} new instance
*/
function cloneInstance( val ) {
var cache;
var names;
var name;
var refs;
var desc;
var tmp;
var ref;
var i;
cache = [];
refs = [];
ref = Object.create( getPrototypeOf( val ) );
cache.push( val );
refs.push( ref );
names = propertyNames( val );
for ( i = 0; i < names.length; i++ ) {
name = names[ i ];
desc = propertyDescriptor( val, name );
if ( hasOwnProp( desc, 'value' ) ) {
tmp = ( isArray( val[name] ) ) ? [] : {};
desc.value = deepCopy( val[name], tmp, cache, refs, -1 );
}
defineProperty( ref, name, desc );
}
if ( !Object.isExtensible( val ) ) {
Object.preventExtensions( ref );
}
if ( Object.isSealed( val ) ) {
Object.seal( ref );
}
if ( Object.isFrozen( val ) ) {
Object.freeze( ref );
}
return ref;
}
/**
* Copies an error object.
*
* @private
* @param {(Error|TypeError|SyntaxError|URIError|ReferenceError|RangeError|EvalError)} error - error to copy
* @returns {(Error|TypeError|SyntaxError|URIError|ReferenceError|RangeError|EvalError)} error copy
*
* @example
* var err1 = new TypeError( 'beep' );
*
* var err2 = copyError( err1 );
* // returns <TypeError>
*/
function copyError( error ) {
var cache = [];
var refs = [];
var keys;
var desc;
var tmp;
var key;
var err;
var i;
// Create a new error...
err = new error.constructor( error.message );
cache.push( error );
refs.push( err );
// If a `stack` property is present, copy it over...
if ( error.stack ) {
err.stack = error.stack;
}
// Node.js specific (system errors)...
if ( error.code ) {
err.code = error.code;
}
if ( error.errno ) {
err.errno = error.errno;
}
if ( error.syscall ) {
err.syscall = error.syscall;
}
// Any enumerable properties...
keys = objectKeys( error );
for ( i = 0; i < keys.length; i++ ) {
key = keys[ i ];
desc = propertyDescriptor( error, key );
if ( hasOwnProp( desc, 'value' ) ) {
tmp = ( isArray( error[ key ] ) ) ? [] : {};
desc.value = deepCopy( error[ key ], tmp, cache, refs, -1 );
}
defineProperty( err, key, desc );
}
return err;
}
// MAIN //
/**
* Recursively performs a deep copy of an input object.
*
* @private
* @param {*} val - value to copy
* @param {(Array|Object)} copy - copy
* @param {Array} cache - an array of visited objects
* @param {Array} refs - an array of object references
* @param {NonNegativeInteger} level - copy depth
* @returns {*} deep copy
*/
function deepCopy( val, copy, cache, refs, level ) {
var parent;
var keys;
var name;
var desc;
var ctor;
var key;
var ref;
var x;
var i;
var j;
level -= 1;
// Primitives and functions...
if (
typeof val !== 'object' ||
val === null
) {
return val;
}
if ( isBuffer( val ) ) {
return copyBuffer( val );
}
if ( isError( val ) ) {
return copyError( val );
}
// Objects...
name = typeOf( val );
if ( name === 'date' ) {
return new Date( +val );
}
if ( name === 'regexp' ) {
return regexp( val.toString() );
}
if ( name === 'set' ) {
return new Set( val );
}
if ( name === 'map' ) {
return new Map( val );
}
if (
name === 'string' ||
name === 'boolean' ||
name === 'number'
) {
// If provided an `Object`, return an equivalent primitive!
return val.valueOf();
}
ctor = typedArrays[ name ];
if ( ctor ) {
return ctor( val );
}
// Class instances...
if (
name !== 'array' &&
name !== 'object'
) {
// Cloning requires ES5 or higher...
if ( typeof Object.freeze === 'function' ) {
return cloneInstance( val );
}
return {};
}
// Arrays and plain objects...
keys = objectKeys( val );
if ( level > 0 ) {
parent = name;
for ( j = 0; j < keys.length; j++ ) {
key = keys[ j ];
x = val[ key ];
// Primitive, Buffer, special class instance...
name = typeOf( x );
if (
typeof x !== 'object' ||
x === null ||
(
name !== 'array' &&
name !== 'object'
) ||
isBuffer( x )
) {
if ( parent === 'object' ) {
desc = propertyDescriptor( val, key );
if ( hasOwnProp( desc, 'value' ) ) {
desc.value = deepCopy( x );
}
defineProperty( copy, key, desc );
} else {
copy[ key ] = deepCopy( x );
}
continue;
}
// Circular reference...
i = indexOf( cache, x );
if ( i !== -1 ) {
copy[ key ] = refs[ i ];
continue;
}
// Plain array or object...
ref = ( isArray( x ) ) ? new Array( x.length ) : {};
cache.push( x );
refs.push( ref );
if ( parent === 'array' ) {
copy[ key ] = deepCopy( x, ref, cache, refs, level );
} else {
desc = propertyDescriptor( val, key );
if ( hasOwnProp( desc, 'value' ) ) {
desc.value = deepCopy( x, ref, cache, refs, level );
}
defineProperty( copy, key, desc );
}
}
} else if ( name === 'array' ) {
for ( j = 0; j < keys.length; j++ ) {
key = keys[ j ];
copy[ key ] = val[ key ];
}
} else {
for ( j = 0; j < keys.length; j++ ) {
key = keys[ j ];
desc = propertyDescriptor( val, key );
defineProperty( copy, key, desc );
}
}
if ( !Object.isExtensible( val ) ) {
Object.preventExtensions( copy );
}
if ( Object.isSealed( val ) ) {
Object.seal( copy );
}
if ( Object.isFrozen( val ) ) {
Object.freeze( copy );
}
return copy;
}
// EXPORTS //
module.exports = deepCopy;
},{"./typed_arrays.js":341,"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-array":79,"@stdlib/assert/is-buffer":88,"@stdlib/assert/is-error":96,"@stdlib/buffer/from-buffer":232,"@stdlib/utils/define-property":351,"@stdlib/utils/get-prototype-of":359,"@stdlib/utils/index-of":369,"@stdlib/utils/keys":386,"@stdlib/utils/property-descriptor":408,"@stdlib/utils/property-names":412,"@stdlib/utils/regexp-from-string":415,"@stdlib/utils/type-of":420}],340:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Copy or deep clone a value to an arbitrary depth.
*
* @module @stdlib/utils/copy
*
* @example
* var copy = require( '@stdlib/utils/copy' );
*
* var out = copy( 'beep' );
* // returns 'beep'
*
* @example
* var copy = require( '@stdlib/utils/copy' );
*
* var value = [
* {
* 'a': 1,
* 'b': true,
* 'c': [ 1, 2, 3 ]
* }
* ];
* var out = copy( value );
* // returns [ {'a': 1, 'b': true, 'c': [ 1, 2, 3 ] } ]
*
* var bool = ( value[0].c === out[0].c );
* // returns false
*/
// MODULES //
var copy = require( './copy.js' );
// EXPORTS //
module.exports = copy;
},{"./copy.js":338}],341:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var Int8Array = require( '@stdlib/array/int8' );
var Uint8Array = require( '@stdlib/array/uint8' );
var Uint8ClampedArray = require( '@stdlib/array/uint8c' );
var Int16Array = require( '@stdlib/array/int16' );
var Uint16Array = require( '@stdlib/array/uint16' );
var Int32Array = require( '@stdlib/array/int32' );
var Uint32Array = require( '@stdlib/array/uint32' );
var Float32Array = require( '@stdlib/array/float32' );
var Float64Array = require( '@stdlib/array/float64' );
// VARIABLES //
var hash;
// FUNCTIONS //
/**
* Copies an `Int8Array`.
*
* @private
* @param {Int8Array} arr - array to copy
* @returns {Int8Array} new array
*/
function int8array( arr ) {
return new Int8Array( arr );
}
/**
* Copies a `Uint8Array`.
*
* @private
* @param {Uint8Array} arr - array to copy
* @returns {Uint8Array} new array
*/
function uint8array( arr ) {
return new Uint8Array( arr );
}
/**
* Copies a `Uint8ClampedArray`.
*
* @private
* @param {Uint8ClampedArray} arr - array to copy
* @returns {Uint8ClampedArray} new array
*/
function uint8clampedarray( arr ) {
return new Uint8ClampedArray( arr );
}
/**
* Copies an `Int16Array`.
*
* @private
* @param {Int16Array} arr - array to copy
* @returns {Int16Array} new array
*/
function int16array( arr ) {
return new Int16Array( arr );
}
/**
* Copies a `Uint16Array`.
*
* @private
* @param {Uint16Array} arr - array to copy
* @returns {Uint16Array} new array
*/
function uint16array( arr ) {
return new Uint16Array( arr );
}
/**
* Copies an `Int32Array`.
*
* @private
* @param {Int32Array} arr - array to copy
* @returns {Int32Array} new array
*/
function int32array( arr ) {
return new Int32Array( arr );
}
/**
* Copies a `Uint32Array`.
*
* @private
* @param {Uint32Array} arr - array to copy
* @returns {Uint32Array} new array
*/
function uint32array( arr ) {
return new Uint32Array( arr );
}
/**
* Copies a `Float32Array`.
*
* @private
* @param {Float32Array} arr - array to copy
* @returns {Float32Array} new array
*/
function float32array( arr ) {
return new Float32Array( arr );
}
/**
* Copies a `Float64Array`.
*
* @private
* @param {Float64Array} arr - array to copy
* @returns {Float64Array} new array
*/
function float64array( arr ) {
return new Float64Array( arr );
}
/**
* Returns a hash of functions for copying typed arrays.
*
* @private
* @returns {Object} function hash
*/
function typedarrays() {
var out = {
'int8array': int8array,
'uint8array': uint8array,
'uint8clampedarray': uint8clampedarray,
'int16array': int16array,
'uint16array': uint16array,
'int32array': int32array,
'uint32array': uint32array,
'float32array': float32array,
'float64array': float64array
};
return out;
}
// MAIN //
hash = typedarrays();
// EXPORTS //
module.exports = hash;
},{"@stdlib/array/float32":2,"@stdlib/array/float64":5,"@stdlib/array/int16":7,"@stdlib/array/int32":10,"@stdlib/array/int8":13,"@stdlib/array/uint16":20,"@stdlib/array/uint32":23,"@stdlib/array/uint8":26,"@stdlib/array/uint8c":29}],342:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Define a non-enumerable read-only accessor.
*
* @module @stdlib/utils/define-nonenumerable-read-only-accessor
*
* @example
* var setNonEnumerableReadOnlyAccessor = require( '@stdlib/utils/define-nonenumerable-read-only-accessor' );
*
* function getter() {
* return 'bar';
* }
*
* var obj = {};
*
* setNonEnumerableReadOnlyAccessor( obj, 'foo', getter );
*
* try {
* obj.foo = 'boop';
* } catch ( err ) {
* console.error( err.message );
* }
*/
// MODULES //
var setNonEnumerableReadOnlyAccessor = require( './main.js' ); // eslint-disable-line id-length
// EXPORTS //
module.exports = setNonEnumerableReadOnlyAccessor;
},{"./main.js":343}],343:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var defineProperty = require( '@stdlib/utils/define-property' );
// MAIN //
/**
* Defines a non-enumerable read-only accessor.
*
* @param {Object} obj - object on which to define the property
* @param {(string|symbol)} prop - property name
* @param {Function} getter - accessor
*
* @example
* function getter() {
* return 'bar';
* }
*
* var obj = {};
*
* setNonEnumerableReadOnlyAccessor( obj, 'foo', getter );
*
* try {
* obj.foo = 'boop';
* } catch ( err ) {
* console.error( err.message );
* }
*/
function setNonEnumerableReadOnlyAccessor( obj, prop, getter ) { // eslint-disable-line id-length
defineProperty( obj, prop, {
'configurable': false,
'enumerable': false,
'get': getter
});
}
// EXPORTS //
module.exports = setNonEnumerableReadOnlyAccessor;
},{"@stdlib/utils/define-property":351}],344:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Define a non-enumerable read-only property.
*
* @module @stdlib/utils/define-nonenumerable-read-only-property
*
* @example
* var setNonEnumerableReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
*
* var obj = {};
*
* setNonEnumerableReadOnly( obj, 'foo', 'bar' );
*
* try {
* obj.foo = 'boop';
* } catch ( err ) {
* console.error( err.message );
* }
*/
// MODULES //
var setNonEnumerableReadOnly = require( './main.js' );
// EXPORTS //
module.exports = setNonEnumerableReadOnly;
},{"./main.js":345}],345:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var defineProperty = require( '@stdlib/utils/define-property' );
// MAIN //
/**
* Defines a non-enumerable read-only property.
*
* @param {Object} obj - object on which to define the property
* @param {(string|symbol)} prop - property name
* @param {*} value - value to set
*
* @example
* var obj = {};
*
* setNonEnumerableReadOnly( obj, 'foo', 'bar' );
*
* try {
* obj.foo = 'boop';
* } catch ( err ) {
* console.error( err.message );
* }
*/
function setNonEnumerableReadOnly( obj, prop, value ) {
defineProperty( obj, prop, {
'configurable': false,
'enumerable': false,
'writable': false,
'value': value
});
}
// EXPORTS //
module.exports = setNonEnumerableReadOnly;
},{"@stdlib/utils/define-property":351}],346:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Define a non-enumerable read-write accessor.
*
* @module @stdlib/utils/define-nonenumerable-read-write-accessor
*
* @example
* var setNonEnumerableReadWriteAccessor = require( '@stdlib/utils/define-nonenumerable-read-write-accessor' );
*
* function getter() {
* return name + ' foo';
* }
*
* function setter( v ) {
* name = v;
* }
*
* var name = 'bar';
* var obj = {};
*
* setNonEnumerableReadWriteAccessor( obj, 'foo', getter, setter );
*
* var v = obj.foo;
* // returns 'bar foo'
*
* obj.foo = 'beep';
*
* v = obj.foo;
* // returns 'beep foo'
*/
// MODULES //
var setNonEnumerableReadWriteAccessor = require( './main.js' );
// EXPORTS //
module.exports = setNonEnumerableReadWriteAccessor;
},{"./main.js":347}],347:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var defineProperty = require( '@stdlib/utils/define-property' );
// MAIN //
/**
* Defines a non-enumerable read-write accessor.
*
* @param {Object} obj - object on which to define the property
* @param {(string|symbol)} prop - property name
* @param {Function} getter - get accessor
* @param {Function} setter - set accessor
*
* @example
* function getter() {
* return name + ' foo';
* }
*
* function setter( v ) {
* name = v;
* }
*
* var name = 'bar';
* var obj = {};
*
* setNonEnumerableReadWriteAccessor( obj, 'foo', getter, setter );
*
* var v = obj.foo;
* // returns 'bar foo'
*
* obj.foo = 'beep';
*
* v = obj.foo;
* // returns 'beep foo'
*/
function setNonEnumerableReadWriteAccessor( obj, prop, getter, setter ) { // eslint-disable-line id-length
defineProperty( obj, prop, {
'configurable': false,
'enumerable': false,
'get': getter,
'set': setter
});
}
// EXPORTS //
module.exports = setNonEnumerableReadWriteAccessor;
},{"@stdlib/utils/define-property":351}],348:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Defines (or modifies) an object property.
*
* ## Notes
*
* - Property descriptors come in two flavors: **data descriptors** and **accessor descriptors**. A data descriptor is a property that has a value, which may or may not be writable. An accessor descriptor is a property described by a getter-setter function pair. A descriptor must be one of these two flavors and cannot be both.
*
* @name defineProperty
* @type {Function}
* @param {Object} obj - object on which to define the property
* @param {(string|symbol)} prop - property name
* @param {Object} descriptor - property descriptor
* @param {boolean} [descriptor.configurable=false] - boolean indicating if property descriptor can be changed and if the property can be deleted from the provided object
* @param {boolean} [descriptor.enumerable=false] - boolean indicating if the property shows up when enumerating object properties
* @param {boolean} [descriptor.writable=false] - boolean indicating if the value associated with the property can be changed with an assignment operator
* @param {*} [descriptor.value] - property value
* @param {(Function|void)} [descriptor.get=undefined] - function which serves as a getter for the property, or, if no getter, undefined. When the property is accessed, a getter function is called without arguments and with the `this` context set to the object through which the property is accessed (which may not be the object on which the property is defined due to inheritance). The return value will be used as the property value.
* @param {(Function|void)} [descriptor.set=undefined] - function which serves as a setter for the property, or, if no setter, undefined. When assigning a property value, a setter function is called with one argument (the value being assigned to the property) and with the `this` context set to the object through which the property is assigned.
* @throws {TypeError} first argument must be an object
* @throws {TypeError} third argument must be an object
* @throws {Error} property descriptor cannot have both a value and a setter and/or getter
* @returns {Object} object with added property
*
* @example
* var obj = {};
*
* defineProperty( obj, 'foo', {
* 'value': 'bar'
* });
*
* var str = obj.foo;
* // returns 'bar'
*/
var defineProperty = Object.defineProperty;
// EXPORTS //
module.exports = defineProperty;
},{}],349:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var main = ( typeof Object.defineProperty === 'function' ) ? Object.defineProperty : null;
// EXPORTS //
module.exports = main;
},{}],350:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var defineProperty = require( './define_property.js' );
// MAIN //
/**
* Tests for `Object.defineProperty` support.
*
* @private
* @returns {boolean} boolean indicating if an environment has `Object.defineProperty` support
*
* @example
* var bool = hasDefinePropertySupport();
* // returns <boolean>
*/
function hasDefinePropertySupport() {
// Test basic support...
try {
defineProperty( {}, 'x', {} );
return true;
} catch ( err ) { // eslint-disable-line no-unused-vars
return false;
}
}
// EXPORTS //
module.exports = hasDefinePropertySupport;
},{"./define_property.js":349}],351:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Define (or modify) an object property.
*
* @module @stdlib/utils/define-property
*
* @example
* var defineProperty = require( '@stdlib/utils/define-property' );
*
* var obj = {};
* defineProperty( obj, 'foo', {
* 'value': 'bar',
* 'writable': false,
* 'configurable': false,
* 'enumerable': false
* });
* obj.foo = 'boop'; // => throws
*/
// MODULES //
var hasDefinePropertySupport = require( './has_define_property_support.js' );
var builtin = require( './builtin.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var defineProperty;
if ( hasDefinePropertySupport() ) {
defineProperty = builtin;
} else {
defineProperty = polyfill;
}
// EXPORTS //
module.exports = defineProperty;
},{"./builtin.js":348,"./has_define_property_support.js":350,"./polyfill.js":352}],352:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
/* eslint-disable no-underscore-dangle, no-proto */
'use strict';
// VARIABLES //
var objectProtoype = Object.prototype;
var toStr = objectProtoype.toString;
var defineGetter = objectProtoype.__defineGetter__;
var defineSetter = objectProtoype.__defineSetter__;
var lookupGetter = objectProtoype.__lookupGetter__;
var lookupSetter = objectProtoype.__lookupSetter__;
// MAIN //
/**
* Defines (or modifies) an object property.
*
* ## Notes
*
* - Property descriptors come in two flavors: **data descriptors** and **accessor descriptors**. A data descriptor is a property that has a value, which may or may not be writable. An accessor descriptor is a property described by a getter-setter function pair. A descriptor must be one of these two flavors and cannot be both.
*
* @param {Object} obj - object on which to define the property
* @param {string} prop - property name
* @param {Object} descriptor - property descriptor
* @param {boolean} [descriptor.configurable=false] - boolean indicating if property descriptor can be changed and if the property can be deleted from the provided object
* @param {boolean} [descriptor.enumerable=false] - boolean indicating if the property shows up when enumerating object properties
* @param {boolean} [descriptor.writable=false] - boolean indicating if the value associated with the property can be changed with an assignment operator
* @param {*} [descriptor.value] - property value
* @param {(Function|void)} [descriptor.get=undefined] - function which serves as a getter for the property, or, if no getter, undefined. When the property is accessed, a getter function is called without arguments and with the `this` context set to the object through which the property is accessed (which may not be the object on which the property is defined due to inheritance). The return value will be used as the property value.
* @param {(Function|void)} [descriptor.set=undefined] - function which serves as a setter for the property, or, if no setter, undefined. When assigning a property value, a setter function is called with one argument (the value being assigned to the property) and with the `this` context set to the object through which the property is assigned.
* @throws {TypeError} first argument must be an object
* @throws {TypeError} third argument must be an object
* @throws {Error} property descriptor cannot have both a value and a setter and/or getter
* @returns {Object} object with added property
*
* @example
* var obj = {};
*
* defineProperty( obj, 'foo', {
* 'value': 'bar'
* });
*
* var str = obj.foo;
* // returns 'bar'
*/
function defineProperty( obj, prop, descriptor ) {
var prototype;
var hasValue;
var hasGet;
var hasSet;
if ( typeof obj !== 'object' || obj === null || toStr.call( obj ) === '[object Array]' ) {
throw new TypeError( 'invalid argument. First argument must be an object. Value: `' + obj + '`.' );
}
if ( typeof descriptor !== 'object' || descriptor === null || toStr.call( descriptor ) === '[object Array]' ) {
throw new TypeError( 'invalid argument. Property descriptor must be an object. Value: `' + descriptor + '`.' );
}
hasValue = ( 'value' in descriptor );
if ( hasValue ) {
if (
lookupGetter.call( obj, prop ) ||
lookupSetter.call( obj, prop )
) {
// Override `__proto__` to avoid touching inherited accessors:
prototype = obj.__proto__;
obj.__proto__ = objectProtoype;
// Delete property as existing getters/setters prevent assigning value to specified property:
delete obj[ prop ];
obj[ prop ] = descriptor.value;
// Restore original prototype:
obj.__proto__ = prototype;
} else {
obj[ prop ] = descriptor.value;
}
}
hasGet = ( 'get' in descriptor );
hasSet = ( 'set' in descriptor );
if ( hasValue && ( hasGet || hasSet ) ) {
throw new Error( 'invalid argument. Cannot specify one or more accessors and a value or writable attribute in the property descriptor.' );
}
if ( hasGet && defineGetter ) {
defineGetter.call( obj, prop, descriptor.get );
}
if ( hasSet && defineSetter ) {
defineSetter.call( obj, prop, descriptor.set );
}
return obj;
}
// EXPORTS //
module.exports = defineProperty;
},{}],353:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Escape a regular expression string or pattern.
*
* @module @stdlib/utils/escape-regexp-string
*
* @example
* var rescape = require( '@stdlib/utils/escape-regexp-string' );
*
* var str = rescape( '[A-Z]*' );
* // returns '\\[A\\-Z\\]\\*'
*/
// MODULES //
var rescape = require( './main.js' );
// EXPORTS //
module.exports = rescape;
},{"./main.js":354}],354:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
// VARIABLES //
var RE_CHARS = /[-\/\\^$*+?.()|[\]{}]/g; // eslint-disable-line no-useless-escape
// MAIN //
/**
* Escapes a regular expression string.
*
* @param {string} str - regular expression string
* @throws {TypeError} first argument must be a string primitive
* @returns {string} escaped string
*
* @example
* var str = rescape( '[A-Z]*' );
* // returns '\\[A\\-Z\\]\\*'
*/
function rescape( str ) {
var len;
var s;
var i;
if ( !isString( str ) ) {
throw new TypeError( 'invalid argument. Must provide a regular expression string. Value: `' + str + '`.' );
}
// Check if the string starts with a forward slash...
if ( str[ 0 ] === '/' ) {
// Find the last forward slash...
len = str.length;
for ( i = len-1; i >= 0; i-- ) {
if ( str[ i ] === '/' ) {
break;
}
}
}
// If we searched the string to no avail or if the first letter is not `/`, assume that the string is not of the form `/[...]/[guimy]`:
if ( i === void 0 || i <= 0 ) {
return str.replace( RE_CHARS, '\\$&' );
}
// We need to de-construct the string...
s = str.substring( 1, i );
// Only escape the characters between the `/`:
s = s.replace( RE_CHARS, '\\$&' );
// Reassemble:
str = str[ 0 ] + s + str.substring( i );
return str;
}
// EXPORTS //
module.exports = rescape;
},{"@stdlib/assert/is-string":158}],355:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isFunction = require( '@stdlib/assert/is-function' );
var hasFunctionNameSupport = require( '@stdlib/assert/has-function-name-support' );
var RE = require( '@stdlib/regexp/function-name' ).REGEXP;
// VARIABLES //
var isFunctionNameSupported = hasFunctionNameSupport();
// MAIN //
/**
* Returns the name of a function.
*
* @param {Function} fcn - input function
* @throws {TypeError} must provide a function
* @returns {string} function name
*
* @example
* var v = functionName( Math.sqrt );
* // returns 'sqrt'
*
* @example
* var v = functionName( function foo(){} );
* // returns 'foo'
*
* @example
* var v = functionName( function(){} );
* // returns '' || 'anonymous'
*
* @example
* var v = functionName( String );
* // returns 'String'
*/
function functionName( fcn ) {
// TODO: add support for generator functions?
if ( isFunction( fcn ) === false ) {
throw new TypeError( 'invalid argument. Must provide a function. Value: `' + fcn + '`.' );
}
if ( isFunctionNameSupported ) {
return fcn.name;
}
return RE.exec( fcn.toString() )[ 1 ];
}
// EXPORTS //
module.exports = functionName;
},{"@stdlib/assert/has-function-name-support":39,"@stdlib/assert/is-function":102,"@stdlib/regexp/function-name":305}],356:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Return the name of a function.
*
* @module @stdlib/utils/function-name
*
* @example
* var functionName = require( '@stdlib/utils/function-name' );
*
* var v = functionName( String );
* // returns 'String'
*
* v = functionName( function foo(){} );
* // returns 'foo'
*
* v = functionName( function(){} );
* // returns '' || 'anonymous'
*/
// MODULES //
var functionName = require( './function_name.js' );
// EXPORTS //
module.exports = functionName;
},{"./function_name.js":355}],357:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isFunction = require( '@stdlib/assert/is-function' );
var builtin = require( './native.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var getProto;
if ( isFunction( Object.getPrototypeOf ) ) {
getProto = builtin;
} else {
getProto = polyfill;
}
// EXPORTS //
module.exports = getProto;
},{"./native.js":360,"./polyfill.js":361,"@stdlib/assert/is-function":102}],358:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var getProto = require( './detect.js' );
// MAIN //
/**
* Returns the prototype of a provided object.
*
* @param {*} value - input value
* @returns {(Object|null)} prototype
*
* @example
* var proto = getPrototypeOf( {} );
* // returns {}
*/
function getPrototypeOf( value ) {
if (
value === null ||
value === void 0
) {
return null;
}
// In order to ensure consistent ES5/ES6 behavior, cast input value to an object (strings, numbers, booleans); ES5 `Object.getPrototypeOf` throws when provided primitives and ES6 `Object.getPrototypeOf` casts:
value = Object( value );
return getProto( value );
}
// EXPORTS //
module.exports = getPrototypeOf;
},{"./detect.js":357}],359:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Return the prototype of a provided object.
*
* @module @stdlib/utils/get-prototype-of
*
* @example
* var getPrototype = require( '@stdlib/utils/get-prototype-of' );
*
* var proto = getPrototype( {} );
* // returns {}
*/
// MODULES //
var getPrototype = require( './get_prototype_of.js' );
// EXPORTS //
module.exports = getPrototype;
},{"./get_prototype_of.js":358}],360:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var getProto = Object.getPrototypeOf;
// EXPORTS //
module.exports = getProto;
},{}],361:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var nativeClass = require( '@stdlib/utils/native-class' );
var getProto = require( './proto.js' );
// MAIN //
/**
* Returns the prototype of a provided object.
*
* @private
* @param {Object} obj - input object
* @returns {(Object|null)} prototype
*/
function getPrototypeOf( obj ) {
var proto = getProto( obj );
if ( proto || proto === null ) {
return proto;
}
if ( nativeClass( obj.constructor ) === '[object Function]' ) {
// May break if the constructor has been tampered with...
return obj.constructor.prototype;
}
if ( obj instanceof Object ) {
return Object.prototype;
}
// Return `null` for objects created via `Object.create( null )`. Also return `null` for cross-realm objects on browsers that lack `__proto__` support, such as IE < 11.
return null;
}
// EXPORTS //
module.exports = getPrototypeOf;
},{"./proto.js":362,"@stdlib/utils/native-class":393}],362:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Returns the value of the `__proto__` property.
*
* @private
* @param {Object} obj - input object
* @returns {*} value of `__proto__` property
*/
function getProto( obj ) {
// eslint-disable-next-line no-proto
return obj.__proto__;
}
// EXPORTS //
module.exports = getProto;
},{}],363:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Returns the global object using code generation.
*
* @private
* @returns {Object} global object
*/
function getGlobal() {
return new Function( 'return this;' )(); // eslint-disable-line no-new-func
}
// EXPORTS //
module.exports = getGlobal;
},{}],364:[function(require,module,exports){
(function (global){(function (){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var obj = ( typeof global === 'object' ) ? global : null;
// EXPORTS //
module.exports = obj;
}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],365:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Return the global object.
*
* @module @stdlib/utils/global
*
* @example
* var getGlobal = require( '@stdlib/utils/global' );
*
* var g = getGlobal();
* // returns {...}
*/
// MODULES //
var getGlobal = require( './main.js' );
// EXPORTS //
module.exports = getGlobal;
},{"./main.js":366}],366:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive;
var getThis = require( './codegen.js' );
var Self = require( './self.js' );
var Win = require( './window.js' );
var Global = require( './global.js' );
// MAIN //
/**
* Returns the global object.
*
* ## Notes
*
* - Using code generation is the **most** reliable way to resolve the global object; however, doing so is likely to violate content security policies (CSPs) in, e.g., Chrome Apps and elsewhere.
*
* @param {boolean} [codegen=false] - boolean indicating whether to use code generation to resolve the global object
* @throws {TypeError} must provide a boolean
* @throws {Error} unable to resolve global object
* @returns {Object} global object
*
* @example
* var g = getGlobal();
* // returns {...}
*/
function getGlobal( codegen ) {
if ( arguments.length ) {
if ( !isBoolean( codegen ) ) {
throw new TypeError( 'invalid argument. Must provide a boolean primitive. Value: `'+codegen+'`.' );
}
if ( codegen ) {
return getThis();
}
// Fall through...
}
// Case: browsers and web workers
if ( Self ) {
return Self;
}
// Case: browsers
if ( Win ) {
return Win;
}
// Case: Node.js
if ( Global ) {
return Global;
}
// Case: unknown
throw new Error( 'unexpected error. Unable to resolve global object.' );
}
// EXPORTS //
module.exports = getGlobal;
},{"./codegen.js":363,"./global.js":364,"./self.js":367,"./window.js":368,"@stdlib/assert/is-boolean":81}],367:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var obj = ( typeof self === 'object' ) ? self : null;
// EXPORTS //
module.exports = obj;
},{}],368:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var obj = ( typeof window === 'object' ) ? window : null;
// EXPORTS //
module.exports = obj;
},{}],369:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Return the first index at which a given element can be found.
*
* @module @stdlib/utils/index-of
*
* @example
* var indexOf = require( '@stdlib/utils/index-of' );
*
* var arr = [ 4, 3, 2, 1 ];
* var idx = indexOf( arr, 3 );
* // returns 1
*
* arr = [ 4, 3, 2, 1 ];
* idx = indexOf( arr, 5 );
* // returns -1
*
* // Using a `fromIndex`:
* arr = [ 1, 2, 3, 4, 5, 2, 6 ];
* idx = indexOf( arr, 2, 3 );
* // returns 5
*
* // `fromIndex` which exceeds `array` length:
* arr = [ 1, 2, 3, 4, 2, 5 ];
* idx = indexOf( arr, 2, 10 );
* // returns -1
*
* // Negative `fromIndex`:
* arr = [ 1, 2, 3, 4, 5, 2, 6, 2 ];
* idx = indexOf( arr, 2, -4 );
* // returns 5
*
* idx = indexOf( arr, 2, -1 );
* // returns 7
*
* // Negative `fromIndex` exceeding input `array` length:
* arr = [ 1, 2, 3, 4, 5, 2, 6 ];
* idx = indexOf( arr, 2, -10 );
* // returns 1
*
* // Array-like objects:
* var str = 'bebop';
* idx = indexOf( str, 'o' );
* // returns 3
*/
// MODULES //
var indexOf = require( './index_of.js' );
// EXPORTS //
module.exports = indexOf;
},{"./index_of.js":370}],370:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isnan = require( '@stdlib/assert/is-nan' );
var isCollection = require( '@stdlib/assert/is-collection' );
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var isInteger = require( '@stdlib/assert/is-integer' ).isPrimitive;
// MAIN //
/**
* Returns the first index at which a given element can be found.
*
* @param {ArrayLike} arr - array-like object
* @param {*} searchElement - element to find
* @param {integer} [fromIndex] - starting index (if negative, the start index is determined relative to last element)
* @throws {TypeError} must provide an array-like object
* @throws {TypeError} `fromIndex` must be an integer
* @returns {integer} index or -1
*
* @example
* var arr = [ 4, 3, 2, 1 ];
* var idx = indexOf( arr, 3 );
* // returns 1
*
* @example
* var arr = [ 4, 3, 2, 1 ];
* var idx = indexOf( arr, 5 );
* // returns -1
*
* @example
* // Using a `fromIndex`:
* var arr = [ 1, 2, 3, 4, 5, 2, 6 ];
* var idx = indexOf( arr, 2, 3 );
* // returns 5
*
* @example
* // `fromIndex` which exceeds `array` length:
* var arr = [ 1, 2, 3, 4, 2, 5 ];
* var idx = indexOf( arr, 2, 10 );
* // returns -1
*
* @example
* // Negative `fromIndex`:
* var arr = [ 1, 2, 3, 4, 5, 2, 6, 2 ];
* var idx = indexOf( arr, 2, -4 );
* // returns 5
*
* idx = indexOf( arr, 2, -1 );
* // returns 7
*
* @example
* // Negative `fromIndex` exceeding input `array` length:
* var arr = [ 1, 2, 3, 4, 5, 2, 6 ];
* var idx = indexOf( arr, 2, -10 );
* // returns 1
*
* @example
* // Array-like objects:
* var str = 'bebop';
* var idx = indexOf( str, 'o' );
* // returns 3
*/
function indexOf( arr, searchElement, fromIndex ) {
var len;
var i;
if ( !isCollection( arr ) && !isString( arr ) ) {
throw new TypeError( 'invalid argument. First argument must be an array-like object. Value: `' + arr + '`.' );
}
len = arr.length;
if ( len === 0 ) {
return -1;
}
if ( arguments.length === 3 ) {
if ( !isInteger( fromIndex ) ) {
throw new TypeError( 'invalid argument. `fromIndex` must be an integer. Value: `' + fromIndex + '`.' );
}
if ( fromIndex >= 0 ) {
if ( fromIndex >= len ) {
return -1;
}
i = fromIndex;
} else {
i = len + fromIndex;
if ( i < 0 ) {
i = 0;
}
}
} else {
i = 0;
}
// Check for `NaN`...
if ( isnan( searchElement ) ) {
for ( ; i < len; i++ ) {
if ( isnan( arr[i] ) ) {
return i;
}
}
} else {
for ( ; i < len; i++ ) {
if ( arr[ i ] === searchElement ) {
return i;
}
}
}
return -1;
}
// EXPORTS //
module.exports = indexOf;
},{"@stdlib/assert/is-collection":90,"@stdlib/assert/is-integer":110,"@stdlib/assert/is-nan":118,"@stdlib/assert/is-string":158}],371:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var builtin = require( './native.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var createObject;
if ( typeof builtin === 'function' ) {
createObject = builtin;
} else {
createObject = polyfill;
}
// EXPORTS //
module.exports = createObject;
},{"./native.js":374,"./polyfill.js":375}],372:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Implement prototypical inheritance by replacing the prototype of one constructor with the prototype of another constructor.
*
* @module @stdlib/utils/inherit
*
* @example
* var inherit = require( '@stdlib/utils/inherit' );
*
* function Foo() {
* return this;
* }
* Foo.prototype.beep = function beep() {
* return 'boop';
* };
*
* function Bar() {
* Foo.call( this );
* return this;
* }
* inherit( Bar, Foo );
*
* var bar = new Bar();
* var v = bar.beep();
* // returns 'boop'
*/
// MODULES //
var inherit = require( './inherit.js' );
// EXPORTS //
module.exports = inherit;
},{"./inherit.js":373}],373:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var defineProperty = require( '@stdlib/utils/define-property' );
var validate = require( './validate.js' );
var createObject = require( './detect.js' );
// MAIN //
/**
* Implements prototypical inheritance by replacing the prototype of one constructor with the prototype of another constructor.
*
* ## Notes
*
* - This implementation is not designed to work with ES2015/ES6 classes. For ES2015/ES6 classes, use `class` with `extends`.
* - For reference, see [node#3455](https://github.com/nodejs/node/pull/3455), [node#4179](https://github.com/nodejs/node/issues/4179), [node#3452](https://github.com/nodejs/node/issues/3452), and [node commit](https://github.com/nodejs/node/commit/29da8cf8d7ab8f66b9091ab22664067d4468461e#diff-3deb3f32958bb937ae05c6f3e4abbdf5).
*
*
* @param {(Object|Function)} ctor - constructor which will inherit
* @param {(Object|Function)} superCtor - super (parent) constructor
* @throws {TypeError} first argument must be either an object or a function which can inherit
* @throws {TypeError} second argument must be either an object or a function from which a constructor can inherit
* @throws {TypeError} second argument must have an inheritable prototype
* @returns {(Object|Function)} child constructor
*
* @example
* function Foo() {
* return this;
* }
* Foo.prototype.beep = function beep() {
* return 'boop';
* };
*
* function Bar() {
* Foo.call( this );
* return this;
* }
* inherit( Bar, Foo );
*
* var bar = new Bar();
* var v = bar.beep();
* // returns 'boop'
*/
function inherit( ctor, superCtor ) {
var err = validate( ctor );
if ( err ) {
throw err;
}
err = validate( superCtor );
if ( err ) {
throw err;
}
if ( typeof superCtor.prototype === 'undefined' ) {
throw new TypeError( 'invalid argument. Second argument must have a prototype from which another object can inherit. Value: `'+superCtor.prototype+'`.' );
}
// Create a prototype which inherits from the parent prototype:
ctor.prototype = createObject( superCtor.prototype );
// Set the constructor to refer to the child constructor:
defineProperty( ctor.prototype, 'constructor', {
'configurable': true,
'enumerable': false,
'writable': true,
'value': ctor
});
return ctor;
}
// EXPORTS //
module.exports = inherit;
},{"./detect.js":371,"./validate.js":376,"@stdlib/utils/define-property":351}],374:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// EXPORTS //
module.exports = Object.create;
},{}],375:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// FUNCTIONS //
/**
* Dummy constructor.
*
* @private
*/
function Ctor() {
// Empty...
}
// MAIN //
/**
* An `Object.create` shim for older JavaScript engines.
*
* @private
* @param {Object} proto - prototype
* @returns {Object} created object
*
* @example
* var obj = createObject( Object.prototype );
* // returns {}
*/
function createObject( proto ) {
Ctor.prototype = proto;
return new Ctor();
}
// EXPORTS //
module.exports = createObject;
},{}],376:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Tests that a value is a valid constructor.
*
* @private
* @param {*} value - value to test
* @returns {(Error|null)} error object or null
*
* @example
* var ctor = function ctor() {};
*
* var err = validate( ctor );
* // returns null
*
* err = validate( null );
* // returns <TypeError>
*/
function validate( value ) {
var type = typeof value;
if (
value === null ||
(type !== 'object' && type !== 'function')
) {
return new TypeError( 'invalid argument. A provided constructor must be either an object (except null) or a function. Value: `'+value+'`.' );
}
return null;
}
// EXPORTS //
module.exports = validate;
},{}],377:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Returns an array of an object's own enumerable property names.
*
* ## Notes
*
* - In contrast to the built-in `Object.keys()`, this function returns an empty array if provided `undefined` or `null`, rather than throwing an error.
*
* @private
* @param {*} value - input object
* @returns {Array} a list of own enumerable property names
*
* @example
* var obj = {
* 'beep': 'boop',
* 'foo': 3.14
* };
*
* var k = keys( obj );
* // e.g., returns [ 'beep', 'foo' ]
*/
function keys( value ) {
return Object.keys( Object( value ) );
}
// EXPORTS //
module.exports = keys;
},{}],378:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isArguments = require( '@stdlib/assert/is-arguments' );
var builtin = require( './builtin.js' );
// VARIABLES //
var slice = Array.prototype.slice;
// MAIN //
/**
* Returns an array of an object's own enumerable property names.
*
* @private
* @param {*} value - input object
* @returns {Array} a list of own enumerable property names
*
* @example
* var obj = {
* 'beep': 'boop',
* 'foo': 3.14
* };
*
* var k = keys( obj );
* // e.g., returns [ 'beep', 'foo' ]
*/
function keys( value ) {
if ( isArguments( value ) ) {
return builtin( slice.call( value ) );
}
return builtin( value );
}
// EXPORTS //
module.exports = keys;
},{"./builtin.js":377,"@stdlib/assert/is-arguments":74}],379:[function(require,module,exports){
module.exports=[
"console",
"external",
"frame",
"frameElement",
"frames",
"innerHeight",
"innerWidth",
"outerHeight",
"outerWidth",
"pageXOffset",
"pageYOffset",
"parent",
"scrollLeft",
"scrollTop",
"scrollX",
"scrollY",
"self",
"webkitIndexedDB",
"webkitStorageInfo",
"window"
]
},{}],380:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var keys = require( './builtin.js' );
// FUNCTIONS //
/**
* Tests the built-in `Object.keys()` implementation when provided `arguments`.
*
* @private
* @returns {boolean} boolean indicating whether the built-in implementation returns the expected number of keys
*/
function test() {
return ( keys( arguments ) || '' ).length !== 2;
}
// MAIN //
/**
* Tests whether the built-in `Object.keys()` implementation supports providing `arguments` as an input value.
*
* ## Notes
*
* - Safari 5.0 does **not** support `arguments` as an input value.
*
* @private
* @returns {boolean} boolean indicating whether a built-in implementation supports `arguments`
*/
function check() {
return test( 1, 2 );
}
// EXPORTS //
module.exports = check;
},{"./builtin.js":377}],381:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var indexOf = require( '@stdlib/utils/index-of' );
var typeOf = require( '@stdlib/utils/type-of' );
var isConstructorPrototype = require( './is_constructor_prototype.js' );
var EXCLUDED_KEYS = require( './excluded_keys.json' );
var win = require( './window.js' );
// VARIABLES //
var bool;
// FUNCTIONS //
/**
* Determines whether an environment throws when comparing to the prototype of a value's constructor (e.g., [IE9][1]).
*
* [1]: https://stackoverflow.com/questions/7688070/why-is-comparing-the-constructor-property-of-two-windows-unreliable
*
* @private
* @returns {boolean} boolean indicating whether an environment is buggy
*/
function check() {
var k;
if ( typeOf( win ) === 'undefined' ) {
return false;
}
for ( k in win ) { // eslint-disable-line guard-for-in
try {
if (
indexOf( EXCLUDED_KEYS, k ) === -1 &&
hasOwnProp( win, k ) &&
win[ k ] !== null &&
typeOf( win[ k ] ) === 'object'
) {
isConstructorPrototype( win[ k ] );
}
} catch ( err ) { // eslint-disable-line no-unused-vars
return true;
}
}
return false;
}
// MAIN //
bool = check();
// EXPORTS //
module.exports = bool;
},{"./excluded_keys.json":379,"./is_constructor_prototype.js":387,"./window.js":392,"@stdlib/assert/has-own-property":53,"@stdlib/utils/index-of":369,"@stdlib/utils/type-of":420}],382:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var bool = ( typeof Object.keys !== 'undefined' );
// EXPORTS //
module.exports = bool;
},{}],383:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isEnumerableProperty = require( '@stdlib/assert/is-enumerable-property' );
var noop = require( '@stdlib/utils/noop' );
// MAIN //
// Note: certain environments treat an object's prototype as enumerable, which, as a matter of convention, it shouldn't be...
var bool = isEnumerableProperty( noop, 'prototype' );
// EXPORTS //
module.exports = bool;
},{"@stdlib/assert/is-enumerable-property":93,"@stdlib/utils/noop":400}],384:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isEnumerableProperty = require( '@stdlib/assert/is-enumerable-property' );
// VARIABLES //
var obj = {
'toString': null
};
// MAIN //
// Note: certain environments don't allow enumeration of overwritten properties which are considered non-enumerable...
var bool = !isEnumerableProperty( obj, 'toString' );
// EXPORTS //
module.exports = bool;
},{"@stdlib/assert/is-enumerable-property":93}],385:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var bool = ( typeof window !== 'undefined' );
// EXPORTS //
module.exports = bool;
},{}],386:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Return an array of an object's own enumerable property names.
*
* @module @stdlib/utils/keys
*
* @example
* var keys = require( '@stdlib/utils/keys' );
*
* var obj = {
* 'beep': 'boop',
* 'foo': 3.14
* };
*
* var k = keys( obj );
* // e.g., returns [ 'beep', 'foo' ]
*/
// MODULES //
var keys = require( './main.js' );
// EXPORTS //
module.exports = keys;
},{"./main.js":389}],387:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Tests whether a value equals the prototype of its constructor.
*
* @private
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether a value equals the prototype of its constructor
*/
function isConstructorPrototype( value ) {
return ( value.constructor && value.constructor.prototype === value );
}
// EXPORTS //
module.exports = isConstructorPrototype;
},{}],388:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var hasAutomationEqualityBug = require( './has_automation_equality_bug.js' );
var isConstructorPrototype = require( './is_constructor_prototype.js' );
var HAS_WINDOW = require( './has_window.js' );
// MAIN //
/**
* Wraps the test for constructor prototype equality to accommodate buggy environments (e.g., environments which throw when testing equality).
*
* @private
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether a value equals the prototype of its constructor
*/
function wrapper( value ) {
if ( HAS_WINDOW === false && !hasAutomationEqualityBug ) {
return isConstructorPrototype( value );
}
try {
return isConstructorPrototype( value );
} catch ( error ) { // eslint-disable-line no-unused-vars
return false;
}
}
// EXPORTS //
module.exports = wrapper;
},{"./has_automation_equality_bug.js":381,"./has_window.js":385,"./is_constructor_prototype.js":387}],389:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var hasArgumentsBug = require( './has_arguments_bug.js' );
var HAS_BUILTIN = require( './has_builtin.js' );
var builtin = require( './builtin.js' );
var wrapper = require( './builtin_wrapper.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
/**
* Returns an array of an object's own enumerable property names.
*
* @name keys
* @type {Function}
* @param {*} value - input object
* @returns {Array} a list of own enumerable property names
*
* @example
* var obj = {
* 'beep': 'boop',
* 'foo': 3.14
* };
*
* var k = keys( obj );
* // e.g., returns [ 'beep', 'foo' ]
*/
var keys;
if ( HAS_BUILTIN ) {
if ( hasArgumentsBug() ) {
keys = wrapper;
} else {
keys = builtin;
}
} else {
keys = polyfill;
}
// EXPORTS //
module.exports = keys;
},{"./builtin.js":377,"./builtin_wrapper.js":378,"./has_arguments_bug.js":380,"./has_builtin.js":382,"./polyfill.js":391}],390:[function(require,module,exports){
module.exports=[
"toString",
"toLocaleString",
"valueOf",
"hasOwnProperty",
"isPrototypeOf",
"propertyIsEnumerable",
"constructor"
]
},{}],391:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isObjectLike = require( '@stdlib/assert/is-object-like' );
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var isArguments = require( '@stdlib/assert/is-arguments' );
var HAS_ENUM_PROTO_BUG = require( './has_enumerable_prototype_bug.js' );
var HAS_NON_ENUM_PROPS_BUG = require( './has_non_enumerable_properties_bug.js' );
var isConstructorPrototype = require( './is_constructor_prototype_wrapper.js' );
var NON_ENUMERABLE = require( './non_enumerable.json' );
// MAIN //
/**
* Returns an array of an object's own enumerable property names.
*
* @private
* @param {*} value - input object
* @returns {Array} a list of own enumerable property names
*
* @example
* var obj = {
* 'beep': 'boop',
* 'foo': 3.14
* };
*
* var k = keys( obj );
* // e.g., returns [ 'beep', 'foo' ]
*/
function keys( value ) {
var skipConstructor;
var skipPrototype;
var isFcn;
var out;
var k;
var p;
var i;
out = [];
if ( isArguments( value ) ) {
// Account for environments which treat `arguments` differently...
for ( i = 0; i < value.length; i++ ) {
out.push( i.toString() );
}
// Note: yes, we are precluding the `arguments` array-like object from having other enumerable properties; however, this should (1) be very rare and (2) not be encouraged (e.g., doing something like `arguments.a = 'b'`; in certain engines directly manipulating the `arguments` value results in automatic de-optimization).
return out;
}
if ( typeof value === 'string' ) {
// Account for environments which do not treat string character indices as "own" properties...
if ( value.length > 0 && !hasOwnProp( value, '0' ) ) {
for ( i = 0; i < value.length; i++ ) {
out.push( i.toString() );
}
}
} else {
isFcn = ( typeof value === 'function' );
if ( isFcn === false && !isObjectLike( value ) ) {
return out;
}
skipPrototype = ( HAS_ENUM_PROTO_BUG && isFcn );
}
for ( k in value ) {
if ( !( skipPrototype && k === 'prototype' ) && hasOwnProp( value, k ) ) {
out.push( String( k ) );
}
}
if ( HAS_NON_ENUM_PROPS_BUG ) {
skipConstructor = isConstructorPrototype( value );
for ( i = 0; i < NON_ENUMERABLE.length; i++ ) {
p = NON_ENUMERABLE[ i ];
if ( !( skipConstructor && p === 'constructor' ) && hasOwnProp( value, p ) ) {
out.push( String( p ) );
}
}
}
return out;
}
// EXPORTS //
module.exports = keys;
},{"./has_enumerable_prototype_bug.js":383,"./has_non_enumerable_properties_bug.js":384,"./is_constructor_prototype_wrapper.js":388,"./non_enumerable.json":390,"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-arguments":74,"@stdlib/assert/is-object-like":143}],392:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var w = ( typeof window === 'undefined' ) ? void 0 : window;
// EXPORTS //
module.exports = w;
},{}],393:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Return a string value indicating a specification defined classification of an object.
*
* @module @stdlib/utils/native-class
*
* @example
* var nativeClass = require( '@stdlib/utils/native-class' );
*
* var str = nativeClass( 'a' );
* // returns '[object String]'
*
* str = nativeClass( 5 );
* // returns '[object Number]'
*
* function Beep() {
* return this;
* }
* str = nativeClass( new Beep() );
* // returns '[object Object]'
*/
// MODULES //
var hasToStringTag = require( '@stdlib/assert/has-tostringtag-support' );
var builtin = require( './native_class.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var nativeClass;
if ( hasToStringTag() ) {
nativeClass = polyfill;
} else {
nativeClass = builtin;
}
// EXPORTS //
module.exports = nativeClass;
},{"./native_class.js":394,"./polyfill.js":395,"@stdlib/assert/has-tostringtag-support":57}],394:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var toStr = require( './tostring.js' );
// MAIN //
/**
* Returns a string value indicating a specification defined classification (via the internal property `[[Class]]`) of an object.
*
* @param {*} v - input value
* @returns {string} string value indicating a specification defined classification of the input value
*
* @example
* var str = nativeClass( 'a' );
* // returns '[object String]'
*
* @example
* var str = nativeClass( 5 );
* // returns '[object Number]'
*
* @example
* function Beep() {
* return this;
* }
* var str = nativeClass( new Beep() );
* // returns '[object Object]'
*/
function nativeClass( v ) {
return toStr.call( v );
}
// EXPORTS //
module.exports = nativeClass;
},{"./tostring.js":396}],395:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var toStringTag = require( './tostringtag.js' );
var toStr = require( './tostring.js' );
// MAIN //
/**
* Returns a string value indicating a specification defined classification of an object in environments supporting `Symbol.toStringTag`.
*
* @param {*} v - input value
* @returns {string} string value indicating a specification defined classification of the input value
*
* @example
* var str = nativeClass( 'a' );
* // returns '[object String]'
*
* @example
* var str = nativeClass( 5 );
* // returns '[object Number]'
*
* @example
* function Beep() {
* return this;
* }
* var str = nativeClass( new Beep() );
* // returns '[object Object]'
*/
function nativeClass( v ) {
var isOwn;
var tag;
var out;
if ( v === null || v === void 0 ) {
return toStr.call( v );
}
tag = v[ toStringTag ];
isOwn = hasOwnProp( v, toStringTag );
// Attempt to override the `toStringTag` property. For built-ins having a `Symbol.toStringTag` property (e.g., `JSON`, `Math`, etc), the `Symbol.toStringTag` property is read-only (e.g., , so we need to wrap in a `try/catch`.
try {
v[ toStringTag ] = void 0;
} catch ( err ) { // eslint-disable-line no-unused-vars
return toStr.call( v );
}
out = toStr.call( v );
if ( isOwn ) {
v[ toStringTag ] = tag;
} else {
delete v[ toStringTag ];
}
return out;
}
// EXPORTS //
module.exports = nativeClass;
},{"./tostring.js":396,"./tostringtag.js":397,"@stdlib/assert/has-own-property":53}],396:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var toStr = Object.prototype.toString;
// EXPORTS //
module.exports = toStr;
},{}],397:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var toStrTag = ( typeof Symbol === 'function' ) ? Symbol.toStringTag : '';
// EXPORTS //
module.exports = toStrTag;
},{}],398:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2020 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Add a callback to the "next tick queue".
*
* @module @stdlib/utils/next-tick
*
* @example
* var nextTick = require( '@stdlib/utils/next-tick' );
*
* function beep() {
* console.log( 'boop' );
* }
*
* nextTick( beep );
*/
// MODULES //
var nextTick = require( './main.js' );
// EXPORTS //
module.exports = nextTick;
},{"./main.js":399}],399:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2020 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var proc = require( 'process' );
// MAIN //
/**
* Adds a callback to the "next tick queue".
*
* ## Notes
*
* - The queue is fully drained after the current operation on the JavaScript stack runs to completion and before the event loop is allowed to continue.
*
* @param {Callback} clbk - callback
* @param {...*} [args] - arguments to provide to the callback upon invocation
*
* @example
* function beep() {
* console.log( 'boop' );
* }
*
* nextTick( beep );
*/
function nextTick( clbk ) {
var args;
var i;
args = [];
for ( i = 1; i < arguments.length; i++ ) {
args.push( arguments[ i ] );
}
proc.nextTick( wrapper );
/**
* Callback wrapper.
*
* ## Notes
*
* - The ability to provide additional arguments was added in Node.js v1.8.1. The wrapper provides support for earlier Node.js versions.
*
* @private
*/
function wrapper() {
clbk.apply( null, args );
}
}
// EXPORTS //
module.exports = nextTick;
},{"process":436}],400:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* No operation.
*
* @module @stdlib/utils/noop
*
* @example
* var noop = require( '@stdlib/utils/noop' );
*
* noop();
* // ...does nothing.
*/
// MODULES //
var noop = require( './noop.js' );
// EXPORTS //
module.exports = noop;
},{"./noop.js":401}],401:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* No operation.
*
* @example
* noop();
* // ...does nothing.
*/
function noop() {
// Empty function...
}
// EXPORTS //
module.exports = noop;
},{}],402:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Return a partial object copy excluding specified keys.
*
* @module @stdlib/utils/omit
*
* @example
* var omit = require( '@stdlib/utils/omit' );
*
* var obj1 = {
* 'a': 1,
* 'b': 2
* };
*
* var obj2 = omit( obj1, 'b' );
* // returns { 'a': 1 }
*/
// MODULES //
var omit = require( './omit.js' );
// EXPORTS //
module.exports = omit;
},{"./omit.js":403}],403:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var objectKeys = require( '@stdlib/utils/keys' );
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var isStringArray = require( '@stdlib/assert/is-string-array' ).primitives;
var indexOf = require( '@stdlib/utils/index-of' );
// MAIN //
/**
* Returns a partial object copy excluding specified keys.
*
* @param {Object} obj - source object
* @param {(string|StringArray)} keys - keys to exclude
* @throws {TypeError} first argument must be an object
* @throws {TypeError} second argument must be either a string or an array of strings
* @returns {Object} new object
*
* @example
* var obj1 = {
* 'a': 1,
* 'b': 2
* };
*
* var obj2 = omit( obj1, 'b' );
* // returns { 'a': 1 }
*/
function omit( obj, keys ) {
var ownKeys;
var out;
var key;
var i;
if ( typeof obj !== 'object' || obj === null ) {
throw new TypeError( 'invalid argument. First argument must be an object. Value: `'+obj+'`.' );
}
ownKeys = objectKeys( obj );
out = {};
if ( isString( keys ) ) {
for ( i = 0; i < ownKeys.length; i++ ) {
key = ownKeys[ i ];
if ( key !== keys ) {
out[ key ] = obj[ key ];
}
}
return out;
}
if ( isStringArray( keys ) ) {
for ( i = 0; i < ownKeys.length; i++ ) {
key = ownKeys[ i ];
if ( indexOf( keys, key ) === -1 ) {
out[ key ] = obj[ key ];
}
}
return out;
}
throw new TypeError( 'invalid argument. Second argument must be either a string primitive or an array of string primitives. Value: `'+keys+'`.' );
}
// EXPORTS //
module.exports = omit;
},{"@stdlib/assert/is-string":158,"@stdlib/assert/is-string-array":157,"@stdlib/utils/index-of":369,"@stdlib/utils/keys":386}],404:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Return a partial object copy containing only specified keys.
*
* @module @stdlib/utils/pick
*
* @example
* var pick = require( '@stdlib/utils/pick' );
*
* var obj1 = {
* 'a': 1,
* 'b': 2
* };
*
* var obj2 = pick( obj1, 'b' );
* // returns { 'b': 2 }
*/
// MODULES //
var pick = require( './pick.js' );
// EXPORTS //
module.exports = pick;
},{"./pick.js":405}],405:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var isStringArray = require( '@stdlib/assert/is-string-array' ).primitives;
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
// MAIN //
/**
* Returns a partial object copy containing only specified keys. If a key does not exist as an own property in a source object, the key is ignored.
*
* @param {Object} obj - source object
* @param {(string|StringArray)} keys - keys to copy
* @throws {TypeError} first argument must be an object
* @throws {TypeError} second argument must be either a string or an array of strings
* @returns {Object} new object
*
* @example
* var obj1 = {
* 'a': 1,
* 'b': 2
* };
*
* var obj2 = pick( obj1, 'b' );
* // returns { 'b': 2 }
*/
function pick( obj, keys ) {
var out;
var key;
var i;
if ( typeof obj !== 'object' || obj === null ) {
throw new TypeError( 'invalid argument. First argument must be an object. Value: `'+obj+'`.' );
}
out = {};
if ( isString( keys ) ) {
if ( hasOwnProp( obj, keys ) ) {
out[ keys ] = obj[ keys ];
}
return out;
}
if ( isStringArray( keys ) ) {
for ( i = 0; i < keys.length; i++ ) {
key = keys[ i ];
if ( hasOwnProp( obj, key ) ) {
out[ key ] = obj[ key ];
}
}
return out;
}
throw new TypeError( 'invalid argument. Second argument must be either a string primitive or an array of string primitives. Value: `'+keys+'`.' );
}
// EXPORTS //
module.exports = pick;
},{"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-string":158,"@stdlib/assert/is-string-array":157}],406:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// VARIABLES //
var propertyDescriptor = Object.getOwnPropertyDescriptor;
// MAIN //
/**
* Returns a property descriptor for an object's own property.
*
* ## Notes
*
* - In contrast to the built-in `Object.getOwnPropertyDescriptor()`, this function returns `null` if provided `undefined` or `null`, rather than throwing an error.
* - In contrast to the built-in `Object.getOwnPropertyDescriptor()`, this function returns `null` if an object does not have a provided property, rather than `undefined`.
*
* @private
* @param {*} value - input object
* @param {(string|symbol)} property - property
* @returns {(Object|null)} property descriptor or null
*
* @example
* var obj = {
* 'beep': 'boop',
* 'foo': 3.14
* };
*
* var desc = getOwnPropertyDescriptor( obj, 'foo' );
* // returns {'configurable':true,'enumerable':true,'writable':true,'value':3.14}
*/
function getOwnPropertyDescriptor( value, property ) {
var desc;
if ( value === null || value === void 0 ) {
return null;
}
desc = propertyDescriptor( value, property );
return ( desc === void 0 ) ? null : desc;
}
// EXPORTS //
module.exports = getOwnPropertyDescriptor;
},{}],407:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var bool = ( typeof Object.getOwnPropertyDescriptor !== 'undefined' );
// EXPORTS //
module.exports = bool;
},{}],408:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Return a property descriptor for an object's own property.
*
* @module @stdlib/utils/property-descriptor
*
* @example
* var getOwnPropertyDescriptor = require( '@stdlib/utils/property-descriptor' );
*
* var obj = {
* 'foo': 'bar',
* 'beep': 'boop'
* };
*
* var keys = getOwnPropertyDescriptor( obj, 'foo' );
* // returns {'configurable':true,'enumerable':true,'writable':true,'value':'bar'}
*/
// MODULES //
var HAS_BUILTIN = require( './has_builtin.js' );
var builtin = require( './builtin.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var main;
if ( HAS_BUILTIN ) {
main = builtin;
} else {
main = polyfill;
}
// EXPORTS //
module.exports = main;
},{"./builtin.js":406,"./has_builtin.js":407,"./polyfill.js":409}],409:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
// MAIN //
/**
* Returns a property descriptor for an object's own property.
*
* ## Notes
*
* - In contrast to the built-in `Object.getOwnPropertyDescriptor()`, this function returns `null` if provided `undefined` or `null`, rather than throwing an error.
* - In contrast to the built-in `Object.getOwnPropertyDescriptor()`, this function returns `null` if an object does not have a provided property, rather than `undefined`.
* - In environments lacking `Object.getOwnPropertyDescriptor()` support, property descriptors do not exist. In non-supporting environment, if an object has a provided property, this function returns a descriptor object equivalent to that returned in a supporting environment; otherwise, the function returns `null`.
*
* @private
* @param {*} value - input object
* @param {(string|symbol)} property - property
* @returns {(Object|null)} property descriptor or null
*
* @example
* var obj = {
* 'beep': 'boop',
* 'foo': 3.14
* };
*
* var desc = getOwnPropertyDescriptor( obj, 'foo' );
* // returns {'configurable':true,'enumerable':true,'writable':true,'value':3.14}
*/
function getOwnPropertyDescriptor( value, property ) {
if ( hasOwnProp( value, property ) ) {
return {
'configurable': true,
'enumerable': true,
'writable': true,
'value': value[ property ]
};
}
return null;
}
// EXPORTS //
module.exports = getOwnPropertyDescriptor;
},{"@stdlib/assert/has-own-property":53}],410:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// VARIABLES //
var propertyNames = Object.getOwnPropertyNames;
// MAIN //
/**
* Returns an array of an object's own enumerable and non-enumerable property names.
*
* ## Notes
*
* - In contrast to the built-in `Object.getOwnPropertyNames()`, this function returns an empty array if provided `undefined` or `null`, rather than throwing an error.
*
* @private
* @param {*} value - input object
* @returns {Array} a list of own property names
*
* @example
* var obj = {
* 'beep': 'boop',
* 'foo': 3.14
* };
*
* var keys = getOwnPropertyNames( obj );
* // e.g., returns [ 'beep', 'foo' ]
*/
function getOwnPropertyNames( value ) {
return propertyNames( Object( value ) );
}
// EXPORTS //
module.exports = getOwnPropertyNames;
},{}],411:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var bool = ( typeof Object.getOwnPropertyNames !== 'undefined' );
// EXPORTS //
module.exports = bool;
},{}],412:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Return an array of an object's own enumerable and non-enumerable property names.
*
* @module @stdlib/utils/property-names
*
* @example
* var getOwnPropertyNames = require( '@stdlib/utils/property-names' );
*
* var keys = getOwnPropertyNames({
* 'foo': 'bar',
* 'beep': 'boop'
* });
* // e.g., returns [ 'foo', 'beep' ]
*/
// MODULES //
var HAS_BUILTIN = require( './has_builtin.js' );
var builtin = require( './builtin.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var main;
if ( HAS_BUILTIN ) {
main = builtin;
} else {
main = polyfill;
}
// EXPORTS //
module.exports = main;
},{"./builtin.js":410,"./has_builtin.js":411,"./polyfill.js":413}],413:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var keys = require( '@stdlib/utils/keys' );
// MAIN //
/**
* Returns an array of an object's own enumerable and non-enumerable property names.
*
* ## Notes
*
* - In contrast to the built-in `Object.getOwnPropertyNames()`, this function returns an empty array if provided `undefined` or `null`, rather than throwing an error.
* - In environments lacking support for `Object.getOwnPropertyNames()`, property descriptors are unavailable, and thus all properties can be safely assumed to be enumerable. Hence, we can defer to calling `Object.keys`, which retrieves all own enumerable property names.
*
* @private
* @param {*} value - input object
* @returns {Array} a list of own property names
*
* @example
* var obj = {
* 'beep': 'boop',
* 'foo': 3.14
* };
*
* var keys = getOwnPropertyNames( obj );
* // e.g., returns [ 'beep', 'foo' ]
*/
function getOwnPropertyNames( value ) {
return keys( Object( value ) );
}
// EXPORTS //
module.exports = getOwnPropertyNames;
},{"@stdlib/utils/keys":386}],414:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var reRegExp = require( '@stdlib/regexp/regexp' );
// MAIN //
/**
* Parses a regular expression string and returns a new regular expression.
*
* @param {string} str - regular expression string
* @throws {TypeError} must provide a regular expression string
* @returns {(RegExp|null)} regular expression or null
*
* @example
* var re = reFromString( '/beep/' );
* // returns /beep/
*/
function reFromString( str ) {
if ( !isString( str ) ) {
throw new TypeError( 'invalid argument. Must provide a regular expression string. Value: `' + str + '`.' );
}
// Capture the regular expression pattern and any flags:
str = reRegExp().exec( str );
// Create a new regular expression:
return ( str ) ? new RegExp( str[1], str[2] ) : null;
}
// EXPORTS //
module.exports = reFromString;
},{"@stdlib/assert/is-string":158,"@stdlib/regexp/regexp":308}],415:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Create a regular expression from a regular expression string.
*
* @module @stdlib/utils/regexp-from-string
*
* @example
* var reFromString = require( '@stdlib/utils/regexp-from-string' );
*
* var re = reFromString( '/beep/' );
* // returns /beep/
*/
// MODULES //
var reFromString = require( './from_string.js' );
// EXPORTS //
module.exports = reFromString;
},{"./from_string.js":414}],416:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var RE = require( './fixtures/re.js' );
var nodeList = require( './fixtures/nodelist.js' );
var typedarray = require( './fixtures/typedarray.js' );
// MAIN //
/**
* Checks whether a polyfill is needed when using the `typeof` operator.
*
* @private
* @returns {boolean} boolean indicating whether a polyfill is needed
*/
function check() {
if (
// Chrome 1-12 returns 'function' for regular expression instances (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof):
typeof RE === 'function' ||
// Safari 8 returns 'object' for typed array and weak map constructors (underscore #1929):
typeof typedarray === 'object' ||
// PhantomJS 1.9 returns 'function' for `NodeList` instances (underscore #2236):
typeof nodeList === 'function'
) {
return true;
}
return false;
}
// EXPORTS //
module.exports = check;
},{"./fixtures/nodelist.js":417,"./fixtures/re.js":418,"./fixtures/typedarray.js":419}],417:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var getGlobal = require( '@stdlib/utils/global' );
// MAIN //
var root = getGlobal();
var nodeList = root.document && root.document.childNodes;
// EXPORTS //
module.exports = nodeList;
},{"@stdlib/utils/global":365}],418:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
var RE = /./;
// EXPORTS //
module.exports = RE;
},{}],419:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
var typedarray = Int8Array; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = typedarray;
},{}],420:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Determine a value's type.
*
* @module @stdlib/utils/type-of
*
* @example
* var typeOf = require( '@stdlib/utils/type-of' );
*
* var str = typeOf( 'a' );
* // returns 'string'
*
* str = typeOf( 5 );
* // returns 'number'
*/
// MODULES //
var usePolyfill = require( './check.js' );
var typeOf = require( './typeof.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var main = ( usePolyfill() ) ? polyfill : typeOf;
// EXPORTS //
module.exports = main;
},{"./check.js":416,"./polyfill.js":421,"./typeof.js":422}],421:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var ctorName = require( '@stdlib/utils/constructor-name' );
// MAIN //
/**
* Determines a value's type.
*
* @param {*} v - input value
* @returns {string} string indicating the value's type
*/
function typeOf( v ) {
return ctorName( v ).toLowerCase();
}
// EXPORTS //
module.exports = typeOf;
},{"@stdlib/utils/constructor-name":336}],422:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var ctorName = require( '@stdlib/utils/constructor-name' );
// NOTES //
/*
* Built-in `typeof` operator behavior:
*
* ```text
* typeof null => 'object'
* typeof undefined => 'undefined'
* typeof 'a' => 'string'
* typeof 5 => 'number'
* typeof NaN => 'number'
* typeof true => 'boolean'
* typeof false => 'boolean'
* typeof {} => 'object'
* typeof [] => 'object'
* typeof function foo(){} => 'function'
* typeof function* foo(){} => 'object'
* typeof Symbol() => 'symbol'
* ```
*
*/
// MAIN //
/**
* Determines a value's type.
*
* @param {*} v - input value
* @returns {string} string indicating the value's type
*/
function typeOf( v ) {
var type;
// Address `typeof null` => `object` (see http://wiki.ecmascript.org/doku.php?id=harmony:typeof_null):
if ( v === null ) {
return 'null';
}
type = typeof v;
// If the `typeof` operator returned something other than `object`, we are done. Otherwise, we need to check for an internal class name or search for a constructor.
if ( type === 'object' ) {
return ctorName( v ).toLowerCase();
}
return type;
}
// EXPORTS //
module.exports = typeOf;
},{"@stdlib/utils/constructor-name":336}],423:[function(require,module,exports){
'use strict'
exports.byteLength = byteLength
exports.toByteArray = toByteArray
exports.fromByteArray = fromByteArray
var lookup = []
var revLookup = []
var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
for (var i = 0, len = code.length; i < len; ++i) {
lookup[i] = code[i]
revLookup[code.charCodeAt(i)] = i
}
// Support decoding URL-safe base64 strings, as Node.js does.
// See: https://en.wikipedia.org/wiki/Base64#URL_applications
revLookup['-'.charCodeAt(0)] = 62
revLookup['_'.charCodeAt(0)] = 63
function getLens (b64) {
var len = b64.length
if (len % 4 > 0) {
throw new Error('Invalid string. Length must be a multiple of 4')
}
// Trim off extra bytes after placeholder bytes are found
// See: https://github.com/beatgammit/base64-js/issues/42
var validLen = b64.indexOf('=')
if (validLen === -1) validLen = len
var placeHoldersLen = validLen === len
? 0
: 4 - (validLen % 4)
return [validLen, placeHoldersLen]
}
// base64 is 4/3 + up to two characters of the original data
function byteLength (b64) {
var lens = getLens(b64)
var validLen = lens[0]
var placeHoldersLen = lens[1]
return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
}
function _byteLength (b64, validLen, placeHoldersLen) {
return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
}
function toByteArray (b64) {
var tmp
var lens = getLens(b64)
var validLen = lens[0]
var placeHoldersLen = lens[1]
var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
var curByte = 0
// if there are placeholders, only get up to the last complete 4 chars
var len = placeHoldersLen > 0
? validLen - 4
: validLen
var i
for (i = 0; i < len; i += 4) {
tmp =
(revLookup[b64.charCodeAt(i)] << 18) |
(revLookup[b64.charCodeAt(i + 1)] << 12) |
(revLookup[b64.charCodeAt(i + 2)] << 6) |
revLookup[b64.charCodeAt(i + 3)]
arr[curByte++] = (tmp >> 16) & 0xFF
arr[curByte++] = (tmp >> 8) & 0xFF
arr[curByte++] = tmp & 0xFF
}
if (placeHoldersLen === 2) {
tmp =
(revLookup[b64.charCodeAt(i)] << 2) |
(revLookup[b64.charCodeAt(i + 1)] >> 4)
arr[curByte++] = tmp & 0xFF
}
if (placeHoldersLen === 1) {
tmp =
(revLookup[b64.charCodeAt(i)] << 10) |
(revLookup[b64.charCodeAt(i + 1)] << 4) |
(revLookup[b64.charCodeAt(i + 2)] >> 2)
arr[curByte++] = (tmp >> 8) & 0xFF
arr[curByte++] = tmp & 0xFF
}
return arr
}
function tripletToBase64 (num) {
return lookup[num >> 18 & 0x3F] +
lookup[num >> 12 & 0x3F] +
lookup[num >> 6 & 0x3F] +
lookup[num & 0x3F]
}
function encodeChunk (uint8, start, end) {
var tmp
var output = []
for (var i = start; i < end; i += 3) {
tmp =
((uint8[i] << 16) & 0xFF0000) +
((uint8[i + 1] << 8) & 0xFF00) +
(uint8[i + 2] & 0xFF)
output.push(tripletToBase64(tmp))
}
return output.join('')
}
function fromByteArray (uint8) {
var tmp
var len = uint8.length
var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
var parts = []
var maxChunkLength = 16383 // must be multiple of 3
// go through the array every three bytes, we'll deal with trailing stuff later
for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
}
// pad the end with zeros, but make sure to not forget the extra bytes
if (extraBytes === 1) {
tmp = uint8[len - 1]
parts.push(
lookup[tmp >> 2] +
lookup[(tmp << 4) & 0x3F] +
'=='
)
} else if (extraBytes === 2) {
tmp = (uint8[len - 2] << 8) + uint8[len - 1]
parts.push(
lookup[tmp >> 10] +
lookup[(tmp >> 4) & 0x3F] +
lookup[(tmp << 2) & 0x3F] +
'='
)
}
return parts.join('')
}
},{}],424:[function(require,module,exports){
},{}],425:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
'use strict';
var R = typeof Reflect === 'object' ? Reflect : null
var ReflectApply = R && typeof R.apply === 'function'
? R.apply
: function ReflectApply(target, receiver, args) {
return Function.prototype.apply.call(target, receiver, args);
}
var ReflectOwnKeys
if (R && typeof R.ownKeys === 'function') {
ReflectOwnKeys = R.ownKeys
} else if (Object.getOwnPropertySymbols) {
ReflectOwnKeys = function ReflectOwnKeys(target) {
return Object.getOwnPropertyNames(target)
.concat(Object.getOwnPropertySymbols(target));
};
} else {
ReflectOwnKeys = function ReflectOwnKeys(target) {
return Object.getOwnPropertyNames(target);
};
}
function ProcessEmitWarning(warning) {
if (console && console.warn) console.warn(warning);
}
var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {
return value !== value;
}
function EventEmitter() {
EventEmitter.init.call(this);
}
module.exports = EventEmitter;
module.exports.once = once;
// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._eventsCount = 0;
EventEmitter.prototype._maxListeners = undefined;
// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
var defaultMaxListeners = 10;
function checkListener(listener) {
if (typeof listener !== 'function') {
throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
}
}
Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
enumerable: true,
get: function() {
return defaultMaxListeners;
},
set: function(arg) {
if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {
throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.');
}
defaultMaxListeners = arg;
}
});
EventEmitter.init = function() {
if (this._events === undefined ||
this._events === Object.getPrototypeOf(this)._events) {
this._events = Object.create(null);
this._eventsCount = 0;
}
this._maxListeners = this._maxListeners || undefined;
};
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {
throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.');
}
this._maxListeners = n;
return this;
};
function _getMaxListeners(that) {
if (that._maxListeners === undefined)
return EventEmitter.defaultMaxListeners;
return that._maxListeners;
}
EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
return _getMaxListeners(this);
};
EventEmitter.prototype.emit = function emit(type) {
var args = [];
for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);
var doError = (type === 'error');
var events = this._events;
if (events !== undefined)
doError = (doError && events.error === undefined);
else if (!doError)
return false;
// If there is no 'error' event listener then throw.
if (doError) {
var er;
if (args.length > 0)
er = args[0];
if (er instanceof Error) {
// Note: The comments on the `throw` lines are intentional, they show
// up in Node's output if this results in an unhandled exception.
throw er; // Unhandled 'error' event
}
// At least give some kind of context to the user
var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));
err.context = er;
throw err; // Unhandled 'error' event
}
var handler = events[type];
if (handler === undefined)
return false;
if (typeof handler === 'function') {
ReflectApply(handler, this, args);
} else {
var len = handler.length;
var listeners = arrayClone(handler, len);
for (var i = 0; i < len; ++i)
ReflectApply(listeners[i], this, args);
}
return true;
};
function _addListener(target, type, listener, prepend) {
var m;
var events;
var existing;
checkListener(listener);
events = target._events;
if (events === undefined) {
events = target._events = Object.create(null);
target._eventsCount = 0;
} else {
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (events.newListener !== undefined) {
target.emit('newListener', type,
listener.listener ? listener.listener : listener);
// Re-assign `events` because a newListener handler could have caused the
// this._events to be assigned to a new object
events = target._events;
}
existing = events[type];
}
if (existing === undefined) {
// Optimize the case of one listener. Don't need the extra array object.
existing = events[type] = listener;
++target._eventsCount;
} else {
if (typeof existing === 'function') {
// Adding the second element, need to change to array.
existing = events[type] =
prepend ? [listener, existing] : [existing, listener];
// If we've already got an array, just append.
} else if (prepend) {
existing.unshift(listener);
} else {
existing.push(listener);
}
// Check for listener leak
m = _getMaxListeners(target);
if (m > 0 && existing.length > m && !existing.warned) {
existing.warned = true;
// No error code for this since it is a Warning
// eslint-disable-next-line no-restricted-syntax
var w = new Error('Possible EventEmitter memory leak detected. ' +
existing.length + ' ' + String(type) + ' listeners ' +
'added. Use emitter.setMaxListeners() to ' +
'increase limit');
w.name = 'MaxListenersExceededWarning';
w.emitter = target;
w.type = type;
w.count = existing.length;
ProcessEmitWarning(w);
}
}
return target;
}
EventEmitter.prototype.addListener = function addListener(type, listener) {
return _addListener(this, type, listener, false);
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.prependListener =
function prependListener(type, listener) {
return _addListener(this, type, listener, true);
};
function onceWrapper() {
if (!this.fired) {
this.target.removeListener(this.type, this.wrapFn);
this.fired = true;
if (arguments.length === 0)
return this.listener.call(this.target);
return this.listener.apply(this.target, arguments);
}
}
function _onceWrap(target, type, listener) {
var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
var wrapped = onceWrapper.bind(state);
wrapped.listener = listener;
state.wrapFn = wrapped;
return wrapped;
}
EventEmitter.prototype.once = function once(type, listener) {
checkListener(listener);
this.on(type, _onceWrap(this, type, listener));
return this;
};
EventEmitter.prototype.prependOnceListener =
function prependOnceListener(type, listener) {
checkListener(listener);
this.prependListener(type, _onceWrap(this, type, listener));
return this;
};
// Emits a 'removeListener' event if and only if the listener was removed.
EventEmitter.prototype.removeListener =
function removeListener(type, listener) {
var list, events, position, i, originalListener;
checkListener(listener);
events = this._events;
if (events === undefined)
return this;
list = events[type];
if (list === undefined)
return this;
if (list === listener || list.listener === listener) {
if (--this._eventsCount === 0)
this._events = Object.create(null);
else {
delete events[type];
if (events.removeListener)
this.emit('removeListener', type, list.listener || listener);
}
} else if (typeof list !== 'function') {
position = -1;
for (i = list.length - 1; i >= 0; i--) {
if (list[i] === listener || list[i].listener === listener) {
originalListener = list[i].listener;
position = i;
break;
}
}
if (position < 0)
return this;
if (position === 0)
list.shift();
else {
spliceOne(list, position);
}
if (list.length === 1)
events[type] = list[0];
if (events.removeListener !== undefined)
this.emit('removeListener', type, originalListener || listener);
}
return this;
};
EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
EventEmitter.prototype.removeAllListeners =
function removeAllListeners(type) {
var listeners, events, i;
events = this._events;
if (events === undefined)
return this;
// not listening for removeListener, no need to emit
if (events.removeListener === undefined) {
if (arguments.length === 0) {
this._events = Object.create(null);
this._eventsCount = 0;
} else if (events[type] !== undefined) {
if (--this._eventsCount === 0)
this._events = Object.create(null);
else
delete events[type];
}
return this;
}
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
var keys = Object.keys(events);
var key;
for (i = 0; i < keys.length; ++i) {
key = keys[i];
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = Object.create(null);
this._eventsCount = 0;
return this;
}
listeners = events[type];
if (typeof listeners === 'function') {
this.removeListener(type, listeners);
} else if (listeners !== undefined) {
// LIFO order
for (i = listeners.length - 1; i >= 0; i--) {
this.removeListener(type, listeners[i]);
}
}
return this;
};
function _listeners(target, type, unwrap) {
var events = target._events;
if (events === undefined)
return [];
var evlistener = events[type];
if (evlistener === undefined)
return [];
if (typeof evlistener === 'function')
return unwrap ? [evlistener.listener || evlistener] : [evlistener];
return unwrap ?
unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
}
EventEmitter.prototype.listeners = function listeners(type) {
return _listeners(this, type, true);
};
EventEmitter.prototype.rawListeners = function rawListeners(type) {
return _listeners(this, type, false);
};
EventEmitter.listenerCount = function(emitter, type) {
if (typeof emitter.listenerCount === 'function') {
return emitter.listenerCount(type);
} else {
return listenerCount.call(emitter, type);
}
};
EventEmitter.prototype.listenerCount = listenerCount;
function listenerCount(type) {
var events = this._events;
if (events !== undefined) {
var evlistener = events[type];
if (typeof evlistener === 'function') {
return 1;
} else if (evlistener !== undefined) {
return evlistener.length;
}
}
return 0;
}
EventEmitter.prototype.eventNames = function eventNames() {
return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];
};
function arrayClone(arr, n) {
var copy = new Array(n);
for (var i = 0; i < n; ++i)
copy[i] = arr[i];
return copy;
}
function spliceOne(list, index) {
for (; index + 1 < list.length; index++)
list[index] = list[index + 1];
list.pop();
}
function unwrapListeners(arr) {
var ret = new Array(arr.length);
for (var i = 0; i < ret.length; ++i) {
ret[i] = arr[i].listener || arr[i];
}
return ret;
}
function once(emitter, name) {
return new Promise(function (resolve, reject) {
function errorListener(err) {
emitter.removeListener(name, resolver);
reject(err);
}
function resolver() {
if (typeof emitter.removeListener === 'function') {
emitter.removeListener('error', errorListener);
}
resolve([].slice.call(arguments));
};
eventTargetAgnosticAddListener(emitter, name, resolver, { once: true });
if (name !== 'error') {
addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true });
}
});
}
function addErrorHandlerIfEventEmitter(emitter, handler, flags) {
if (typeof emitter.on === 'function') {
eventTargetAgnosticAddListener(emitter, 'error', handler, flags);
}
}
function eventTargetAgnosticAddListener(emitter, name, listener, flags) {
if (typeof emitter.on === 'function') {
if (flags.once) {
emitter.once(name, listener);
} else {
emitter.on(name, listener);
}
} else if (typeof emitter.addEventListener === 'function') {
// EventTarget does not have `error` event semantics like Node
// EventEmitters, we do not listen for `error` events here.
emitter.addEventListener(name, function wrapListener(arg) {
// IE does not have builtin `{ once: true }` support so we
// have to do it manually.
if (flags.once) {
emitter.removeEventListener(name, wrapListener);
}
listener(arg);
});
} else {
throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter);
}
}
},{}],426:[function(require,module,exports){
(function (Buffer){(function (){
/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <https://feross.org>
* @license MIT
*/
/* eslint-disable no-proto */
'use strict'
var base64 = require('base64-js')
var ieee754 = require('ieee754')
exports.Buffer = Buffer
exports.SlowBuffer = SlowBuffer
exports.INSPECT_MAX_BYTES = 50
var K_MAX_LENGTH = 0x7fffffff
exports.kMaxLength = K_MAX_LENGTH
/**
* If `Buffer.TYPED_ARRAY_SUPPORT`:
* === true Use Uint8Array implementation (fastest)
* === false Print warning and recommend using `buffer` v4.x which has an Object
* implementation (most compatible, even IE6)
*
* Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
* Opera 11.6+, iOS 4.2+.
*
* We report that the browser does not support typed arrays if the are not subclassable
* using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
* (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
* for __proto__ and has a buggy typed array implementation.
*/
Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
typeof console.error === 'function') {
console.error(
'This browser lacks typed array (Uint8Array) support which is required by ' +
'`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
)
}
function typedArraySupport () {
// Can typed array instances can be augmented?
try {
var arr = new Uint8Array(1)
arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } }
return arr.foo() === 42
} catch (e) {
return false
}
}
Object.defineProperty(Buffer.prototype, 'parent', {
enumerable: true,
get: function () {
if (!Buffer.isBuffer(this)) return undefined
return this.buffer
}
})
Object.defineProperty(Buffer.prototype, 'offset', {
enumerable: true,
get: function () {
if (!Buffer.isBuffer(this)) return undefined
return this.byteOffset
}
})
function createBuffer (length) {
if (length > K_MAX_LENGTH) {
throw new RangeError('The value "' + length + '" is invalid for option "size"')
}
// Return an augmented `Uint8Array` instance
var buf = new Uint8Array(length)
buf.__proto__ = Buffer.prototype
return buf
}
/**
* The Buffer constructor returns instances of `Uint8Array` that have their
* prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
* `Uint8Array`, so the returned instances will have all the node `Buffer` methods
* and the `Uint8Array` methods. Square bracket notation works as expected -- it
* returns a single octet.
*
* The `Uint8Array` prototype remains unmodified.
*/
function Buffer (arg, encodingOrOffset, length) {
// Common case.
if (typeof arg === 'number') {
if (typeof encodingOrOffset === 'string') {
throw new TypeError(
'The "string" argument must be of type string. Received type number'
)
}
return allocUnsafe(arg)
}
return from(arg, encodingOrOffset, length)
}
// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
if (typeof Symbol !== 'undefined' && Symbol.species != null &&
Buffer[Symbol.species] === Buffer) {
Object.defineProperty(Buffer, Symbol.species, {
value: null,
configurable: true,
enumerable: false,
writable: false
})
}
Buffer.poolSize = 8192 // not used by this implementation
function from (value, encodingOrOffset, length) {
if (typeof value === 'string') {
return fromString(value, encodingOrOffset)
}
if (ArrayBuffer.isView(value)) {
return fromArrayLike(value)
}
if (value == null) {
throw TypeError(
'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
'or Array-like Object. Received type ' + (typeof value)
)
}
if (isInstance(value, ArrayBuffer) ||
(value && isInstance(value.buffer, ArrayBuffer))) {
return fromArrayBuffer(value, encodingOrOffset, length)
}
if (typeof value === 'number') {
throw new TypeError(
'The "value" argument must not be of type number. Received type number'
)
}
var valueOf = value.valueOf && value.valueOf()
if (valueOf != null && valueOf !== value) {
return Buffer.from(valueOf, encodingOrOffset, length)
}
var b = fromObject(value)
if (b) return b
if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
typeof value[Symbol.toPrimitive] === 'function') {
return Buffer.from(
value[Symbol.toPrimitive]('string'), encodingOrOffset, length
)
}
throw new TypeError(
'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
'or Array-like Object. Received type ' + (typeof value)
)
}
/**
* Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
* if value is a number.
* Buffer.from(str[, encoding])
* Buffer.from(array)
* Buffer.from(buffer)
* Buffer.from(arrayBuffer[, byteOffset[, length]])
**/
Buffer.from = function (value, encodingOrOffset, length) {
return from(value, encodingOrOffset, length)
}
// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
// https://github.com/feross/buffer/pull/148
Buffer.prototype.__proto__ = Uint8Array.prototype
Buffer.__proto__ = Uint8Array
function assertSize (size) {
if (typeof size !== 'number') {
throw new TypeError('"size" argument must be of type number')
} else if (size < 0) {
throw new RangeError('The value "' + size + '" is invalid for option "size"')
}
}
function alloc (size, fill, encoding) {
assertSize(size)
if (size <= 0) {
return createBuffer(size)
}
if (fill !== undefined) {
// Only pay attention to encoding if it's a string. This
// prevents accidentally sending in a number that would
// be interpretted as a start offset.
return typeof encoding === 'string'
? createBuffer(size).fill(fill, encoding)
: createBuffer(size).fill(fill)
}
return createBuffer(size)
}
/**
* Creates a new filled Buffer instance.
* alloc(size[, fill[, encoding]])
**/
Buffer.alloc = function (size, fill, encoding) {
return alloc(size, fill, encoding)
}
function allocUnsafe (size) {
assertSize(size)
return createBuffer(size < 0 ? 0 : checked(size) | 0)
}
/**
* Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
* */
Buffer.allocUnsafe = function (size) {
return allocUnsafe(size)
}
/**
* Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
*/
Buffer.allocUnsafeSlow = function (size) {
return allocUnsafe(size)
}
function fromString (string, encoding) {
if (typeof encoding !== 'string' || encoding === '') {
encoding = 'utf8'
}
if (!Buffer.isEncoding(encoding)) {
throw new TypeError('Unknown encoding: ' + encoding)
}
var length = byteLength(string, encoding) | 0
var buf = createBuffer(length)
var actual = buf.write(string, encoding)
if (actual !== length) {
// Writing a hex string, for example, that contains invalid characters will
// cause everything after the first invalid character to be ignored. (e.g.
// 'abxxcd' will be treated as 'ab')
buf = buf.slice(0, actual)
}
return buf
}
function fromArrayLike (array) {
var length = array.length < 0 ? 0 : checked(array.length) | 0
var buf = createBuffer(length)
for (var i = 0; i < length; i += 1) {
buf[i] = array[i] & 255
}
return buf
}
function fromArrayBuffer (array, byteOffset, length) {
if (byteOffset < 0 || array.byteLength < byteOffset) {
throw new RangeError('"offset" is outside of buffer bounds')
}
if (array.byteLength < byteOffset + (length || 0)) {
throw new RangeError('"length" is outside of buffer bounds')
}
var buf
if (byteOffset === undefined && length === undefined) {
buf = new Uint8Array(array)
} else if (length === undefined) {
buf = new Uint8Array(array, byteOffset)
} else {
buf = new Uint8Array(array, byteOffset, length)
}
// Return an augmented `Uint8Array` instance
buf.__proto__ = Buffer.prototype
return buf
}
function fromObject (obj) {
if (Buffer.isBuffer(obj)) {
var len = checked(obj.length) | 0
var buf = createBuffer(len)
if (buf.length === 0) {
return buf
}
obj.copy(buf, 0, 0, len)
return buf
}
if (obj.length !== undefined) {
if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
return createBuffer(0)
}
return fromArrayLike(obj)
}
if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
return fromArrayLike(obj.data)
}
}
function checked (length) {
// Note: cannot use `length < K_MAX_LENGTH` here because that fails when
// length is NaN (which is otherwise coerced to zero.)
if (length >= K_MAX_LENGTH) {
throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
}
return length | 0
}
function SlowBuffer (length) {
if (+length != length) { // eslint-disable-line eqeqeq
length = 0
}
return Buffer.alloc(+length)
}
Buffer.isBuffer = function isBuffer (b) {
return b != null && b._isBuffer === true &&
b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
}
Buffer.compare = function compare (a, b) {
if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)
if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)
if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
throw new TypeError(
'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
)
}
if (a === b) return 0
var x = a.length
var y = b.length
for (var i = 0, len = Math.min(x, y); i < len; ++i) {
if (a[i] !== b[i]) {
x = a[i]
y = b[i]
break
}
}
if (x < y) return -1
if (y < x) return 1
return 0
}
Buffer.isEncoding = function isEncoding (encoding) {
switch (String(encoding).toLowerCase()) {
case 'hex':
case 'utf8':
case 'utf-8':
case 'ascii':
case 'latin1':
case 'binary':
case 'base64':
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return true
default:
return false
}
}
Buffer.concat = function concat (list, length) {
if (!Array.isArray(list)) {
throw new TypeError('"list" argument must be an Array of Buffers')
}
if (list.length === 0) {
return Buffer.alloc(0)
}
var i
if (length === undefined) {
length = 0
for (i = 0; i < list.length; ++i) {
length += list[i].length
}
}
var buffer = Buffer.allocUnsafe(length)
var pos = 0
for (i = 0; i < list.length; ++i) {
var buf = list[i]
if (isInstance(buf, Uint8Array)) {
buf = Buffer.from(buf)
}
if (!Buffer.isBuffer(buf)) {
throw new TypeError('"list" argument must be an Array of Buffers')
}
buf.copy(buffer, pos)
pos += buf.length
}
return buffer
}
function byteLength (string, encoding) {
if (Buffer.isBuffer(string)) {
return string.length
}
if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
return string.byteLength
}
if (typeof string !== 'string') {
throw new TypeError(
'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
'Received type ' + typeof string
)
}
var len = string.length
var mustMatch = (arguments.length > 2 && arguments[2] === true)
if (!mustMatch && len === 0) return 0
// Use a for loop to avoid recursion
var loweredCase = false
for (;;) {
switch (encoding) {
case 'ascii':
case 'latin1':
case 'binary':
return len
case 'utf8':
case 'utf-8':
return utf8ToBytes(string).length
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return len * 2
case 'hex':
return len >>> 1
case 'base64':
return base64ToBytes(string).length
default:
if (loweredCase) {
return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
}
encoding = ('' + encoding).toLowerCase()
loweredCase = true
}
}
}
Buffer.byteLength = byteLength
function slowToString (encoding, start, end) {
var loweredCase = false
// No need to verify that "this.length <= MAX_UINT32" since it's a read-only
// property of a typed array.
// This behaves neither like String nor Uint8Array in that we set start/end
// to their upper/lower bounds if the value passed is out of range.
// undefined is handled specially as per ECMA-262 6th Edition,
// Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
if (start === undefined || start < 0) {
start = 0
}
// Return early if start > this.length. Done here to prevent potential uint32
// coercion fail below.
if (start > this.length) {
return ''
}
if (end === undefined || end > this.length) {
end = this.length
}
if (end <= 0) {
return ''
}
// Force coersion to uint32. This will also coerce falsey/NaN values to 0.
end >>>= 0
start >>>= 0
if (end <= start) {
return ''
}
if (!encoding) encoding = 'utf8'
while (true) {
switch (encoding) {
case 'hex':
return hexSlice(this, start, end)
case 'utf8':
case 'utf-8':
return utf8Slice(this, start, end)
case 'ascii':
return asciiSlice(this, start, end)
case 'latin1':
case 'binary':
return latin1Slice(this, start, end)
case 'base64':
return base64Slice(this, start, end)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return utf16leSlice(this, start, end)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = (encoding + '').toLowerCase()
loweredCase = true
}
}
}
// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
// reliably in a browserify context because there could be multiple different
// copies of the 'buffer' package in use. This method works even for Buffer
// instances that were created from another copy of the `buffer` package.
// See: https://github.com/feross/buffer/issues/154
Buffer.prototype._isBuffer = true
function swap (b, n, m) {
var i = b[n]
b[n] = b[m]
b[m] = i
}
Buffer.prototype.swap16 = function swap16 () {
var len = this.length
if (len % 2 !== 0) {
throw new RangeError('Buffer size must be a multiple of 16-bits')
}
for (var i = 0; i < len; i += 2) {
swap(this, i, i + 1)
}
return this
}
Buffer.prototype.swap32 = function swap32 () {
var len = this.length
if (len % 4 !== 0) {
throw new RangeError('Buffer size must be a multiple of 32-bits')
}
for (var i = 0; i < len; i += 4) {
swap(this, i, i + 3)
swap(this, i + 1, i + 2)
}
return this
}
Buffer.prototype.swap64 = function swap64 () {
var len = this.length
if (len % 8 !== 0) {
throw new RangeError('Buffer size must be a multiple of 64-bits')
}
for (var i = 0; i < len; i += 8) {
swap(this, i, i + 7)
swap(this, i + 1, i + 6)
swap(this, i + 2, i + 5)
swap(this, i + 3, i + 4)
}
return this
}
Buffer.prototype.toString = function toString () {
var length = this.length
if (length === 0) return ''
if (arguments.length === 0) return utf8Slice(this, 0, length)
return slowToString.apply(this, arguments)
}
Buffer.prototype.toLocaleString = Buffer.prototype.toString
Buffer.prototype.equals = function equals (b) {
if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
if (this === b) return true
return Buffer.compare(this, b) === 0
}
Buffer.prototype.inspect = function inspect () {
var str = ''
var max = exports.INSPECT_MAX_BYTES
str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()
if (this.length > max) str += ' ... '
return '<Buffer ' + str + '>'
}
Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
if (isInstance(target, Uint8Array)) {
target = Buffer.from(target, target.offset, target.byteLength)
}
if (!Buffer.isBuffer(target)) {
throw new TypeError(
'The "target" argument must be one of type Buffer or Uint8Array. ' +
'Received type ' + (typeof target)
)
}
if (start === undefined) {
start = 0
}
if (end === undefined) {
end = target ? target.length : 0
}
if (thisStart === undefined) {
thisStart = 0
}
if (thisEnd === undefined) {
thisEnd = this.length
}
if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
throw new RangeError('out of range index')
}
if (thisStart >= thisEnd && start >= end) {
return 0
}
if (thisStart >= thisEnd) {
return -1
}
if (start >= end) {
return 1
}
start >>>= 0
end >>>= 0
thisStart >>>= 0
thisEnd >>>= 0
if (this === target) return 0
var x = thisEnd - thisStart
var y = end - start
var len = Math.min(x, y)
var thisCopy = this.slice(thisStart, thisEnd)
var targetCopy = target.slice(start, end)
for (var i = 0; i < len; ++i) {
if (thisCopy[i] !== targetCopy[i]) {
x = thisCopy[i]
y = targetCopy[i]
break
}
}
if (x < y) return -1
if (y < x) return 1
return 0
}
// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
//
// Arguments:
// - buffer - a Buffer to search
// - val - a string, Buffer, or number
// - byteOffset - an index into `buffer`; will be clamped to an int32
// - encoding - an optional encoding, relevant is val is a string
// - dir - true for indexOf, false for lastIndexOf
function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
// Empty buffer means no match
if (buffer.length === 0) return -1
// Normalize byteOffset
if (typeof byteOffset === 'string') {
encoding = byteOffset
byteOffset = 0
} else if (byteOffset > 0x7fffffff) {
byteOffset = 0x7fffffff
} else if (byteOffset < -0x80000000) {
byteOffset = -0x80000000
}
byteOffset = +byteOffset // Coerce to Number.
if (numberIsNaN(byteOffset)) {
// byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
byteOffset = dir ? 0 : (buffer.length - 1)
}
// Normalize byteOffset: negative offsets start from the end of the buffer
if (byteOffset < 0) byteOffset = buffer.length + byteOffset
if (byteOffset >= buffer.length) {
if (dir) return -1
else byteOffset = buffer.length - 1
} else if (byteOffset < 0) {
if (dir) byteOffset = 0
else return -1
}
// Normalize val
if (typeof val === 'string') {
val = Buffer.from(val, encoding)
}
// Finally, search either indexOf (if dir is true) or lastIndexOf
if (Buffer.isBuffer(val)) {
// Special case: looking for empty string/buffer always fails
if (val.length === 0) {
return -1
}
return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
} else if (typeof val === 'number') {
val = val & 0xFF // Search for a byte value [0-255]
if (typeof Uint8Array.prototype.indexOf === 'function') {
if (dir) {
return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
} else {
return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
}
}
return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
}
throw new TypeError('val must be string, number or Buffer')
}
function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
var indexSize = 1
var arrLength = arr.length
var valLength = val.length
if (encoding !== undefined) {
encoding = String(encoding).toLowerCase()
if (encoding === 'ucs2' || encoding === 'ucs-2' ||
encoding === 'utf16le' || encoding === 'utf-16le') {
if (arr.length < 2 || val.length < 2) {
return -1
}
indexSize = 2
arrLength /= 2
valLength /= 2
byteOffset /= 2
}
}
function read (buf, i) {
if (indexSize === 1) {
return buf[i]
} else {
return buf.readUInt16BE(i * indexSize)
}
}
var i
if (dir) {
var foundIndex = -1
for (i = byteOffset; i < arrLength; i++) {
if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
if (foundIndex === -1) foundIndex = i
if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
} else {
if (foundIndex !== -1) i -= i - foundIndex
foundIndex = -1
}
}
} else {
if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
for (i = byteOffset; i >= 0; i--) {
var found = true
for (var j = 0; j < valLength; j++) {
if (read(arr, i + j) !== read(val, j)) {
found = false
break
}
}
if (found) return i
}
}
return -1
}
Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
return this.indexOf(val, byteOffset, encoding) !== -1
}
Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
}
Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
}
function hexWrite (buf, string, offset, length) {
offset = Number(offset) || 0
var remaining = buf.length - offset
if (!length) {
length = remaining
} else {
length = Number(length)
if (length > remaining) {
length = remaining
}
}
var strLen = string.length
if (length > strLen / 2) {
length = strLen / 2
}
for (var i = 0; i < length; ++i) {
var parsed = parseInt(string.substr(i * 2, 2), 16)
if (numberIsNaN(parsed)) return i
buf[offset + i] = parsed
}
return i
}
function utf8Write (buf, string, offset, length) {
return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
}
function asciiWrite (buf, string, offset, length) {
return blitBuffer(asciiToBytes(string), buf, offset, length)
}
function latin1Write (buf, string, offset, length) {
return asciiWrite(buf, string, offset, length)
}
function base64Write (buf, string, offset, length) {
return blitBuffer(base64ToBytes(string), buf, offset, length)
}
function ucs2Write (buf, string, offset, length) {
return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
}
Buffer.prototype.write = function write (string, offset, length, encoding) {
// Buffer#write(string)
if (offset === undefined) {
encoding = 'utf8'
length = this.length
offset = 0
// Buffer#write(string, encoding)
} else if (length === undefined && typeof offset === 'string') {
encoding = offset
length = this.length
offset = 0
// Buffer#write(string, offset[, length][, encoding])
} else if (isFinite(offset)) {
offset = offset >>> 0
if (isFinite(length)) {
length = length >>> 0
if (encoding === undefined) encoding = 'utf8'
} else {
encoding = length
length = undefined
}
} else {
throw new Error(
'Buffer.write(string, encoding, offset[, length]) is no longer supported'
)
}
var remaining = this.length - offset
if (length === undefined || length > remaining) length = remaining
if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
throw new RangeError('Attempt to write outside buffer bounds')
}
if (!encoding) encoding = 'utf8'
var loweredCase = false
for (;;) {
switch (encoding) {
case 'hex':
return hexWrite(this, string, offset, length)
case 'utf8':
case 'utf-8':
return utf8Write(this, string, offset, length)
case 'ascii':
return asciiWrite(this, string, offset, length)
case 'latin1':
case 'binary':
return latin1Write(this, string, offset, length)
case 'base64':
// Warning: maxLength not taken into account in base64Write
return base64Write(this, string, offset, length)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return ucs2Write(this, string, offset, length)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = ('' + encoding).toLowerCase()
loweredCase = true
}
}
}
Buffer.prototype.toJSON = function toJSON () {
return {
type: 'Buffer',
data: Array.prototype.slice.call(this._arr || this, 0)
}
}
function base64Slice (buf, start, end) {
if (start === 0 && end === buf.length) {
return base64.fromByteArray(buf)
} else {
return base64.fromByteArray(buf.slice(start, end))
}
}
function utf8Slice (buf, start, end) {
end = Math.min(buf.length, end)
var res = []
var i = start
while (i < end) {
var firstByte = buf[i]
var codePoint = null
var bytesPerSequence = (firstByte > 0xEF) ? 4
: (firstByte > 0xDF) ? 3
: (firstByte > 0xBF) ? 2
: 1
if (i + bytesPerSequence <= end) {
var secondByte, thirdByte, fourthByte, tempCodePoint
switch (bytesPerSequence) {
case 1:
if (firstByte < 0x80) {
codePoint = firstByte
}
break
case 2:
secondByte = buf[i + 1]
if ((secondByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
if (tempCodePoint > 0x7F) {
codePoint = tempCodePoint
}
}
break
case 3:
secondByte = buf[i + 1]
thirdByte = buf[i + 2]
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
codePoint = tempCodePoint
}
}
break
case 4:
secondByte = buf[i + 1]
thirdByte = buf[i + 2]
fourthByte = buf[i + 3]
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
codePoint = tempCodePoint
}
}
}
}
if (codePoint === null) {
// we did not generate a valid codePoint so insert a
// replacement char (U+FFFD) and advance only 1 byte
codePoint = 0xFFFD
bytesPerSequence = 1
} else if (codePoint > 0xFFFF) {
// encode to utf16 (surrogate pair dance)
codePoint -= 0x10000
res.push(codePoint >>> 10 & 0x3FF | 0xD800)
codePoint = 0xDC00 | codePoint & 0x3FF
}
res.push(codePoint)
i += bytesPerSequence
}
return decodeCodePointsArray(res)
}
// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
var MAX_ARGUMENTS_LENGTH = 0x1000
function decodeCodePointsArray (codePoints) {
var len = codePoints.length
if (len <= MAX_ARGUMENTS_LENGTH) {
return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
}
// Decode in chunks to avoid "call stack size exceeded".
var res = ''
var i = 0
while (i < len) {
res += String.fromCharCode.apply(
String,
codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
)
}
return res
}
function asciiSlice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i] & 0x7F)
}
return ret
}
function latin1Slice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i])
}
return ret
}
function hexSlice (buf, start, end) {
var len = buf.length
if (!start || start < 0) start = 0
if (!end || end < 0 || end > len) end = len
var out = ''
for (var i = start; i < end; ++i) {
out += toHex(buf[i])
}
return out
}
function utf16leSlice (buf, start, end) {
var bytes = buf.slice(start, end)
var res = ''
for (var i = 0; i < bytes.length; i += 2) {
res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
}
return res
}
Buffer.prototype.slice = function slice (start, end) {
var len = this.length
start = ~~start
end = end === undefined ? len : ~~end
if (start < 0) {
start += len
if (start < 0) start = 0
} else if (start > len) {
start = len
}
if (end < 0) {
end += len
if (end < 0) end = 0
} else if (end > len) {
end = len
}
if (end < start) end = start
var newBuf = this.subarray(start, end)
// Return an augmented `Uint8Array` instance
newBuf.__proto__ = Buffer.prototype
return newBuf
}
/*
* Need to make sure that buffer isn't trying to write out of bounds.
*/
function checkOffset (offset, ext, length) {
if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
}
Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var val = this[offset]
var mul = 1
var i = 0
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul
}
return val
}
Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) {
checkOffset(offset, byteLength, this.length)
}
var val = this[offset + --byteLength]
var mul = 1
while (byteLength > 0 && (mul *= 0x100)) {
val += this[offset + --byteLength] * mul
}
return val
}
Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 1, this.length)
return this[offset]
}
Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
return this[offset] | (this[offset + 1] << 8)
}
Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
return (this[offset] << 8) | this[offset + 1]
}
Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return ((this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16)) +
(this[offset + 3] * 0x1000000)
}
Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] * 0x1000000) +
((this[offset + 1] << 16) |
(this[offset + 2] << 8) |
this[offset + 3])
}
Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var val = this[offset]
var mul = 1
var i = 0
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul
}
mul *= 0x80
if (val >= mul) val -= Math.pow(2, 8 * byteLength)
return val
}
Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var i = byteLength
var mul = 1
var val = this[offset + --i]
while (i > 0 && (mul *= 0x100)) {
val += this[offset + --i] * mul
}
mul *= 0x80
if (val >= mul) val -= Math.pow(2, 8 * byteLength)
return val
}
Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 1, this.length)
if (!(this[offset] & 0x80)) return (this[offset])
return ((0xff - this[offset] + 1) * -1)
}
Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset] | (this[offset + 1] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset + 1] | (this[offset] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16) |
(this[offset + 3] << 24)
}
Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] << 24) |
(this[offset + 1] << 16) |
(this[offset + 2] << 8) |
(this[offset + 3])
}
Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, true, 23, 4)
}
Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, false, 23, 4)
}
Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, true, 52, 8)
}
Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, false, 52, 8)
}
function checkInt (buf, value, offset, ext, max, min) {
if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
if (offset + ext > buf.length) throw new RangeError('Index out of range')
}
Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) {
var maxBytes = Math.pow(2, 8 * byteLength) - 1
checkInt(this, value, offset, byteLength, maxBytes, 0)
}
var mul = 1
var i = 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
this[offset + i] = (value / mul) & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) {
var maxBytes = Math.pow(2, 8 * byteLength) - 1
checkInt(this, value, offset, byteLength, maxBytes, 0)
}
var i = byteLength - 1
var mul = 1
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
this[offset + i] = (value / mul) & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
this[offset] = (value & 0xff)
return offset + 1
}
Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
return offset + 2
}
Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
this[offset] = (value >>> 8)
this[offset + 1] = (value & 0xff)
return offset + 2
}
Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
this[offset + 3] = (value >>> 24)
this[offset + 2] = (value >>> 16)
this[offset + 1] = (value >>> 8)
this[offset] = (value & 0xff)
return offset + 4
}
Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = (value & 0xff)
return offset + 4
}
Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
var limit = Math.pow(2, (8 * byteLength) - 1)
checkInt(this, value, offset, byteLength, limit - 1, -limit)
}
var i = 0
var mul = 1
var sub = 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
sub = 1
}
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
var limit = Math.pow(2, (8 * byteLength) - 1)
checkInt(this, value, offset, byteLength, limit - 1, -limit)
}
var i = byteLength - 1
var mul = 1
var sub = 0
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
sub = 1
}
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
if (value < 0) value = 0xff + value + 1
this[offset] = (value & 0xff)
return offset + 1
}
Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
return offset + 2
}
Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
this[offset] = (value >>> 8)
this[offset + 1] = (value & 0xff)
return offset + 2
}
Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
this[offset + 2] = (value >>> 16)
this[offset + 3] = (value >>> 24)
return offset + 4
}
Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
if (value < 0) value = 0xffffffff + value + 1
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = (value & 0xff)
return offset + 4
}
function checkIEEE754 (buf, value, offset, ext, max, min) {
if (offset + ext > buf.length) throw new RangeError('Index out of range')
if (offset < 0) throw new RangeError('Index out of range')
}
function writeFloat (buf, value, offset, littleEndian, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
}
ieee754.write(buf, value, offset, littleEndian, 23, 4)
return offset + 4
}
Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
return writeFloat(this, value, offset, true, noAssert)
}
Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
return writeFloat(this, value, offset, false, noAssert)
}
function writeDouble (buf, value, offset, littleEndian, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
}
ieee754.write(buf, value, offset, littleEndian, 52, 8)
return offset + 8
}
Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
return writeDouble(this, value, offset, true, noAssert)
}
Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
return writeDouble(this, value, offset, false, noAssert)
}
// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
Buffer.prototype.copy = function copy (target, targetStart, start, end) {
if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
if (!start) start = 0
if (!end && end !== 0) end = this.length
if (targetStart >= target.length) targetStart = target.length
if (!targetStart) targetStart = 0
if (end > 0 && end < start) end = start
// Copy 0 bytes; we're done
if (end === start) return 0
if (target.length === 0 || this.length === 0) return 0
// Fatal error conditions
if (targetStart < 0) {
throw new RangeError('targetStart out of bounds')
}
if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
if (end < 0) throw new RangeError('sourceEnd out of bounds')
// Are we oob?
if (end > this.length) end = this.length
if (target.length - targetStart < end - start) {
end = target.length - targetStart + start
}
var len = end - start
if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
// Use built-in when available, missing from IE11
this.copyWithin(targetStart, start, end)
} else if (this === target && start < targetStart && targetStart < end) {
// descending copy from end
for (var i = len - 1; i >= 0; --i) {
target[i + targetStart] = this[i + start]
}
} else {
Uint8Array.prototype.set.call(
target,
this.subarray(start, end),
targetStart
)
}
return len
}
// Usage:
// buffer.fill(number[, offset[, end]])
// buffer.fill(buffer[, offset[, end]])
// buffer.fill(string[, offset[, end]][, encoding])
Buffer.prototype.fill = function fill (val, start, end, encoding) {
// Handle string cases:
if (typeof val === 'string') {
if (typeof start === 'string') {
encoding = start
start = 0
end = this.length
} else if (typeof end === 'string') {
encoding = end
end = this.length
}
if (encoding !== undefined && typeof encoding !== 'string') {
throw new TypeError('encoding must be a string')
}
if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
throw new TypeError('Unknown encoding: ' + encoding)
}
if (val.length === 1) {
var code = val.charCodeAt(0)
if ((encoding === 'utf8' && code < 128) ||
encoding === 'latin1') {
// Fast path: If `val` fits into a single byte, use that numeric value.
val = code
}
}
} else if (typeof val === 'number') {
val = val & 255
}
// Invalid ranges are not set to a default, so can range check early.
if (start < 0 || this.length < start || this.length < end) {
throw new RangeError('Out of range index')
}
if (end <= start) {
return this
}
start = start >>> 0
end = end === undefined ? this.length : end >>> 0
if (!val) val = 0
var i
if (typeof val === 'number') {
for (i = start; i < end; ++i) {
this[i] = val
}
} else {
var bytes = Buffer.isBuffer(val)
? val
: Buffer.from(val, encoding)
var len = bytes.length
if (len === 0) {
throw new TypeError('The value "' + val +
'" is invalid for argument "value"')
}
for (i = 0; i < end - start; ++i) {
this[i + start] = bytes[i % len]
}
}
return this
}
// HELPER FUNCTIONS
// ================
var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
function base64clean (str) {
// Node takes equal signs as end of the Base64 encoding
str = str.split('=')[0]
// Node strips out invalid characters like \n and \t from the string, base64-js does not
str = str.trim().replace(INVALID_BASE64_RE, '')
// Node converts strings with length < 2 to ''
if (str.length < 2) return ''
// Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
while (str.length % 4 !== 0) {
str = str + '='
}
return str
}
function toHex (n) {
if (n < 16) return '0' + n.toString(16)
return n.toString(16)
}
function utf8ToBytes (string, units) {
units = units || Infinity
var codePoint
var length = string.length
var leadSurrogate = null
var bytes = []
for (var i = 0; i < length; ++i) {
codePoint = string.charCodeAt(i)
// is surrogate component
if (codePoint > 0xD7FF && codePoint < 0xE000) {
// last char was a lead
if (!leadSurrogate) {
// no lead yet
if (codePoint > 0xDBFF) {
// unexpected trail
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
} else if (i + 1 === length) {
// unpaired lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
}
// valid lead
leadSurrogate = codePoint
continue
}
// 2 leads in a row
if (codePoint < 0xDC00) {
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
leadSurrogate = codePoint
continue
}
// valid surrogate pair
codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
} else if (leadSurrogate) {
// valid bmp char, but last char was a lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
}
leadSurrogate = null
// encode utf8
if (codePoint < 0x80) {
if ((units -= 1) < 0) break
bytes.push(codePoint)
} else if (codePoint < 0x800) {
if ((units -= 2) < 0) break
bytes.push(
codePoint >> 0x6 | 0xC0,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x10000) {
if ((units -= 3) < 0) break
bytes.push(
codePoint >> 0xC | 0xE0,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x110000) {
if ((units -= 4) < 0) break
bytes.push(
codePoint >> 0x12 | 0xF0,
codePoint >> 0xC & 0x3F | 0x80,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else {
throw new Error('Invalid code point')
}
}
return bytes
}
function asciiToBytes (str) {
var byteArray = []
for (var i = 0; i < str.length; ++i) {
// Node's code seems to be doing this and not & 0x7F..
byteArray.push(str.charCodeAt(i) & 0xFF)
}
return byteArray
}
function utf16leToBytes (str, units) {
var c, hi, lo
var byteArray = []
for (var i = 0; i < str.length; ++i) {
if ((units -= 2) < 0) break
c = str.charCodeAt(i)
hi = c >> 8
lo = c % 256
byteArray.push(lo)
byteArray.push(hi)
}
return byteArray
}
function base64ToBytes (str) {
return base64.toByteArray(base64clean(str))
}
function blitBuffer (src, dst, offset, length) {
for (var i = 0; i < length; ++i) {
if ((i + offset >= dst.length) || (i >= src.length)) break
dst[i + offset] = src[i]
}
return i
}
// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
// the `instanceof` check but they should be treated as of that type.
// See: https://github.com/feross/buffer/issues/166
function isInstance (obj, type) {
return obj instanceof type ||
(obj != null && obj.constructor != null && obj.constructor.name != null &&
obj.constructor.name === type.name)
}
function numberIsNaN (obj) {
// For IE11 support
return obj !== obj // eslint-disable-line no-self-compare
}
}).call(this)}).call(this,require("buffer").Buffer)
},{"base64-js":423,"buffer":426,"ieee754":430}],427:[function(require,module,exports){
(function (Buffer){(function (){
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(arg) {
if (Array.isArray) {
return Array.isArray(arg);
}
return objectToString(arg) === '[object Array]';
}
exports.isArray = isArray;
function isBoolean(arg) {
return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;
function isNull(arg) {
return arg === null;
}
exports.isNull = isNull;
function isNullOrUndefined(arg) {
return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;
function isNumber(arg) {
return typeof arg === 'number';
}
exports.isNumber = isNumber;
function isString(arg) {
return typeof arg === 'string';
}
exports.isString = isString;
function isSymbol(arg) {
return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;
function isUndefined(arg) {
return arg === void 0;
}
exports.isUndefined = isUndefined;
function isRegExp(re) {
return objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;
function isDate(d) {
return objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
function isError(e) {
return (objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;
function isFunction(arg) {
return typeof arg === 'function';
}
exports.isFunction = isFunction;
function isPrimitive(arg) {
return arg === null ||
typeof arg === 'boolean' ||
typeof arg === 'number' ||
typeof arg === 'string' ||
typeof arg === 'symbol' || // ES6 symbol
typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;
exports.isBuffer = Buffer.isBuffer;
function objectToString(o) {
return Object.prototype.toString.call(o);
}
}).call(this)}).call(this,{"isBuffer":require("../../is-buffer/index.js")})
},{"../../is-buffer/index.js":432}],428:[function(require,module,exports){
(function (process){(function (){
/**
* This is the web browser implementation of `debug()`.
*
* Expose `debug()` as the module.
*/
exports = module.exports = require('./debug');
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.storage = 'undefined' != typeof chrome
&& 'undefined' != typeof chrome.storage
? chrome.storage.local
: localstorage();
/**
* Colors.
*/
exports.colors = [
'lightseagreen',
'forestgreen',
'goldenrod',
'dodgerblue',
'darkorchid',
'crimson'
];
/**
* Currently only WebKit-based Web Inspectors, Firefox >= v31,
* and the Firebug extension (any Firefox version) are known
* to support "%c" CSS customizations.
*
* TODO: add a `localStorage` variable to explicitly enable/disable colors
*/
function useColors() {
// NB: In an Electron preload script, document will be defined but not fully
// initialized. Since we know we're in Chrome, we'll just detect this case
// explicitly
if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') {
return true;
}
// is webkit? http://stackoverflow.com/a/16459606/376773
// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
// is firebug? http://stackoverflow.com/a/398120/376773
(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
// is firefox >= v31?
// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
// double check webkit in userAgent just in case we are in a worker
(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
}
/**
* Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
*/
exports.formatters.j = function(v) {
try {
return JSON.stringify(v);
} catch (err) {
return '[UnexpectedJSONParseError]: ' + err.message;
}
};
/**
* Colorize log arguments if enabled.
*
* @api public
*/
function formatArgs(args) {
var useColors = this.useColors;
args[0] = (useColors ? '%c' : '')
+ this.namespace
+ (useColors ? ' %c' : ' ')
+ args[0]
+ (useColors ? '%c ' : ' ')
+ '+' + exports.humanize(this.diff);
if (!useColors) return;
var c = 'color: ' + this.color;
args.splice(1, 0, c, 'color: inherit')
// the final "%c" is somewhat tricky, because there could be other
// arguments passed either before or after the %c, so we need to
// figure out the correct index to insert the CSS into
var index = 0;
var lastC = 0;
args[0].replace(/%[a-zA-Z%]/g, function(match) {
if ('%%' === match) return;
index++;
if ('%c' === match) {
// we only are interested in the *last* %c
// (the user may have provided their own)
lastC = index;
}
});
args.splice(lastC, 0, c);
}
/**
* Invokes `console.log()` when available.
* No-op when `console.log` is not a "function".
*
* @api public
*/
function log() {
// this hackery is required for IE8/9, where
// the `console.log` function doesn't have 'apply'
return 'object' === typeof console
&& console.log
&& Function.prototype.apply.call(console.log, console, arguments);
}
/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
try {
if (null == namespaces) {
exports.storage.removeItem('debug');
} else {
exports.storage.debug = namespaces;
}
} catch(e) {}
}
/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/
function load() {
var r;
try {
r = exports.storage.debug;
} catch(e) {}
// If debug isn't set in LS, and we're in Electron, try to load $DEBUG
if (!r && typeof process !== 'undefined' && 'env' in process) {
r = process.env.DEBUG;
}
return r;
}
/**
* Enable namespaces listed in `localStorage.debug` initially.
*/
exports.enable(load());
/**
* Localstorage attempts to return the localstorage.
*
* This is necessary because safari throws
* when a user disables cookies/localstorage
* and you attempt to access it.
*
* @return {LocalStorage}
* @api private
*/
function localstorage() {
try {
return window.localStorage;
} catch (e) {}
}
}).call(this)}).call(this,require('_process'))
},{"./debug":429,"_process":436}],429:[function(require,module,exports){
/**
* This is the common logic for both the Node.js and web browser
* implementations of `debug()`.
*
* Expose `debug()` as the module.
*/
exports = module.exports = createDebug.debug = createDebug['default'] = createDebug;
exports.coerce = coerce;
exports.disable = disable;
exports.enable = enable;
exports.enabled = enabled;
exports.humanize = require('ms');
/**
* The currently active debug mode names, and names to skip.
*/
exports.names = [];
exports.skips = [];
/**
* Map of special "%n" handling functions, for the debug "format" argument.
*
* Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
*/
exports.formatters = {};
/**
* Previous log timestamp.
*/
var prevTime;
/**
* Select a color.
* @param {String} namespace
* @return {Number}
* @api private
*/
function selectColor(namespace) {
var hash = 0, i;
for (i in namespace) {
hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
hash |= 0; // Convert to 32bit integer
}
return exports.colors[Math.abs(hash) % exports.colors.length];
}
/**
* Create a debugger with the given `namespace`.
*
* @param {String} namespace
* @return {Function}
* @api public
*/
function createDebug(namespace) {
function debug() {
// disabled?
if (!debug.enabled) return;
var self = debug;
// set `diff` timestamp
var curr = +new Date();
var ms = curr - (prevTime || curr);
self.diff = ms;
self.prev = prevTime;
self.curr = curr;
prevTime = curr;
// turn the `arguments` into a proper Array
var args = new Array(arguments.length);
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i];
}
args[0] = exports.coerce(args[0]);
if ('string' !== typeof args[0]) {
// anything else let's inspect with %O
args.unshift('%O');
}
// apply any `formatters` transformations
var index = 0;
args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) {
// if we encounter an escaped % then don't increase the array index
if (match === '%%') return match;
index++;
var formatter = exports.formatters[format];
if ('function' === typeof formatter) {
var val = args[index];
match = formatter.call(self, val);
// now we need to remove `args[index]` since it's inlined in the `format`
args.splice(index, 1);
index--;
}
return match;
});
// apply env-specific formatting (colors, etc.)
exports.formatArgs.call(self, args);
var logFn = debug.log || exports.log || console.log.bind(console);
logFn.apply(self, args);
}
debug.namespace = namespace;
debug.enabled = exports.enabled(namespace);
debug.useColors = exports.useColors();
debug.color = selectColor(namespace);
// env-specific initialization logic for debug instances
if ('function' === typeof exports.init) {
exports.init(debug);
}
return debug;
}
/**
* Enables a debug mode by namespaces. This can include modes
* separated by a colon and wildcards.
*
* @param {String} namespaces
* @api public
*/
function enable(namespaces) {
exports.save(namespaces);
exports.names = [];
exports.skips = [];
var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
var len = split.length;
for (var i = 0; i < len; i++) {
if (!split[i]) continue; // ignore empty strings
namespaces = split[i].replace(/\*/g, '.*?');
if (namespaces[0] === '-') {
exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
} else {
exports.names.push(new RegExp('^' + namespaces + '$'));
}
}
}
/**
* Disable debug output.
*
* @api public
*/
function disable() {
exports.enable('');
}
/**
* Returns true if the given mode name is enabled, false otherwise.
*
* @param {String} name
* @return {Boolean}
* @api public
*/
function enabled(name) {
var i, len;
for (i = 0, len = exports.skips.length; i < len; i++) {
if (exports.skips[i].test(name)) {
return false;
}
}
for (i = 0, len = exports.names.length; i < len; i++) {
if (exports.names[i].test(name)) {
return true;
}
}
return false;
}
/**
* Coerce `val`.
*
* @param {Mixed} val
* @return {Mixed}
* @api private
*/
function coerce(val) {
if (val instanceof Error) return val.stack || val.message;
return val;
}
},{"ms":434}],430:[function(require,module,exports){
/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
exports.read = function (buffer, offset, isLE, mLen, nBytes) {
var e, m
var eLen = (nBytes * 8) - mLen - 1
var eMax = (1 << eLen) - 1
var eBias = eMax >> 1
var nBits = -7
var i = isLE ? (nBytes - 1) : 0
var d = isLE ? -1 : 1
var s = buffer[offset + i]
i += d
e = s & ((1 << (-nBits)) - 1)
s >>= (-nBits)
nBits += eLen
for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
m = e & ((1 << (-nBits)) - 1)
e >>= (-nBits)
nBits += mLen
for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
if (e === 0) {
e = 1 - eBias
} else if (e === eMax) {
return m ? NaN : ((s ? -1 : 1) * Infinity)
} else {
m = m + Math.pow(2, mLen)
e = e - eBias
}
return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
}
exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
var e, m, c
var eLen = (nBytes * 8) - mLen - 1
var eMax = (1 << eLen) - 1
var eBias = eMax >> 1
var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
var i = isLE ? 0 : (nBytes - 1)
var d = isLE ? 1 : -1
var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
value = Math.abs(value)
if (isNaN(value) || value === Infinity) {
m = isNaN(value) ? 1 : 0
e = eMax
} else {
e = Math.floor(Math.log(value) / Math.LN2)
if (value * (c = Math.pow(2, -e)) < 1) {
e--
c *= 2
}
if (e + eBias >= 1) {
value += rt / c
} else {
value += rt * Math.pow(2, 1 - eBias)
}
if (value * c >= 2) {
e++
c /= 2
}
if (e + eBias >= eMax) {
m = 0
e = eMax
} else if (e + eBias >= 1) {
m = ((value * c) - 1) * Math.pow(2, mLen)
e = e + eBias
} else {
m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
e = 0
}
}
for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
e = (e << mLen) | m
eLen += mLen
for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
buffer[offset + i - d] |= s * 128
}
},{}],431:[function(require,module,exports){
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
if (superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
})
}
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
if (superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
}
},{}],432:[function(require,module,exports){
/*!
* Determine if an object is a Buffer
*
* @author Feross Aboukhadijeh <https://feross.org>
* @license MIT
*/
// The _isBuffer check is for Safari 5-7 support, because it's missing
// Object.prototype.constructor. Remove this eventually
module.exports = function (obj) {
return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
}
function isBuffer (obj) {
return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
}
// For Node v0.10 support. Remove this eventually.
function isSlowBuffer (obj) {
return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
}
},{}],433:[function(require,module,exports){
var toString = {}.toString;
module.exports = Array.isArray || function (arr) {
return toString.call(arr) == '[object Array]';
};
},{}],434:[function(require,module,exports){
/**
* Helpers.
*/
var s = 1000;
var m = s * 60;
var h = m * 60;
var d = h * 24;
var y = d * 365.25;
/**
* Parse or format the given `val`.
*
* Options:
*
* - `long` verbose formatting [false]
*
* @param {String|Number} val
* @param {Object} [options]
* @throws {Error} throw an error if val is not a non-empty string or a number
* @return {String|Number}
* @api public
*/
module.exports = function(val, options) {
options = options || {};
var type = typeof val;
if (type === 'string' && val.length > 0) {
return parse(val);
} else if (type === 'number' && isNaN(val) === false) {
return options.long ? fmtLong(val) : fmtShort(val);
}
throw new Error(
'val is not a non-empty string or a valid number. val=' +
JSON.stringify(val)
);
};
/**
* Parse the given `str` and return milliseconds.
*
* @param {String} str
* @return {Number}
* @api private
*/
function parse(str) {
str = String(str);
if (str.length > 100) {
return;
}
var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(
str
);
if (!match) {
return;
}
var n = parseFloat(match[1]);
var type = (match[2] || 'ms').toLowerCase();
switch (type) {
case 'years':
case 'year':
case 'yrs':
case 'yr':
case 'y':
return n * y;
case 'days':
case 'day':
case 'd':
return n * d;
case 'hours':
case 'hour':
case 'hrs':
case 'hr':
case 'h':
return n * h;
case 'minutes':
case 'minute':
case 'mins':
case 'min':
case 'm':
return n * m;
case 'seconds':
case 'second':
case 'secs':
case 'sec':
case 's':
return n * s;
case 'milliseconds':
case 'millisecond':
case 'msecs':
case 'msec':
case 'ms':
return n;
default:
return undefined;
}
}
/**
* Short format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtShort(ms) {
if (ms >= d) {
return Math.round(ms / d) + 'd';
}
if (ms >= h) {
return Math.round(ms / h) + 'h';
}
if (ms >= m) {
return Math.round(ms / m) + 'm';
}
if (ms >= s) {
return Math.round(ms / s) + 's';
}
return ms + 'ms';
}
/**
* Long format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtLong(ms) {
return plural(ms, d, 'day') ||
plural(ms, h, 'hour') ||
plural(ms, m, 'minute') ||
plural(ms, s, 'second') ||
ms + ' ms';
}
/**
* Pluralization helper.
*/
function plural(ms, n, name) {
if (ms < n) {
return;
}
if (ms < n * 1.5) {
return Math.floor(ms / n) + ' ' + name;
}
return Math.ceil(ms / n) + ' ' + name + 's';
}
},{}],435:[function(require,module,exports){
(function (process){(function (){
'use strict';
if (typeof process === 'undefined' ||
!process.version ||
process.version.indexOf('v0.') === 0 ||
process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
module.exports = { nextTick: nextTick };
} else {
module.exports = process
}
function nextTick(fn, arg1, arg2, arg3) {
if (typeof fn !== 'function') {
throw new TypeError('"callback" argument must be a function');
}
var len = arguments.length;
var args, i;
switch (len) {
case 0:
case 1:
return process.nextTick(fn);
case 2:
return process.nextTick(function afterTickOne() {
fn.call(null, arg1);
});
case 3:
return process.nextTick(function afterTickTwo() {
fn.call(null, arg1, arg2);
});
case 4:
return process.nextTick(function afterTickThree() {
fn.call(null, arg1, arg2, arg3);
});
default:
args = new Array(len - 1);
i = 0;
while (i < args.length) {
args[i++] = arguments[i];
}
return process.nextTick(function afterTick() {
fn.apply(null, args);
});
}
}
}).call(this)}).call(this,require('_process'))
},{"_process":436}],436:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
function defaultSetTimout() {
throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
throw new Error('clearTimeout has not been defined');
}
(function () {
try {
if (typeof setTimeout === 'function') {
cachedSetTimeout = setTimeout;
} else {
cachedSetTimeout = defaultSetTimout;
}
} catch (e) {
cachedSetTimeout = defaultSetTimout;
}
try {
if (typeof clearTimeout === 'function') {
cachedClearTimeout = clearTimeout;
} else {
cachedClearTimeout = defaultClearTimeout;
}
} catch (e) {
cachedClearTimeout = defaultClearTimeout;
}
} ())
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
}
// if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch(e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch(e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
}
// if clearTimeout wasn't available but was latter defined
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
runTimeout(drainQueue);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.prependListener = noop;
process.prependOnceListener = noop;
process.listeners = function (name) { return [] }
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
},{}],437:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
// a duplex stream is just a stream that is both readable and writable.
// Since JS doesn't have multiple prototypal inheritance, this class
// prototypally inherits from Readable, and then parasitically from
// Writable.
'use strict';
/*<replacement>*/
var pna = require('process-nextick-args');
/*</replacement>*/
/*<replacement>*/
var objectKeys = Object.keys || function (obj) {
var keys = [];
for (var key in obj) {
keys.push(key);
}return keys;
};
/*</replacement>*/
module.exports = Duplex;
/*<replacement>*/
var util = Object.create(require('core-util-is'));
util.inherits = require('inherits');
/*</replacement>*/
var Readable = require('./_stream_readable');
var Writable = require('./_stream_writable');
util.inherits(Duplex, Readable);
{
// avoid scope creep, the keys array can then be collected
var keys = objectKeys(Writable.prototype);
for (var v = 0; v < keys.length; v++) {
var method = keys[v];
if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
}
}
function Duplex(options) {
if (!(this instanceof Duplex)) return new Duplex(options);
Readable.call(this, options);
Writable.call(this, options);
if (options && options.readable === false) this.readable = false;
if (options && options.writable === false) this.writable = false;
this.allowHalfOpen = true;
if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
this.once('end', onend);
}
Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
// making it explicit this property is not enumerable
// because otherwise some prototype manipulation in
// userland will fail
enumerable: false,
get: function () {
return this._writableState.highWaterMark;
}
});
// the no-half-open enforcer
function onend() {
// if we allow half-open state, or if the writable side ended,
// then we're ok.
if (this.allowHalfOpen || this._writableState.ended) return;
// no more data can be written.
// But allow more writes to happen in this tick.
pna.nextTick(onEndNT, this);
}
function onEndNT(self) {
self.end();
}
Object.defineProperty(Duplex.prototype, 'destroyed', {
get: function () {
if (this._readableState === undefined || this._writableState === undefined) {
return false;
}
return this._readableState.destroyed && this._writableState.destroyed;
},
set: function (value) {
// we ignore the value if the stream
// has not been initialized yet
if (this._readableState === undefined || this._writableState === undefined) {
return;
}
// backward compatibility, the user is explicitly
// managing destroyed
this._readableState.destroyed = value;
this._writableState.destroyed = value;
}
});
Duplex.prototype._destroy = function (err, cb) {
this.push(null);
this.end();
pna.nextTick(cb, err);
};
},{"./_stream_readable":439,"./_stream_writable":441,"core-util-is":427,"inherits":431,"process-nextick-args":435}],438:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
// a passthrough stream.
// basically just the most minimal sort of Transform stream.
// Every written chunk gets output as-is.
'use strict';
module.exports = PassThrough;
var Transform = require('./_stream_transform');
/*<replacement>*/
var util = Object.create(require('core-util-is'));
util.inherits = require('inherits');
/*</replacement>*/
util.inherits(PassThrough, Transform);
function PassThrough(options) {
if (!(this instanceof PassThrough)) return new PassThrough(options);
Transform.call(this, options);
}
PassThrough.prototype._transform = function (chunk, encoding, cb) {
cb(null, chunk);
};
},{"./_stream_transform":440,"core-util-is":427,"inherits":431}],439:[function(require,module,exports){
(function (process,global){(function (){
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
'use strict';
/*<replacement>*/
var pna = require('process-nextick-args');
/*</replacement>*/
module.exports = Readable;
/*<replacement>*/
var isArray = require('isarray');
/*</replacement>*/
/*<replacement>*/
var Duplex;
/*</replacement>*/
Readable.ReadableState = ReadableState;
/*<replacement>*/
var EE = require('events').EventEmitter;
var EElistenerCount = function (emitter, type) {
return emitter.listeners(type).length;
};
/*</replacement>*/
/*<replacement>*/
var Stream = require('./internal/streams/stream');
/*</replacement>*/
/*<replacement>*/
var Buffer = require('safe-buffer').Buffer;
var OurUint8Array = global.Uint8Array || function () {};
function _uint8ArrayToBuffer(chunk) {
return Buffer.from(chunk);
}
function _isUint8Array(obj) {
return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
}
/*</replacement>*/
/*<replacement>*/
var util = Object.create(require('core-util-is'));
util.inherits = require('inherits');
/*</replacement>*/
/*<replacement>*/
var debugUtil = require('util');
var debug = void 0;
if (debugUtil && debugUtil.debuglog) {
debug = debugUtil.debuglog('stream');
} else {
debug = function () {};
}
/*</replacement>*/
var BufferList = require('./internal/streams/BufferList');
var destroyImpl = require('./internal/streams/destroy');
var StringDecoder;
util.inherits(Readable, Stream);
var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
function prependListener(emitter, event, fn) {
// Sadly this is not cacheable as some libraries bundle their own
// event emitter implementation with them.
if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);
// This is a hack to make sure that our error handler is attached before any
// userland ones. NEVER DO THIS. This is here only because this code needs
// to continue to work with older versions of Node.js that do not include
// the prependListener() method. The goal is to eventually remove this hack.
if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
}
function ReadableState(options, stream) {
Duplex = Duplex || require('./_stream_duplex');
options = options || {};
// Duplex streams are both readable and writable, but share
// the same options object.
// However, some cases require setting options to different
// values for the readable and the writable sides of the duplex stream.
// These options can be provided separately as readableXXX and writableXXX.
var isDuplex = stream instanceof Duplex;
// object stream flag. Used to make read(n) ignore n and to
// make all the buffer merging and length checks go away
this.objectMode = !!options.objectMode;
if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
// the point at which it stops calling _read() to fill the buffer
// Note: 0 is a valid value, means "don't call _read preemptively ever"
var hwm = options.highWaterMark;
var readableHwm = options.readableHighWaterMark;
var defaultHwm = this.objectMode ? 16 : 16 * 1024;
if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm;
// cast to ints.
this.highWaterMark = Math.floor(this.highWaterMark);
// A linked list is used to store data chunks instead of an array because the
// linked list can remove elements from the beginning faster than
// array.shift()
this.buffer = new BufferList();
this.length = 0;
this.pipes = null;
this.pipesCount = 0;
this.flowing = null;
this.ended = false;
this.endEmitted = false;
this.reading = false;
// a flag to be able to tell if the event 'readable'/'data' is emitted
// immediately, or on a later tick. We set this to true at first, because
// any actions that shouldn't happen until "later" should generally also
// not happen before the first read call.
this.sync = true;
// whenever we return null, then we set a flag to say
// that we're awaiting a 'readable' event emission.
this.needReadable = false;
this.emittedReadable = false;
this.readableListening = false;
this.resumeScheduled = false;
// has it been destroyed
this.destroyed = false;
// Crypto is kind of old and crusty. Historically, its default string
// encoding is 'binary' so we have to make this configurable.
// Everything else in the universe uses 'utf8', though.
this.defaultEncoding = options.defaultEncoding || 'utf8';
// the number of writers that are awaiting a drain event in .pipe()s
this.awaitDrain = 0;
// if true, a maybeReadMore has been scheduled
this.readingMore = false;
this.decoder = null;
this.encoding = null;
if (options.encoding) {
if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
this.decoder = new StringDecoder(options.encoding);
this.encoding = options.encoding;
}
}
function Readable(options) {
Duplex = Duplex || require('./_stream_duplex');
if (!(this instanceof Readable)) return new Readable(options);
this._readableState = new ReadableState(options, this);
// legacy
this.readable = true;
if (options) {
if (typeof options.read === 'function') this._read = options.read;
if (typeof options.destroy === 'function') this._destroy = options.destroy;
}
Stream.call(this);
}
Object.defineProperty(Readable.prototype, 'destroyed', {
get: function () {
if (this._readableState === undefined) {
return false;
}
return this._readableState.destroyed;
},
set: function (value) {
// we ignore the value if the stream
// has not been initialized yet
if (!this._readableState) {
return;
}
// backward compatibility, the user is explicitly
// managing destroyed
this._readableState.destroyed = value;
}
});
Readable.prototype.destroy = destroyImpl.destroy;
Readable.prototype._undestroy = destroyImpl.undestroy;
Readable.prototype._destroy = function (err, cb) {
this.push(null);
cb(err);
};
// Manually shove something into the read() buffer.
// This returns true if the highWaterMark has not been hit yet,
// similar to how Writable.write() returns true if you should
// write() some more.
Readable.prototype.push = function (chunk, encoding) {
var state = this._readableState;
var skipChunkCheck;
if (!state.objectMode) {
if (typeof chunk === 'string') {
encoding = encoding || state.defaultEncoding;
if (encoding !== state.encoding) {
chunk = Buffer.from(chunk, encoding);
encoding = '';
}
skipChunkCheck = true;
}
} else {
skipChunkCheck = true;
}
return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
};
// Unshift should *always* be something directly out of read()
Readable.prototype.unshift = function (chunk) {
return readableAddChunk(this, chunk, null, true, false);
};
function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
var state = stream._readableState;
if (chunk === null) {
state.reading = false;
onEofChunk(stream, state);
} else {
var er;
if (!skipChunkCheck) er = chunkInvalid(state, chunk);
if (er) {
stream.emit('error', er);
} else if (state.objectMode || chunk && chunk.length > 0) {
if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
chunk = _uint8ArrayToBuffer(chunk);
}
if (addToFront) {
if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);
} else if (state.ended) {
stream.emit('error', new Error('stream.push() after EOF'));
} else {
state.reading = false;
if (state.decoder && !encoding) {
chunk = state.decoder.write(chunk);
if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
} else {
addChunk(stream, state, chunk, false);
}
}
} else if (!addToFront) {
state.reading = false;
}
}
return needMoreData(state);
}
function addChunk(stream, state, chunk, addToFront) {
if (state.flowing && state.length === 0 && !state.sync) {
stream.emit('data', chunk);
stream.read(0);
} else {
// update the buffer info.
state.length += state.objectMode ? 1 : chunk.length;
if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
if (state.needReadable) emitReadable(stream);
}
maybeReadMore(stream, state);
}
function chunkInvalid(state, chunk) {
var er;
if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
er = new TypeError('Invalid non-string/buffer chunk');
}
return er;
}
// if it's past the high water mark, we can push in some more.
// Also, if we have no data yet, we can stand some
// more bytes. This is to work around cases where hwm=0,
// such as the repl. Also, if the push() triggered a
// readable event, and the user called read(largeNumber) such that
// needReadable was set, then we ought to push more, so that another
// 'readable' event will be triggered.
function needMoreData(state) {
return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
}
Readable.prototype.isPaused = function () {
return this._readableState.flowing === false;
};
// backwards compatibility.
Readable.prototype.setEncoding = function (enc) {
if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
this._readableState.decoder = new StringDecoder(enc);
this._readableState.encoding = enc;
return this;
};
// Don't raise the hwm > 8MB
var MAX_HWM = 0x800000;
function computeNewHighWaterMark(n) {
if (n >= MAX_HWM) {
n = MAX_HWM;
} else {
// Get the next highest power of 2 to prevent increasing hwm excessively in
// tiny amounts
n--;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
n++;
}
return n;
}
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function howMuchToRead(n, state) {
if (n <= 0 || state.length === 0 && state.ended) return 0;
if (state.objectMode) return 1;
if (n !== n) {
// Only flow one buffer at a time
if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
}
// If we're asking for more than the current hwm, then raise the hwm.
if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
if (n <= state.length) return n;
// Don't have enough
if (!state.ended) {
state.needReadable = true;
return 0;
}
return state.length;
}
// you can override either this method, or the async _read(n) below.
Readable.prototype.read = function (n) {
debug('read', n);
n = parseInt(n, 10);
var state = this._readableState;
var nOrig = n;
if (n !== 0) state.emittedReadable = false;
// if we're doing read(0) to trigger a readable event, but we
// already have a bunch of data in the buffer, then just trigger
// the 'readable' event and move on.
if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
debug('read: emitReadable', state.length, state.ended);
if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
return null;
}
n = howMuchToRead(n, state);
// if we've ended, and we're now clear, then finish it up.
if (n === 0 && state.ended) {
if (state.length === 0) endReadable(this);
return null;
}
// All the actual chunk generation logic needs to be
// *below* the call to _read. The reason is that in certain
// synthetic stream cases, such as passthrough streams, _read
// may be a completely synchronous operation which may change
// the state of the read buffer, providing enough data when
// before there was *not* enough.
//
// So, the steps are:
// 1. Figure out what the state of things will be after we do
// a read from the buffer.
//
// 2. If that resulting state will trigger a _read, then call _read.
// Note that this may be asynchronous, or synchronous. Yes, it is
// deeply ugly to write APIs this way, but that still doesn't mean
// that the Readable class should behave improperly, as streams are
// designed to be sync/async agnostic.
// Take note if the _read call is sync or async (ie, if the read call
// has returned yet), so that we know whether or not it's safe to emit
// 'readable' etc.
//
// 3. Actually pull the requested chunks out of the buffer and return.
// if we need a readable event, then we need to do some reading.
var doRead = state.needReadable;
debug('need readable', doRead);
// if we currently have less than the highWaterMark, then also read some
if (state.length === 0 || state.length - n < state.highWaterMark) {
doRead = true;
debug('length less than watermark', doRead);
}
// however, if we've ended, then there's no point, and if we're already
// reading, then it's unnecessary.
if (state.ended || state.reading) {
doRead = false;
debug('reading or ended', doRead);
} else if (doRead) {
debug('do read');
state.reading = true;
state.sync = true;
// if the length is currently zero, then we *need* a readable event.
if (state.length === 0) state.needReadable = true;
// call internal read method
this._read(state.highWaterMark);
state.sync = false;
// If _read pushed data synchronously, then `reading` will be false,
// and we need to re-evaluate how much data we can return to the user.
if (!state.reading) n = howMuchToRead(nOrig, state);
}
var ret;
if (n > 0) ret = fromList(n, state);else ret = null;
if (ret === null) {
state.needReadable = true;
n = 0;
} else {
state.length -= n;
}
if (state.length === 0) {
// If we have nothing in the buffer, then we want to know
// as soon as we *do* get something into the buffer.
if (!state.ended) state.needReadable = true;
// If we tried to read() past the EOF, then emit end on the next tick.
if (nOrig !== n && state.ended) endReadable(this);
}
if (ret !== null) this.emit('data', ret);
return ret;
};
function onEofChunk(stream, state) {
if (state.ended) return;
if (state.decoder) {
var chunk = state.decoder.end();
if (chunk && chunk.length) {
state.buffer.push(chunk);
state.length += state.objectMode ? 1 : chunk.length;
}
}
state.ended = true;
// emit 'readable' now to make sure it gets picked up.
emitReadable(stream);
}
// Don't emit readable right away in sync mode, because this can trigger
// another read() call => stack overflow. This way, it might trigger
// a nextTick recursion warning, but that's not so bad.
function emitReadable(stream) {
var state = stream._readableState;
state.needReadable = false;
if (!state.emittedReadable) {
debug('emitReadable', state.flowing);
state.emittedReadable = true;
if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream);
}
}
function emitReadable_(stream) {
debug('emit readable');
stream.emit('readable');
flow(stream);
}
// at this point, the user has presumably seen the 'readable' event,
// and called read() to consume some data. that may have triggered
// in turn another _read(n) call, in which case reading = true if
// it's in progress.
// However, if we're not ended, or reading, and the length < hwm,
// then go ahead and try to read some more preemptively.
function maybeReadMore(stream, state) {
if (!state.readingMore) {
state.readingMore = true;
pna.nextTick(maybeReadMore_, stream, state);
}
}
function maybeReadMore_(stream, state) {
var len = state.length;
while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
debug('maybeReadMore read 0');
stream.read(0);
if (len === state.length)
// didn't get any data, stop spinning.
break;else len = state.length;
}
state.readingMore = false;
}
// abstract method. to be overridden in specific implementation classes.
// call cb(er, data) where data is <= n in length.
// for virtual (non-string, non-buffer) streams, "length" is somewhat
// arbitrary, and perhaps not very meaningful.
Readable.prototype._read = function (n) {
this.emit('error', new Error('_read() is not implemented'));
};
Readable.prototype.pipe = function (dest, pipeOpts) {
var src = this;
var state = this._readableState;
switch (state.pipesCount) {
case 0:
state.pipes = dest;
break;
case 1:
state.pipes = [state.pipes, dest];
break;
default:
state.pipes.push(dest);
break;
}
state.pipesCount += 1;
debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
var endFn = doEnd ? onend : unpipe;
if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn);
dest.on('unpipe', onunpipe);
function onunpipe(readable, unpipeInfo) {
debug('onunpipe');
if (readable === src) {
if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
unpipeInfo.hasUnpiped = true;
cleanup();
}
}
}
function onend() {
debug('onend');
dest.end();
}
// when the dest drains, it reduces the awaitDrain counter
// on the source. This would be more elegant with a .once()
// handler in flow(), but adding and removing repeatedly is
// too slow.
var ondrain = pipeOnDrain(src);
dest.on('drain', ondrain);
var cleanedUp = false;
function cleanup() {
debug('cleanup');
// cleanup event handlers once the pipe is broken
dest.removeListener('close', onclose);
dest.removeListener('finish', onfinish);
dest.removeListener('drain', ondrain);
dest.removeListener('error', onerror);
dest.removeListener('unpipe', onunpipe);
src.removeListener('end', onend);
src.removeListener('end', unpipe);
src.removeListener('data', ondata);
cleanedUp = true;
// if the reader is waiting for a drain event from this
// specific writer, then it would cause it to never start
// flowing again.
// So, if this is awaiting a drain, then we just call it now.
// If we don't know, then assume that we are waiting for one.
if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
}
// If the user pushes more data while we're writing to dest then we'll end up
// in ondata again. However, we only want to increase awaitDrain once because
// dest will only emit one 'drain' event for the multiple writes.
// => Introduce a guard on increasing awaitDrain.
var increasedAwaitDrain = false;
src.on('data', ondata);
function ondata(chunk) {
debug('ondata');
increasedAwaitDrain = false;
var ret = dest.write(chunk);
if (false === ret && !increasedAwaitDrain) {
// If the user unpiped during `dest.write()`, it is possible
// to get stuck in a permanently paused state if that write
// also returned false.
// => Check whether `dest` is still a piping destination.
if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
debug('false write response, pause', src._readableState.awaitDrain);
src._readableState.awaitDrain++;
increasedAwaitDrain = true;
}
src.pause();
}
}
// if the dest has an error, then stop piping into it.
// however, don't suppress the throwing behavior for this.
function onerror(er) {
debug('onerror', er);
unpipe();
dest.removeListener('error', onerror);
if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
}
// Make sure our error handler is attached before userland ones.
prependListener(dest, 'error', onerror);
// Both close and finish should trigger unpipe, but only once.
function onclose() {
dest.removeListener('finish', onfinish);
unpipe();
}
dest.once('close', onclose);
function onfinish() {
debug('onfinish');
dest.removeListener('close', onclose);
unpipe();
}
dest.once('finish', onfinish);
function unpipe() {
debug('unpipe');
src.unpipe(dest);
}
// tell the dest that it's being piped to
dest.emit('pipe', src);
// start the flow if it hasn't been started already.
if (!state.flowing) {
debug('pipe resume');
src.resume();
}
return dest;
};
function pipeOnDrain(src) {
return function () {
var state = src._readableState;
debug('pipeOnDrain', state.awaitDrain);
if (state.awaitDrain) state.awaitDrain--;
if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
state.flowing = true;
flow(src);
}
};
}
Readable.prototype.unpipe = function (dest) {
var state = this._readableState;
var unpipeInfo = { hasUnpiped: false };
// if we're not piping anywhere, then do nothing.
if (state.pipesCount === 0) return this;
// just one destination. most common case.
if (state.pipesCount === 1) {
// passed in one, but it's not the right one.
if (dest && dest !== state.pipes) return this;
if (!dest) dest = state.pipes;
// got a match.
state.pipes = null;
state.pipesCount = 0;
state.flowing = false;
if (dest) dest.emit('unpipe', this, unpipeInfo);
return this;
}
// slow case. multiple pipe destinations.
if (!dest) {
// remove all.
var dests = state.pipes;
var len = state.pipesCount;
state.pipes = null;
state.pipesCount = 0;
state.flowing = false;
for (var i = 0; i < len; i++) {
dests[i].emit('unpipe', this, unpipeInfo);
}return this;
}
// try to find the right one.
var index = indexOf(state.pipes, dest);
if (index === -1) return this;
state.pipes.splice(index, 1);
state.pipesCount -= 1;
if (state.pipesCount === 1) state.pipes = state.pipes[0];
dest.emit('unpipe', this, unpipeInfo);
return this;
};
// set up data events if they are asked for
// Ensure readable listeners eventually get something
Readable.prototype.on = function (ev, fn) {
var res = Stream.prototype.on.call(this, ev, fn);
if (ev === 'data') {
// Start flowing on next tick if stream isn't explicitly paused
if (this._readableState.flowing !== false) this.resume();
} else if (ev === 'readable') {
var state = this._readableState;
if (!state.endEmitted && !state.readableListening) {
state.readableListening = state.needReadable = true;
state.emittedReadable = false;
if (!state.reading) {
pna.nextTick(nReadingNextTick, this);
} else if (state.length) {
emitReadable(this);
}
}
}
return res;
};
Readable.prototype.addListener = Readable.prototype.on;
function nReadingNextTick(self) {
debug('readable nexttick read 0');
self.read(0);
}
// pause() and resume() are remnants of the legacy readable stream API
// If the user uses them, then switch into old mode.
Readable.prototype.resume = function () {
var state = this._readableState;
if (!state.flowing) {
debug('resume');
state.flowing = true;
resume(this, state);
}
return this;
};
function resume(stream, state) {
if (!state.resumeScheduled) {
state.resumeScheduled = true;
pna.nextTick(resume_, stream, state);
}
}
function resume_(stream, state) {
if (!state.reading) {
debug('resume read 0');
stream.read(0);
}
state.resumeScheduled = false;
state.awaitDrain = 0;
stream.emit('resume');
flow(stream);
if (state.flowing && !state.reading) stream.read(0);
}
Readable.prototype.pause = function () {
debug('call pause flowing=%j', this._readableState.flowing);
if (false !== this._readableState.flowing) {
debug('pause');
this._readableState.flowing = false;
this.emit('pause');
}
return this;
};
function flow(stream) {
var state = stream._readableState;
debug('flow', state.flowing);
while (state.flowing && stream.read() !== null) {}
}
// wrap an old-style stream as the async data source.
// This is *not* part of the readable stream interface.
// It is an ugly unfortunate mess of history.
Readable.prototype.wrap = function (stream) {
var _this = this;
var state = this._readableState;
var paused = false;
stream.on('end', function () {
debug('wrapped end');
if (state.decoder && !state.ended) {
var chunk = state.decoder.end();
if (chunk && chunk.length) _this.push(chunk);
}
_this.push(null);
});
stream.on('data', function (chunk) {
debug('wrapped data');
if (state.decoder) chunk = state.decoder.write(chunk);
// don't skip over falsy values in objectMode
if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
var ret = _this.push(chunk);
if (!ret) {
paused = true;
stream.pause();
}
});
// proxy all the other methods.
// important when wrapping filters and duplexes.
for (var i in stream) {
if (this[i] === undefined && typeof stream[i] === 'function') {
this[i] = function (method) {
return function () {
return stream[method].apply(stream, arguments);
};
}(i);
}
}
// proxy certain important events.
for (var n = 0; n < kProxyEvents.length; n++) {
stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
}
// when we try to consume some more bytes, simply unpause the
// underlying stream.
this._read = function (n) {
debug('wrapped _read', n);
if (paused) {
paused = false;
stream.resume();
}
};
return this;
};
Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
// making it explicit this property is not enumerable
// because otherwise some prototype manipulation in
// userland will fail
enumerable: false,
get: function () {
return this._readableState.highWaterMark;
}
});
// exposed for testing purposes only.
Readable._fromList = fromList;
// Pluck off n bytes from an array of buffers.
// Length is the combined lengths of all the buffers in the list.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function fromList(n, state) {
// nothing buffered
if (state.length === 0) return null;
var ret;
if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
// read it all, truncate the list
if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length);
state.buffer.clear();
} else {
// read part of list
ret = fromListPartial(n, state.buffer, state.decoder);
}
return ret;
}
// Extracts only enough buffered data to satisfy the amount requested.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function fromListPartial(n, list, hasStrings) {
var ret;
if (n < list.head.data.length) {
// slice is the same for buffers and strings
ret = list.head.data.slice(0, n);
list.head.data = list.head.data.slice(n);
} else if (n === list.head.data.length) {
// first chunk is a perfect match
ret = list.shift();
} else {
// result spans more than one buffer
ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
}
return ret;
}
// Copies a specified amount of characters from the list of buffered data
// chunks.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function copyFromBufferString(n, list) {
var p = list.head;
var c = 1;
var ret = p.data;
n -= ret.length;
while (p = p.next) {
var str = p.data;
var nb = n > str.length ? str.length : n;
if (nb === str.length) ret += str;else ret += str.slice(0, n);
n -= nb;
if (n === 0) {
if (nb === str.length) {
++c;
if (p.next) list.head = p.next;else list.head = list.tail = null;
} else {
list.head = p;
p.data = str.slice(nb);
}
break;
}
++c;
}
list.length -= c;
return ret;
}
// Copies a specified amount of bytes from the list of buffered data chunks.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function copyFromBuffer(n, list) {
var ret = Buffer.allocUnsafe(n);
var p = list.head;
var c = 1;
p.data.copy(ret);
n -= p.data.length;
while (p = p.next) {
var buf = p.data;
var nb = n > buf.length ? buf.length : n;
buf.copy(ret, ret.length - n, 0, nb);
n -= nb;
if (n === 0) {
if (nb === buf.length) {
++c;
if (p.next) list.head = p.next;else list.head = list.tail = null;
} else {
list.head = p;
p.data = buf.slice(nb);
}
break;
}
++c;
}
list.length -= c;
return ret;
}
function endReadable(stream) {
var state = stream._readableState;
// If we get here before consuming all the bytes, then that is a
// bug in node. Should never happen.
if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
if (!state.endEmitted) {
state.ended = true;
pna.nextTick(endReadableNT, state, stream);
}
}
function endReadableNT(state, stream) {
// Check that we didn't get one last unshift.
if (!state.endEmitted && state.length === 0) {
state.endEmitted = true;
stream.readable = false;
stream.emit('end');
}
}
function indexOf(xs, x) {
for (var i = 0, l = xs.length; i < l; i++) {
if (xs[i] === x) return i;
}
return -1;
}
}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./_stream_duplex":437,"./internal/streams/BufferList":442,"./internal/streams/destroy":443,"./internal/streams/stream":444,"_process":436,"core-util-is":427,"events":425,"inherits":431,"isarray":433,"process-nextick-args":435,"safe-buffer":446,"string_decoder/":447,"util":424}],440:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
// a transform stream is a readable/writable stream where you do
// something with the data. Sometimes it's called a "filter",
// but that's not a great name for it, since that implies a thing where
// some bits pass through, and others are simply ignored. (That would
// be a valid example of a transform, of course.)
//
// While the output is causally related to the input, it's not a
// necessarily symmetric or synchronous transformation. For example,
// a zlib stream might take multiple plain-text writes(), and then
// emit a single compressed chunk some time in the future.
//
// Here's how this works:
//
// The Transform stream has all the aspects of the readable and writable
// stream classes. When you write(chunk), that calls _write(chunk,cb)
// internally, and returns false if there's a lot of pending writes
// buffered up. When you call read(), that calls _read(n) until
// there's enough pending readable data buffered up.
//
// In a transform stream, the written data is placed in a buffer. When
// _read(n) is called, it transforms the queued up data, calling the
// buffered _write cb's as it consumes chunks. If consuming a single
// written chunk would result in multiple output chunks, then the first
// outputted bit calls the readcb, and subsequent chunks just go into
// the read buffer, and will cause it to emit 'readable' if necessary.
//
// This way, back-pressure is actually determined by the reading side,
// since _read has to be called to start processing a new chunk. However,
// a pathological inflate type of transform can cause excessive buffering
// here. For example, imagine a stream where every byte of input is
// interpreted as an integer from 0-255, and then results in that many
// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
// 1kb of data being output. In this case, you could write a very small
// amount of input, and end up with a very large amount of output. In
// such a pathological inflating mechanism, there'd be no way to tell
// the system to stop doing the transform. A single 4MB write could
// cause the system to run out of memory.
//
// However, even in such a pathological case, only a single written chunk
// would be consumed, and then the rest would wait (un-transformed) until
// the results of the previous transformed chunk were consumed.
'use strict';
module.exports = Transform;
var Duplex = require('./_stream_duplex');
/*<replacement>*/
var util = Object.create(require('core-util-is'));
util.inherits = require('inherits');
/*</replacement>*/
util.inherits(Transform, Duplex);
function afterTransform(er, data) {
var ts = this._transformState;
ts.transforming = false;
var cb = ts.writecb;
if (!cb) {
return this.emit('error', new Error('write callback called multiple times'));
}
ts.writechunk = null;
ts.writecb = null;
if (data != null) // single equals check for both `null` and `undefined`
this.push(data);
cb(er);
var rs = this._readableState;
rs.reading = false;
if (rs.needReadable || rs.length < rs.highWaterMark) {
this._read(rs.highWaterMark);
}
}
function Transform(options) {
if (!(this instanceof Transform)) return new Transform(options);
Duplex.call(this, options);
this._transformState = {
afterTransform: afterTransform.bind(this),
needTransform: false,
transforming: false,
writecb: null,
writechunk: null,
writeencoding: null
};
// start out asking for a readable event once data is transformed.
this._readableState.needReadable = true;
// we have implemented the _read method, and done the other things
// that Readable wants before the first _read call, so unset the
// sync guard flag.
this._readableState.sync = false;
if (options) {
if (typeof options.transform === 'function') this._transform = options.transform;
if (typeof options.flush === 'function') this._flush = options.flush;
}
// When the writable side finishes, then flush out anything remaining.
this.on('prefinish', prefinish);
}
function prefinish() {
var _this = this;
if (typeof this._flush === 'function') {
this._flush(function (er, data) {
done(_this, er, data);
});
} else {
done(this, null, null);
}
}
Transform.prototype.push = function (chunk, encoding) {
this._transformState.needTransform = false;
return Duplex.prototype.push.call(this, chunk, encoding);
};
// This is the part where you do stuff!
// override this function in implementation classes.
// 'chunk' is an input chunk.
//
// Call `push(newChunk)` to pass along transformed output
// to the readable side. You may call 'push' zero or more times.
//
// Call `cb(err)` when you are done with this chunk. If you pass
// an error, then that'll put the hurt on the whole operation. If you
// never call cb(), then you'll never get another chunk.
Transform.prototype._transform = function (chunk, encoding, cb) {
throw new Error('_transform() is not implemented');
};
Transform.prototype._write = function (chunk, encoding, cb) {
var ts = this._transformState;
ts.writecb = cb;
ts.writechunk = chunk;
ts.writeencoding = encoding;
if (!ts.transforming) {
var rs = this._readableState;
if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
}
};
// Doesn't matter what the args are here.
// _transform does all the work.
// That we got here means that the readable side wants more data.
Transform.prototype._read = function (n) {
var ts = this._transformState;
if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
ts.transforming = true;
this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
} else {
// mark that we need a transform, so that any data that comes in
// will get processed, now that we've asked for it.
ts.needTransform = true;
}
};
Transform.prototype._destroy = function (err, cb) {
var _this2 = this;
Duplex.prototype._destroy.call(this, err, function (err2) {
cb(err2);
_this2.emit('close');
});
};
function done(stream, er, data) {
if (er) return stream.emit('error', er);
if (data != null) // single equals check for both `null` and `undefined`
stream.push(data);
// if there's nothing in the write buffer, then that means
// that nothing more will ever be provided
if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0');
if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming');
return stream.push(null);
}
},{"./_stream_duplex":437,"core-util-is":427,"inherits":431}],441:[function(require,module,exports){
(function (process,global,setImmediate){(function (){
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
// A bit simpler than readable streams.
// Implement an async ._write(chunk, encoding, cb), and it'll handle all
// the drain event emission and buffering.
'use strict';
/*<replacement>*/
var pna = require('process-nextick-args');
/*</replacement>*/
module.exports = Writable;
/* <replacement> */
function WriteReq(chunk, encoding, cb) {
this.chunk = chunk;
this.encoding = encoding;
this.callback = cb;
this.next = null;
}
// It seems a linked list but it is not
// there will be only 2 of these for each stream
function CorkedRequest(state) {
var _this = this;
this.next = null;
this.entry = null;
this.finish = function () {
onCorkedFinish(_this, state);
};
}
/* </replacement> */
/*<replacement>*/
var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick;
/*</replacement>*/
/*<replacement>*/
var Duplex;
/*</replacement>*/
Writable.WritableState = WritableState;
/*<replacement>*/
var util = Object.create(require('core-util-is'));
util.inherits = require('inherits');
/*</replacement>*/
/*<replacement>*/
var internalUtil = {
deprecate: require('util-deprecate')
};
/*</replacement>*/
/*<replacement>*/
var Stream = require('./internal/streams/stream');
/*</replacement>*/
/*<replacement>*/
var Buffer = require('safe-buffer').Buffer;
var OurUint8Array = global.Uint8Array || function () {};
function _uint8ArrayToBuffer(chunk) {
return Buffer.from(chunk);
}
function _isUint8Array(obj) {
return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
}
/*</replacement>*/
var destroyImpl = require('./internal/streams/destroy');
util.inherits(Writable, Stream);
function nop() {}
function WritableState(options, stream) {
Duplex = Duplex || require('./_stream_duplex');
options = options || {};
// Duplex streams are both readable and writable, but share
// the same options object.
// However, some cases require setting options to different
// values for the readable and the writable sides of the duplex stream.
// These options can be provided separately as readableXXX and writableXXX.
var isDuplex = stream instanceof Duplex;
// object stream flag to indicate whether or not this stream
// contains buffers or objects.
this.objectMode = !!options.objectMode;
if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
// the point at which write() starts returning false
// Note: 0 is a valid value, means that we always return false if
// the entire buffer is not flushed immediately on write()
var hwm = options.highWaterMark;
var writableHwm = options.writableHighWaterMark;
var defaultHwm = this.objectMode ? 16 : 16 * 1024;
if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm;
// cast to ints.
this.highWaterMark = Math.floor(this.highWaterMark);
// if _final has been called
this.finalCalled = false;
// drain event flag.
this.needDrain = false;
// at the start of calling end()
this.ending = false;
// when end() has been called, and returned
this.ended = false;
// when 'finish' is emitted
this.finished = false;
// has it been destroyed
this.destroyed = false;
// should we decode strings into buffers before passing to _write?
// this is here so that some node-core streams can optimize string
// handling at a lower level.
var noDecode = options.decodeStrings === false;
this.decodeStrings = !noDecode;
// Crypto is kind of old and crusty. Historically, its default string
// encoding is 'binary' so we have to make this configurable.
// Everything else in the universe uses 'utf8', though.
this.defaultEncoding = options.defaultEncoding || 'utf8';
// not an actual buffer we keep track of, but a measurement
// of how much we're waiting to get pushed to some underlying
// socket or file.
this.length = 0;
// a flag to see when we're in the middle of a write.
this.writing = false;
// when true all writes will be buffered until .uncork() call
this.corked = 0;
// a flag to be able to tell if the onwrite cb is called immediately,
// or on a later tick. We set this to true at first, because any
// actions that shouldn't happen until "later" should generally also
// not happen before the first write call.
this.sync = true;
// a flag to know if we're processing previously buffered items, which
// may call the _write() callback in the same tick, so that we don't
// end up in an overlapped onwrite situation.
this.bufferProcessing = false;
// the callback that's passed to _write(chunk,cb)
this.onwrite = function (er) {
onwrite(stream, er);
};
// the callback that the user supplies to write(chunk,encoding,cb)
this.writecb = null;
// the amount that is being written when _write is called.
this.writelen = 0;
this.bufferedRequest = null;
this.lastBufferedRequest = null;
// number of pending user-supplied write callbacks
// this must be 0 before 'finish' can be emitted
this.pendingcb = 0;
// emit prefinish if the only thing we're waiting for is _write cbs
// This is relevant for synchronous Transform streams
this.prefinished = false;
// True if the error was already emitted and should not be thrown again
this.errorEmitted = false;
// count buffered requests
this.bufferedRequestCount = 0;
// allocate the first CorkedRequest, there is always
// one allocated and free to use, and we maintain at most two
this.corkedRequestsFree = new CorkedRequest(this);
}
WritableState.prototype.getBuffer = function getBuffer() {
var current = this.bufferedRequest;
var out = [];
while (current) {
out.push(current);
current = current.next;
}
return out;
};
(function () {
try {
Object.defineProperty(WritableState.prototype, 'buffer', {
get: internalUtil.deprecate(function () {
return this.getBuffer();
}, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
});
} catch (_) {}
})();
// Test _writableState for inheritance to account for Duplex streams,
// whose prototype chain only points to Readable.
var realHasInstance;
if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
realHasInstance = Function.prototype[Symbol.hasInstance];
Object.defineProperty(Writable, Symbol.hasInstance, {
value: function (object) {
if (realHasInstance.call(this, object)) return true;
if (this !== Writable) return false;
return object && object._writableState instanceof WritableState;
}
});
} else {
realHasInstance = function (object) {
return object instanceof this;
};
}
function Writable(options) {
Duplex = Duplex || require('./_stream_duplex');
// Writable ctor is applied to Duplexes, too.
// `realHasInstance` is necessary because using plain `instanceof`
// would return false, as no `_writableState` property is attached.
// Trying to use the custom `instanceof` for Writable here will also break the
// Node.js LazyTransform implementation, which has a non-trivial getter for
// `_writableState` that would lead to infinite recursion.
if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
return new Writable(options);
}
this._writableState = new WritableState(options, this);
// legacy.
this.writable = true;
if (options) {
if (typeof options.write === 'function') this._write = options.write;
if (typeof options.writev === 'function') this._writev = options.writev;
if (typeof options.destroy === 'function') this._destroy = options.destroy;
if (typeof options.final === 'function') this._final = options.final;
}
Stream.call(this);
}
// Otherwise people can pipe Writable streams, which is just wrong.
Writable.prototype.pipe = function () {
this.emit('error', new Error('Cannot pipe, not readable'));
};
function writeAfterEnd(stream, cb) {
var er = new Error('write after end');
// TODO: defer error events consistently everywhere, not just the cb
stream.emit('error', er);
pna.nextTick(cb, er);
}
// Checks that a user-supplied chunk is valid, especially for the particular
// mode the stream is in. Currently this means that `null` is never accepted
// and undefined/non-string values are only allowed in object mode.
function validChunk(stream, state, chunk, cb) {
var valid = true;
var er = false;
if (chunk === null) {
er = new TypeError('May not write null values to stream');
} else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
er = new TypeError('Invalid non-string/buffer chunk');
}
if (er) {
stream.emit('error', er);
pna.nextTick(cb, er);
valid = false;
}
return valid;
}
Writable.prototype.write = function (chunk, encoding, cb) {
var state = this._writableState;
var ret = false;
var isBuf = !state.objectMode && _isUint8Array(chunk);
if (isBuf && !Buffer.isBuffer(chunk)) {
chunk = _uint8ArrayToBuffer(chunk);
}
if (typeof encoding === 'function') {
cb = encoding;
encoding = null;
}
if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
if (typeof cb !== 'function') cb = nop;
if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
state.pendingcb++;
ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
}
return ret;
};
Writable.prototype.cork = function () {
var state = this._writableState;
state.corked++;
};
Writable.prototype.uncork = function () {
var state = this._writableState;
if (state.corked) {
state.corked--;
if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
}
};
Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
// node::ParseEncoding() requires lower case.
if (typeof encoding === 'string') encoding = encoding.toLowerCase();
if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding);
this._writableState.defaultEncoding = encoding;
return this;
};
function decodeChunk(state, chunk, encoding) {
if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
chunk = Buffer.from(chunk, encoding);
}
return chunk;
}
Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
// making it explicit this property is not enumerable
// because otherwise some prototype manipulation in
// userland will fail
enumerable: false,
get: function () {
return this._writableState.highWaterMark;
}
});
// if we're already writing something, then just put this
// in the queue, and wait our turn. Otherwise, call _write
// If we return false, then we need a drain event, so set that flag.
function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
if (!isBuf) {
var newChunk = decodeChunk(state, chunk, encoding);
if (chunk !== newChunk) {
isBuf = true;
encoding = 'buffer';
chunk = newChunk;
}
}
var len = state.objectMode ? 1 : chunk.length;
state.length += len;
var ret = state.length < state.highWaterMark;
// we must ensure that previous needDrain will not be reset to false.
if (!ret) state.needDrain = true;
if (state.writing || state.corked) {
var last = state.lastBufferedRequest;
state.lastBufferedRequest = {
chunk: chunk,
encoding: encoding,
isBuf: isBuf,
callback: cb,
next: null
};
if (last) {
last.next = state.lastBufferedRequest;
} else {
state.bufferedRequest = state.lastBufferedRequest;
}
state.bufferedRequestCount += 1;
} else {
doWrite(stream, state, false, len, chunk, encoding, cb);
}
return ret;
}
function doWrite(stream, state, writev, len, chunk, encoding, cb) {
state.writelen = len;
state.writecb = cb;
state.writing = true;
state.sync = true;
if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
state.sync = false;
}
function onwriteError(stream, state, sync, er, cb) {
--state.pendingcb;
if (sync) {
// defer the callback if we are being called synchronously
// to avoid piling up things on the stack
pna.nextTick(cb, er);
// this can emit finish, and it will always happen
// after error
pna.nextTick(finishMaybe, stream, state);
stream._writableState.errorEmitted = true;
stream.emit('error', er);
} else {
// the caller expect this to happen before if
// it is async
cb(er);
stream._writableState.errorEmitted = true;
stream.emit('error', er);
// this can emit finish, but finish must
// always follow error
finishMaybe(stream, state);
}
}
function onwriteStateUpdate(state) {
state.writing = false;
state.writecb = null;
state.length -= state.writelen;
state.writelen = 0;
}
function onwrite(stream, er) {
var state = stream._writableState;
var sync = state.sync;
var cb = state.writecb;
onwriteStateUpdate(state);
if (er) onwriteError(stream, state, sync, er, cb);else {
// Check if we're actually ready to finish, but don't emit yet
var finished = needFinish(state);
if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
clearBuffer(stream, state);
}
if (sync) {
/*<replacement>*/
asyncWrite(afterWrite, stream, state, finished, cb);
/*</replacement>*/
} else {
afterWrite(stream, state, finished, cb);
}
}
}
function afterWrite(stream, state, finished, cb) {
if (!finished) onwriteDrain(stream, state);
state.pendingcb--;
cb();
finishMaybe(stream, state);
}
// Must force callback to be called on nextTick, so that we don't
// emit 'drain' before the write() consumer gets the 'false' return
// value, and has a chance to attach a 'drain' listener.
function onwriteDrain(stream, state) {
if (state.length === 0 && state.needDrain) {
state.needDrain = false;
stream.emit('drain');
}
}
// if there's something in the buffer waiting, then process it
function clearBuffer(stream, state) {
state.bufferProcessing = true;
var entry = state.bufferedRequest;
if (stream._writev && entry && entry.next) {
// Fast case, write everything using _writev()
var l = state.bufferedRequestCount;
var buffer = new Array(l);
var holder = state.corkedRequestsFree;
holder.entry = entry;
var count = 0;
var allBuffers = true;
while (entry) {
buffer[count] = entry;
if (!entry.isBuf) allBuffers = false;
entry = entry.next;
count += 1;
}
buffer.allBuffers = allBuffers;
doWrite(stream, state, true, state.length, buffer, '', holder.finish);
// doWrite is almost always async, defer these to save a bit of time
// as the hot path ends with doWrite
state.pendingcb++;
state.lastBufferedRequest = null;
if (holder.next) {
state.corkedRequestsFree = holder.next;
holder.next = null;
} else {
state.corkedRequestsFree = new CorkedRequest(state);
}
state.bufferedRequestCount = 0;
} else {
// Slow case, write chunks one-by-one
while (entry) {
var chunk = entry.chunk;
var encoding = entry.encoding;
var cb = entry.callback;
var len = state.objectMode ? 1 : chunk.length;
doWrite(stream, state, false, len, chunk, encoding, cb);
entry = entry.next;
state.bufferedRequestCount--;
// if we didn't call the onwrite immediately, then
// it means that we need to wait until it does.
// also, that means that the chunk and cb are currently
// being processed, so move the buffer counter past them.
if (state.writing) {
break;
}
}
if (entry === null) state.lastBufferedRequest = null;
}
state.bufferedRequest = entry;
state.bufferProcessing = false;
}
Writable.prototype._write = function (chunk, encoding, cb) {
cb(new Error('_write() is not implemented'));
};
Writable.prototype._writev = null;
Writable.prototype.end = function (chunk, encoding, cb) {
var state = this._writableState;
if (typeof chunk === 'function') {
cb = chunk;
chunk = null;
encoding = null;
} else if (typeof encoding === 'function') {
cb = encoding;
encoding = null;
}
if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
// .end() fully uncorks
if (state.corked) {
state.corked = 1;
this.uncork();
}
// ignore unnecessary end() calls.
if (!state.ending && !state.finished) endWritable(this, state, cb);
};
function needFinish(state) {
return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
}
function callFinal(stream, state) {
stream._final(function (err) {
state.pendingcb--;
if (err) {
stream.emit('error', err);
}
state.prefinished = true;
stream.emit('prefinish');
finishMaybe(stream, state);
});
}
function prefinish(stream, state) {
if (!state.prefinished && !state.finalCalled) {
if (typeof stream._final === 'function') {
state.pendingcb++;
state.finalCalled = true;
pna.nextTick(callFinal, stream, state);
} else {
state.prefinished = true;
stream.emit('prefinish');
}
}
}
function finishMaybe(stream, state) {
var need = needFinish(state);
if (need) {
prefinish(stream, state);
if (state.pendingcb === 0) {
state.finished = true;
stream.emit('finish');
}
}
return need;
}
function endWritable(stream, state, cb) {
state.ending = true;
finishMaybe(stream, state);
if (cb) {
if (state.finished) pna.nextTick(cb);else stream.once('finish', cb);
}
state.ended = true;
stream.writable = false;
}
function onCorkedFinish(corkReq, state, err) {
var entry = corkReq.entry;
corkReq.entry = null;
while (entry) {
var cb = entry.callback;
state.pendingcb--;
cb(err);
entry = entry.next;
}
if (state.corkedRequestsFree) {
state.corkedRequestsFree.next = corkReq;
} else {
state.corkedRequestsFree = corkReq;
}
}
Object.defineProperty(Writable.prototype, 'destroyed', {
get: function () {
if (this._writableState === undefined) {
return false;
}
return this._writableState.destroyed;
},
set: function (value) {
// we ignore the value if the stream
// has not been initialized yet
if (!this._writableState) {
return;
}
// backward compatibility, the user is explicitly
// managing destroyed
this._writableState.destroyed = value;
}
});
Writable.prototype.destroy = destroyImpl.destroy;
Writable.prototype._undestroy = destroyImpl.undestroy;
Writable.prototype._destroy = function (err, cb) {
this.end();
cb(err);
};
}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("timers").setImmediate)
},{"./_stream_duplex":437,"./internal/streams/destroy":443,"./internal/streams/stream":444,"_process":436,"core-util-is":427,"inherits":431,"process-nextick-args":435,"safe-buffer":446,"timers":448,"util-deprecate":449}],442:[function(require,module,exports){
'use strict';
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Buffer = require('safe-buffer').Buffer;
var util = require('util');
function copyBuffer(src, target, offset) {
src.copy(target, offset);
}
module.exports = function () {
function BufferList() {
_classCallCheck(this, BufferList);
this.head = null;
this.tail = null;
this.length = 0;
}
BufferList.prototype.push = function push(v) {
var entry = { data: v, next: null };
if (this.length > 0) this.tail.next = entry;else this.head = entry;
this.tail = entry;
++this.length;
};
BufferList.prototype.unshift = function unshift(v) {
var entry = { data: v, next: this.head };
if (this.length === 0) this.tail = entry;
this.head = entry;
++this.length;
};
BufferList.prototype.shift = function shift() {
if (this.length === 0) return;
var ret = this.head.data;
if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
--this.length;
return ret;
};
BufferList.prototype.clear = function clear() {
this.head = this.tail = null;
this.length = 0;
};
BufferList.prototype.join = function join(s) {
if (this.length === 0) return '';
var p = this.head;
var ret = '' + p.data;
while (p = p.next) {
ret += s + p.data;
}return ret;
};
BufferList.prototype.concat = function concat(n) {
if (this.length === 0) return Buffer.alloc(0);
if (this.length === 1) return this.head.data;
var ret = Buffer.allocUnsafe(n >>> 0);
var p = this.head;
var i = 0;
while (p) {
copyBuffer(p.data, ret, i);
i += p.data.length;
p = p.next;
}
return ret;
};
return BufferList;
}();
if (util && util.inspect && util.inspect.custom) {
module.exports.prototype[util.inspect.custom] = function () {
var obj = util.inspect({ length: this.length });
return this.constructor.name + ' ' + obj;
};
}
},{"safe-buffer":446,"util":424}],443:[function(require,module,exports){
'use strict';
/*<replacement>*/
var pna = require('process-nextick-args');
/*</replacement>*/
// undocumented cb() API, needed for core, not for public API
function destroy(err, cb) {
var _this = this;
var readableDestroyed = this._readableState && this._readableState.destroyed;
var writableDestroyed = this._writableState && this._writableState.destroyed;
if (readableDestroyed || writableDestroyed) {
if (cb) {
cb(err);
} else if (err && (!this._writableState || !this._writableState.errorEmitted)) {
pna.nextTick(emitErrorNT, this, err);
}
return this;
}
// we set destroyed to true before firing error callbacks in order
// to make it re-entrance safe in case destroy() is called within callbacks
if (this._readableState) {
this._readableState.destroyed = true;
}
// if this is a duplex stream mark the writable part as destroyed as well
if (this._writableState) {
this._writableState.destroyed = true;
}
this._destroy(err || null, function (err) {
if (!cb && err) {
pna.nextTick(emitErrorNT, _this, err);
if (_this._writableState) {
_this._writableState.errorEmitted = true;
}
} else if (cb) {
cb(err);
}
});
return this;
}
function undestroy() {
if (this._readableState) {
this._readableState.destroyed = false;
this._readableState.reading = false;
this._readableState.ended = false;
this._readableState.endEmitted = false;
}
if (this._writableState) {
this._writableState.destroyed = false;
this._writableState.ended = false;
this._writableState.ending = false;
this._writableState.finished = false;
this._writableState.errorEmitted = false;
}
}
function emitErrorNT(self, err) {
self.emit('error', err);
}
module.exports = {
destroy: destroy,
undestroy: undestroy
};
},{"process-nextick-args":435}],444:[function(require,module,exports){
module.exports = require('events').EventEmitter;
},{"events":425}],445:[function(require,module,exports){
exports = module.exports = require('./lib/_stream_readable.js');
exports.Stream = exports;
exports.Readable = exports;
exports.Writable = require('./lib/_stream_writable.js');
exports.Duplex = require('./lib/_stream_duplex.js');
exports.Transform = require('./lib/_stream_transform.js');
exports.PassThrough = require('./lib/_stream_passthrough.js');
},{"./lib/_stream_duplex.js":437,"./lib/_stream_passthrough.js":438,"./lib/_stream_readable.js":439,"./lib/_stream_transform.js":440,"./lib/_stream_writable.js":441}],446:[function(require,module,exports){
/* eslint-disable node/no-deprecated-api */
var buffer = require('buffer')
var Buffer = buffer.Buffer
// alternative to using Object.keys for old browsers
function copyProps (src, dst) {
for (var key in src) {
dst[key] = src[key]
}
}
if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
module.exports = buffer
} else {
// Copy properties from require('buffer')
copyProps(buffer, exports)
exports.Buffer = SafeBuffer
}
function SafeBuffer (arg, encodingOrOffset, length) {
return Buffer(arg, encodingOrOffset, length)
}
// Copy static methods from Buffer
copyProps(Buffer, SafeBuffer)
SafeBuffer.from = function (arg, encodingOrOffset, length) {
if (typeof arg === 'number') {
throw new TypeError('Argument must not be a number')
}
return Buffer(arg, encodingOrOffset, length)
}
SafeBuffer.alloc = function (size, fill, encoding) {
if (typeof size !== 'number') {
throw new TypeError('Argument must be a number')
}
var buf = Buffer(size)
if (fill !== undefined) {
if (typeof encoding === 'string') {
buf.fill(fill, encoding)
} else {
buf.fill(fill)
}
} else {
buf.fill(0)
}
return buf
}
SafeBuffer.allocUnsafe = function (size) {
if (typeof size !== 'number') {
throw new TypeError('Argument must be a number')
}
return Buffer(size)
}
SafeBuffer.allocUnsafeSlow = function (size) {
if (typeof size !== 'number') {
throw new TypeError('Argument must be a number')
}
return buffer.SlowBuffer(size)
}
},{"buffer":426}],447:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
'use strict';
/*<replacement>*/
var Buffer = require('safe-buffer').Buffer;
/*</replacement>*/
var isEncoding = Buffer.isEncoding || function (encoding) {
encoding = '' + encoding;
switch (encoding && encoding.toLowerCase()) {
case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw':
return true;
default:
return false;
}
};
function _normalizeEncoding(enc) {
if (!enc) return 'utf8';
var retried;
while (true) {
switch (enc) {
case 'utf8':
case 'utf-8':
return 'utf8';
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return 'utf16le';
case 'latin1':
case 'binary':
return 'latin1';
case 'base64':
case 'ascii':
case 'hex':
return enc;
default:
if (retried) return; // undefined
enc = ('' + enc).toLowerCase();
retried = true;
}
}
};
// Do not cache `Buffer.isEncoding` when checking encoding names as some
// modules monkey-patch it to support additional encodings
function normalizeEncoding(enc) {
var nenc = _normalizeEncoding(enc);
if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
return nenc || enc;
}
// StringDecoder provides an interface for efficiently splitting a series of
// buffers into a series of JS strings without breaking apart multi-byte
// characters.
exports.StringDecoder = StringDecoder;
function StringDecoder(encoding) {
this.encoding = normalizeEncoding(encoding);
var nb;
switch (this.encoding) {
case 'utf16le':
this.text = utf16Text;
this.end = utf16End;
nb = 4;
break;
case 'utf8':
this.fillLast = utf8FillLast;
nb = 4;
break;
case 'base64':
this.text = base64Text;
this.end = base64End;
nb = 3;
break;
default:
this.write = simpleWrite;
this.end = simpleEnd;
return;
}
this.lastNeed = 0;
this.lastTotal = 0;
this.lastChar = Buffer.allocUnsafe(nb);
}
StringDecoder.prototype.write = function (buf) {
if (buf.length === 0) return '';
var r;
var i;
if (this.lastNeed) {
r = this.fillLast(buf);
if (r === undefined) return '';
i = this.lastNeed;
this.lastNeed = 0;
} else {
i = 0;
}
if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
return r || '';
};
StringDecoder.prototype.end = utf8End;
// Returns only complete characters in a Buffer
StringDecoder.prototype.text = utf8Text;
// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
StringDecoder.prototype.fillLast = function (buf) {
if (this.lastNeed <= buf.length) {
buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
return this.lastChar.toString(this.encoding, 0, this.lastTotal);
}
buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
this.lastNeed -= buf.length;
};
// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
// continuation byte. If an invalid byte is detected, -2 is returned.
function utf8CheckByte(byte) {
if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;
return byte >> 6 === 0x02 ? -1 : -2;
}
// Checks at most 3 bytes at the end of a Buffer in order to detect an
// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
// needed to complete the UTF-8 character (if applicable) are returned.
function utf8CheckIncomplete(self, buf, i) {
var j = buf.length - 1;
if (j < i) return 0;
var nb = utf8CheckByte(buf[j]);
if (nb >= 0) {
if (nb > 0) self.lastNeed = nb - 1;
return nb;
}
if (--j < i || nb === -2) return 0;
nb = utf8CheckByte(buf[j]);
if (nb >= 0) {
if (nb > 0) self.lastNeed = nb - 2;
return nb;
}
if (--j < i || nb === -2) return 0;
nb = utf8CheckByte(buf[j]);
if (nb >= 0) {
if (nb > 0) {
if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
}
return nb;
}
return 0;
}
// Validates as many continuation bytes for a multi-byte UTF-8 character as
// needed or are available. If we see a non-continuation byte where we expect
// one, we "replace" the validated continuation bytes we've seen so far with
// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding
// behavior. The continuation byte check is included three times in the case
// where all of the continuation bytes for a character exist in the same buffer.
// It is also done this way as a slight performance increase instead of using a
// loop.
function utf8CheckExtraBytes(self, buf, p) {
if ((buf[0] & 0xC0) !== 0x80) {
self.lastNeed = 0;
return '\ufffd';
}
if (self.lastNeed > 1 && buf.length > 1) {
if ((buf[1] & 0xC0) !== 0x80) {
self.lastNeed = 1;
return '\ufffd';
}
if (self.lastNeed > 2 && buf.length > 2) {
if ((buf[2] & 0xC0) !== 0x80) {
self.lastNeed = 2;
return '\ufffd';
}
}
}
}
// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
function utf8FillLast(buf) {
var p = this.lastTotal - this.lastNeed;
var r = utf8CheckExtraBytes(this, buf, p);
if (r !== undefined) return r;
if (this.lastNeed <= buf.length) {
buf.copy(this.lastChar, p, 0, this.lastNeed);
return this.lastChar.toString(this.encoding, 0, this.lastTotal);
}
buf.copy(this.lastChar, p, 0, buf.length);
this.lastNeed -= buf.length;
}
// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
// partial character, the character's bytes are buffered until the required
// number of bytes are available.
function utf8Text(buf, i) {
var total = utf8CheckIncomplete(this, buf, i);
if (!this.lastNeed) return buf.toString('utf8', i);
this.lastTotal = total;
var end = buf.length - (total - this.lastNeed);
buf.copy(this.lastChar, 0, end);
return buf.toString('utf8', i, end);
}
// For UTF-8, a replacement character is added when ending on a partial
// character.
function utf8End(buf) {
var r = buf && buf.length ? this.write(buf) : '';
if (this.lastNeed) return r + '\ufffd';
return r;
}
// UTF-16LE typically needs two bytes per character, but even if we have an even
// number of bytes available, we need to check if we end on a leading/high
// surrogate. In that case, we need to wait for the next two bytes in order to
// decode the last character properly.
function utf16Text(buf, i) {
if ((buf.length - i) % 2 === 0) {
var r = buf.toString('utf16le', i);
if (r) {
var c = r.charCodeAt(r.length - 1);
if (c >= 0xD800 && c <= 0xDBFF) {
this.lastNeed = 2;
this.lastTotal = 4;
this.lastChar[0] = buf[buf.length - 2];
this.lastChar[1] = buf[buf.length - 1];
return r.slice(0, -1);
}
}
return r;
}
this.lastNeed = 1;
this.lastTotal = 2;
this.lastChar[0] = buf[buf.length - 1];
return buf.toString('utf16le', i, buf.length - 1);
}
// For UTF-16LE we do not explicitly append special replacement characters if we
// end on a partial character, we simply let v8 handle that.
function utf16End(buf) {
var r = buf && buf.length ? this.write(buf) : '';
if (this.lastNeed) {
var end = this.lastTotal - this.lastNeed;
return r + this.lastChar.toString('utf16le', 0, end);
}
return r;
}
function base64Text(buf, i) {
var n = (buf.length - i) % 3;
if (n === 0) return buf.toString('base64', i);
this.lastNeed = 3 - n;
this.lastTotal = 3;
if (n === 1) {
this.lastChar[0] = buf[buf.length - 1];
} else {
this.lastChar[0] = buf[buf.length - 2];
this.lastChar[1] = buf[buf.length - 1];
}
return buf.toString('base64', i, buf.length - n);
}
function base64End(buf) {
var r = buf && buf.length ? this.write(buf) : '';
if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
return r;
}
// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
function simpleWrite(buf) {
return buf.toString(this.encoding);
}
function simpleEnd(buf) {
return buf && buf.length ? this.write(buf) : '';
}
},{"safe-buffer":446}],448:[function(require,module,exports){
(function (setImmediate,clearImmediate){(function (){
var nextTick = require('process/browser.js').nextTick;
var apply = Function.prototype.apply;
var slice = Array.prototype.slice;
var immediateIds = {};
var nextImmediateId = 0;
// DOM APIs, for completeness
exports.setTimeout = function() {
return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
};
exports.setInterval = function() {
return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
};
exports.clearTimeout =
exports.clearInterval = function(timeout) { timeout.close(); };
function Timeout(id, clearFn) {
this._id = id;
this._clearFn = clearFn;
}
Timeout.prototype.unref = Timeout.prototype.ref = function() {};
Timeout.prototype.close = function() {
this._clearFn.call(window, this._id);
};
// Does not start the time, just sets up the members needed.
exports.enroll = function(item, msecs) {
clearTimeout(item._idleTimeoutId);
item._idleTimeout = msecs;
};
exports.unenroll = function(item) {
clearTimeout(item._idleTimeoutId);
item._idleTimeout = -1;
};
exports._unrefActive = exports.active = function(item) {
clearTimeout(item._idleTimeoutId);
var msecs = item._idleTimeout;
if (msecs >= 0) {
item._idleTimeoutId = setTimeout(function onTimeout() {
if (item._onTimeout)
item._onTimeout();
}, msecs);
}
};
// That's not how node.js implements it but the exposed api is the same.
exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) {
var id = nextImmediateId++;
var args = arguments.length < 2 ? false : slice.call(arguments, 1);
immediateIds[id] = true;
nextTick(function onNextTick() {
if (immediateIds[id]) {
// fn.call() is faster so we optimize for the common use-case
// @see http://jsperf.com/call-apply-segu
if (args) {
fn.apply(null, args);
} else {
fn.call(null);
}
// Prevent ids from leaking
exports.clearImmediate(id);
}
});
return id;
};
exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) {
delete immediateIds[id];
};
}).call(this)}).call(this,require("timers").setImmediate,require("timers").clearImmediate)
},{"process/browser.js":436,"timers":448}],449:[function(require,module,exports){
(function (global){(function (){
/**
* Module exports.
*/
module.exports = deprecate;
/**
* Mark that a method should not be used.
* Returns a modified function which warns once by default.
*
* If `localStorage.noDeprecation = true` is set, then it is a no-op.
*
* If `localStorage.throwDeprecation = true` is set, then deprecated functions
* will throw an Error when invoked.
*
* If `localStorage.traceDeprecation = true` is set, then deprecated functions
* will invoke `console.trace()` instead of `console.error()`.
*
* @param {Function} fn - the function to deprecate
* @param {String} msg - the string to print to the console when `fn` is invoked
* @returns {Function} a new "deprecated" version of `fn`
* @api public
*/
function deprecate (fn, msg) {
if (config('noDeprecation')) {
return fn;
}
var warned = false;
function deprecated() {
if (!warned) {
if (config('throwDeprecation')) {
throw new Error(msg);
} else if (config('traceDeprecation')) {
console.trace(msg);
} else {
console.warn(msg);
}
warned = true;
}
return fn.apply(this, arguments);
}
return deprecated;
}
/**
* Checks `localStorage` for boolean values for the given `name`.
*
* @param {String} name
* @returns {Boolean}
* @api private
*/
function config (name) {
// accessing global.localStorage can trigger a DOMException in sandboxed iframes
try {
if (!global.localStorage) return false;
} catch (_) {
return false;
}
var val = global.localStorage[name];
if (null == val) return false;
return String(val).toLowerCase() === 'true';
}
}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}]},{},[311]);
| stdlib-js/www | public/docs/api/latest/@stdlib/stats/base/dists/exponential/median/benchmark_bundle.js | JavaScript | apache-2.0 | 883,740 |
OC.L10N.register(
"lib",
{
"Help" : "Hjelp",
"Personal" : "Personleg",
"Settings" : "Innstillingar",
"Users" : "Brukarar",
"Admin" : "Administrer",
"Unknown filetype" : "Ukjend filtype",
"Invalid image" : "Ugyldig bilete",
"today" : "i dag",
"yesterday" : "i går",
"_%n day ago_::_%n days ago_" : ["",""],
"last month" : "førre månad",
"_%n month ago_::_%n months ago_" : ["","%n månadar sidan"],
"last year" : "i fjor",
"_%n year ago_::_%n years ago_" : ["",""],
"_%n hour ago_::_%n hours ago_" : ["","%n timar sidan"],
"_%n minute ago_::_%n minutes ago_" : ["","%n minutt sidan"],
"seconds ago" : "sekund sidan",
"web services under your control" : "Vev tjenester under din kontroll",
"Authentication error" : "Feil i autentisering",
"%s shared »%s« with you" : "%s delte «%s» med deg",
"A valid username must be provided" : "Du må oppgje eit gyldig brukarnamn",
"A valid password must be provided" : "Du må oppgje eit gyldig passord"
},
"nplurals=2; plural=(n != 1);");
| kebenxiaoming/owncloudRedis | lib/l10n/nn_NO.js | JavaScript | apache-2.0 | 1,079 |
var assert = require('assert');
var H = require('../test_harness.js');
var cb = H.newClient();
describe('#get/set', function() {
it('should work in basic cases', function(done) {
var key = H.genKey("set");
cb.set(key, "bar", H.okCallback(function(firstresult){
// nothing broke
cb.set(key, "baz", H.okCallback(function(secondresult){
assert.notDeepEqual(firstresult.cas, secondresult.cas, "CAS should change");
cb.set(key, "bam", firstresult, function(err, result){
assert(err, "Key should fail with stale CAS");
cb.get(key, H.okCallback(function(result){
assert.equal(result.value, "baz");
cb.set(key, "grr", secondresult, H.okCallback(function(result){
cb.get(key, H.okCallback(function(result){
assert.equal("grr", result.value);
done();
}));
}));
}));
});
}));
}));
});
it('should work when passing json strings', function(done) {
var key = H.genKey("set-json");
cb.set(key, JSON.stringify({foo: "bar"}), H.okCallback(function(){
cb.set(key, JSON.stringify({foo: "baz"}), H.okCallback(function(){
cb.get(key, H.okCallback(function(result){
assert.equal(JSON.stringify({foo: "baz"}), result.value);
done();
}));
}));
}));
});
it('should work when passing large values', function(done) {
var key = H.genKey("set-big");
var value = "";
for (var ii = 0; ii < 8192; ++ii) {
value += "012345678\n";
}
cb.set(key, value, H.okCallback(function(setres) {
cb.get(key, H.okCallback(function(getres) {
assert.equal(value, getres.value);
done();
}));
}));
});
it('should convert objects to json and back', function(done) {
var key = H.genKey("set-format");
H.setGet(key, {foo: "bar"}, function(doc) {
assert.equal("bar", doc.foo);
done();
});
});
it('should round-trip Unicode values', function(done) {
var key = H.genKey("set-unicode");
var value = ['☆'];
H.setGet(key, value, function(doc){
assert.deepEqual(value, doc);
done();
});
});
it('should return raw string when using format option', function(done) {
var value = [1,2,3,4,5,6];
var key = H.genKey("set-raw");
cb.set(key, value, H.okCallback(function(){
cb.get(key, { format: 'raw' }, H.okCallback(function(result){
assert.equal(result.value, JSON.stringify(value));
done();
}));
}));
});
it('should properly handle setting raw strings', function(done) {
var value = "hello";
var key = H.genKey("set-json-strings");
cb.set(key, value, { format: 'json' }, H.okCallback(function(){
cb.get(key, H.okCallback(function(result){
assert.equal(result.value, value);
cb.get(key, { format: 'raw' }, H.okCallback(function(result){
assert.equal(result.value, '"hello"');
done();
}));
}));
}));
});
it('should handle setting unencodable values', function(done) {
var value = [1,2,3,4];
var key = H.genKey("set-utf8-unconvertible");
cb.set(key, value, { format: 'raw' }, function(err, result){
assert(err);
done();
});
});
it('should round-trip raw Buffers', function(done) {
var buf = new Buffer([0, 1, 2]);
// \x00, \x01, \x02
var key = H.genKey("set-raw-format");
cb.set(key, buf, H.okCallback(function(){
cb.get(key, H.okCallback(function(result){
var doc = result.value;
assert(Buffer.isBuffer(doc));
assert.deepEqual(buf, doc);
assert.equal(result.flags, H.format.raw);
done();
}));
}));
});
it('should allow overriding of flags', function(done) {
var value = {val:"value"};
var key = H.genKey("set-flags-override");
// Note that we must specify the format as the flags no longer carries it
cb.set(key, value, {flags: 14}, H.okCallback(function(){
cb.get(key, {format: H.format.json},
H.okCallback(function(result){
assert.deepEqual(result.value, value);
assert.equal(result.flags, 14);
done();
}));
}));
});
it('should expire values correct', function(done) {
this.timeout(3000);
var value = {val:"value"};
var key = H.genKey("expiry");
cb.set(key, value, {expiry: 1}, H.okCallback(function(){
cb.get(key, H.okCallback(function(result){
assert.deepEqual(result.value, value);
setTimeout(function () {
cb.get(key, function(err, result) {
assert(err, "Key should no longer exist");
done();
});
}, 2000);
}));
}));
});
it('should touch on get with expiry', function(done) {
this.timeout(3000);
var value = {val:"value"};
var key = H.genKey("getandtouch");
cb.set(key, value, {expiry: 1}, H.okCallback(function(){
// This should extend the expiry by 5 seconds
cb.get(key, {expiry:5}, H.okCallback(function(result){
assert.deepEqual(result.value, value);
setTimeout(function () {
cb.get(key, H.okCallback(function(result){
assert.deepEqual(result.value, value);
done();
}));
}, 2000);
}));
}));
});
});
| couchbaselabs/expiry-notifier | node_modules/couchbase/test/get-set.js | JavaScript | apache-2.0 | 5,360 |
/a/lib/tsc.js --w
//// [/user/username/projects/myproject/lib1/tools/tools.interface.ts]
export interface ITest {
title: string;
}
//// [/user/username/projects/myproject/lib1/tools/public.ts]
export * from "./tools.interface";
//// [/user/username/projects/myproject/app.ts]
import { Data } from "lib2/public";
export class App {
public constructor() {
new Data().test();
}
}
//// [/user/username/projects/myproject/lib2/public.ts]
export * from "./data";
//// [/user/username/projects/myproject/lib1/public.ts]
export * from "./tools/public";
//// [/user/username/projects/myproject/lib2/data.ts]
import { ITest } from "lib1/public";
export class Data {
public test() {
const result: ITest = {
title: "title"
}
return result;
}
}
//// [/user/username/projects/myproject/tsconfig.json]
{"files":["app.ts"],"compilerOptions":{"baseUrl":"."}}
//// [/a/lib/lib.d.ts]
/// <reference no-default-lib="true"/>
interface Boolean {}
interface Function {}
interface CallableFunction {}
interface NewableFunction {}
interface IArguments {}
interface Number { toExponential: any; }
interface Object {}
interface RegExp {}
interface String { charAt: any; }
interface Array<T> { length: number; [n: number]: T; }
//// [/user/username/projects/myproject/lib1/tools/tools.interface.js]
"use strict";
exports.__esModule = true;
//// [/user/username/projects/myproject/lib1/tools/public.js]
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (!exports.hasOwnProperty(p)) __createBinding(exports, m, p);
}
exports.__esModule = true;
__exportStar(require("./tools.interface"), exports);
//// [/user/username/projects/myproject/lib1/public.js]
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (!exports.hasOwnProperty(p)) __createBinding(exports, m, p);
}
exports.__esModule = true;
__exportStar(require("./tools/public"), exports);
//// [/user/username/projects/myproject/lib2/data.js]
"use strict";
exports.__esModule = true;
exports.Data = void 0;
var Data = /** @class */ (function () {
function Data() {
}
Data.prototype.test = function () {
var result = {
title: "title"
};
return result;
};
return Data;
}());
exports.Data = Data;
//// [/user/username/projects/myproject/lib2/public.js]
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (!exports.hasOwnProperty(p)) __createBinding(exports, m, p);
}
exports.__esModule = true;
__exportStar(require("./data"), exports);
//// [/user/username/projects/myproject/app.js]
"use strict";
exports.__esModule = true;
exports.App = void 0;
var public_1 = require("lib2/public");
var App = /** @class */ (function () {
function App() {
new public_1.Data().test();
}
return App;
}());
exports.App = App;
Output::
>> Screen clear
[[90m12:00:37 AM[0m] Starting compilation in watch mode...
[[90m12:00:50 AM[0m] Found 0 errors. Watching for file changes.
Program root files: ["/user/username/projects/myproject/app.ts"]
Program options: {"baseUrl":"/user/username/projects/myproject","watch":true,"configFilePath":"/user/username/projects/myproject/tsconfig.json"}
Program files::
/a/lib/lib.d.ts
/user/username/projects/myproject/lib1/tools/tools.interface.ts
/user/username/projects/myproject/lib1/tools/public.ts
/user/username/projects/myproject/lib1/public.ts
/user/username/projects/myproject/lib2/data.ts
/user/username/projects/myproject/lib2/public.ts
/user/username/projects/myproject/app.ts
Semantic diagnostics in builder refreshed for::
/a/lib/lib.d.ts
/user/username/projects/myproject/lib1/tools/tools.interface.ts
/user/username/projects/myproject/lib1/tools/public.ts
/user/username/projects/myproject/lib1/public.ts
/user/username/projects/myproject/lib2/data.ts
/user/username/projects/myproject/lib2/public.ts
/user/username/projects/myproject/app.ts
WatchedFiles::
/user/username/projects/myproject/tsconfig.json:
{"fileName":"/user/username/projects/myproject/tsconfig.json","pollingInterval":250}
/user/username/projects/myproject/app.ts:
{"fileName":"/user/username/projects/myproject/app.ts","pollingInterval":250}
/user/username/projects/myproject/lib2/public.ts:
{"fileName":"/user/username/projects/myproject/lib2/public.ts","pollingInterval":250}
/user/username/projects/myproject/lib2/data.ts:
{"fileName":"/user/username/projects/myproject/lib2/data.ts","pollingInterval":250}
/user/username/projects/myproject/lib1/public.ts:
{"fileName":"/user/username/projects/myproject/lib1/public.ts","pollingInterval":250}
/user/username/projects/myproject/lib1/tools/public.ts:
{"fileName":"/user/username/projects/myproject/lib1/tools/public.ts","pollingInterval":250}
/user/username/projects/myproject/lib1/tools/tools.interface.ts:
{"fileName":"/user/username/projects/myproject/lib1/tools/tools.interface.ts","pollingInterval":250}
/a/lib/lib.d.ts:
{"fileName":"/a/lib/lib.d.ts","pollingInterval":250}
FsWatches::
FsWatchesRecursive::
/user/username/projects/myproject/node_modules/@types:
{"directoryName":"/user/username/projects/myproject/node_modules/@types","fallbackPollingInterval":500,"fallbackOptions":{"watchFile":"PriorityPollingInterval"}}
exitCode:: ExitStatus.undefined
Change:: Rename property title to title2 of interface ITest
//// [/user/username/projects/myproject/lib1/tools/tools.interface.ts]
export interface ITest {
title2: string;
}
//// [/user/username/projects/myproject/lib1/tools/tools.interface.js] file written with same contents
//// [/user/username/projects/myproject/lib1/tools/public.js] file written with same contents
Output::
>> Screen clear
[[90m12:00:54 AM[0m] File change detected. Starting incremental compilation...
[96mlib2/data.ts[0m:[93m5[0m:[93m13[0m - [91merror[0m[90m TS2322: [0mType '{ title: string; }' is not assignable to type 'ITest'.
Object literal may only specify known properties, but 'title' does not exist in type 'ITest'. Did you mean to write 'title2'?
[7m5[0m title: "title"
[7m [0m [91m ~~~~~~~~~~~~~~[0m
[[90m12:01:01 AM[0m] Found 1 error. Watching for file changes.
Program root files: ["/user/username/projects/myproject/app.ts"]
Program options: {"baseUrl":"/user/username/projects/myproject","watch":true,"configFilePath":"/user/username/projects/myproject/tsconfig.json"}
Program files::
/a/lib/lib.d.ts
/user/username/projects/myproject/lib1/tools/tools.interface.ts
/user/username/projects/myproject/lib1/tools/public.ts
/user/username/projects/myproject/lib1/public.ts
/user/username/projects/myproject/lib2/data.ts
/user/username/projects/myproject/lib2/public.ts
/user/username/projects/myproject/app.ts
Semantic diagnostics in builder refreshed for::
/user/username/projects/myproject/lib1/tools/tools.interface.ts
/user/username/projects/myproject/lib1/tools/public.ts
/user/username/projects/myproject/lib1/public.ts
/user/username/projects/myproject/lib2/data.ts
/user/username/projects/myproject/lib2/public.ts
/user/username/projects/myproject/app.ts
WatchedFiles::
/user/username/projects/myproject/tsconfig.json:
{"fileName":"/user/username/projects/myproject/tsconfig.json","pollingInterval":250}
/user/username/projects/myproject/app.ts:
{"fileName":"/user/username/projects/myproject/app.ts","pollingInterval":250}
/user/username/projects/myproject/lib2/public.ts:
{"fileName":"/user/username/projects/myproject/lib2/public.ts","pollingInterval":250}
/user/username/projects/myproject/lib2/data.ts:
{"fileName":"/user/username/projects/myproject/lib2/data.ts","pollingInterval":250}
/user/username/projects/myproject/lib1/public.ts:
{"fileName":"/user/username/projects/myproject/lib1/public.ts","pollingInterval":250}
/user/username/projects/myproject/lib1/tools/public.ts:
{"fileName":"/user/username/projects/myproject/lib1/tools/public.ts","pollingInterval":250}
/user/username/projects/myproject/lib1/tools/tools.interface.ts:
{"fileName":"/user/username/projects/myproject/lib1/tools/tools.interface.ts","pollingInterval":250}
/a/lib/lib.d.ts:
{"fileName":"/a/lib/lib.d.ts","pollingInterval":250}
FsWatches::
FsWatchesRecursive::
/user/username/projects/myproject/node_modules/@types:
{"directoryName":"/user/username/projects/myproject/node_modules/@types","fallbackPollingInterval":500,"fallbackOptions":{"watchFile":"PriorityPollingInterval"}}
exitCode:: ExitStatus.undefined
| alexeagle/TypeScript | tests/baselines/reference/tscWatch/emitAndErrorUpdates/default/updates-errors-when-file-transitively-exported-file-changes/when-there-are-no-circular-import-and-exports.js | JavaScript | apache-2.0 | 9,659 |
import React from 'react';
import ComponentItem from './component-item';
export default function(props) {
return (
<ul className="component-list">
{props.items.map(item => {
return (
<ComponentItem key={item.id} name={item.name} experience={item.experience}/>
);
})}
</ul>
);
}
| dafobe/react-component-test | reactjs-component-test/app/components/views/component-list.js | JavaScript | apache-2.0 | 331 |
/**
* Copyright 2015 The AMP HTML Authors. 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.
*/
import {Timer} from '../../src/service/timer-impl';
import * as sinon from 'sinon';
describes.fakeWin('Timer', {}, env => {
let sandbox;
let windowMock;
let timer;
beforeEach(() => {
sandbox = sinon.sandbox.create();
const WindowApi = function() {};
WindowApi.prototype.setTimeout = function(unusedCallback, unusedDelay) {};
WindowApi.prototype.clearTimeout = function(unusedTimerId) {};
WindowApi.prototype.document = {};
const windowApi = new WindowApi();
windowMock = sandbox.mock(windowApi);
timer = new Timer(windowApi);
});
afterEach(() => {
windowMock.verify();
sandbox.restore();
});
it('delay', () => {
const handler = () => {};
windowMock.expects('setTimeout').returns(1).once();
windowMock.expects('clearTimeout').never();
timer.delay(handler, 111);
});
it('delay 0 real window', done => {
timer = new Timer(self);
timer.delay(done, 0);
});
it('delay 1 real window', done => {
timer = new Timer(self);
timer.delay(done, 1);
});
it('delay default', done => {
windowMock.expects('setTimeout').never();
windowMock.expects('clearTimeout').never();
timer.delay(done);
});
it('cancel', () => {
windowMock.expects('clearTimeout').withExactArgs(1).once();
timer.cancel(1);
});
it('cancel default', done => {
windowMock.expects('setTimeout').never();
windowMock.expects('clearTimeout').never();
const id = timer.delay(() => {
throw new Error('should have been cancelled');
});
timer.cancel(id);
// This makes sure the error has time to throw while this test
// is still running.
timer.delay(done);
});
it('promise', () => {
windowMock.expects('setTimeout').withExactArgs(sinon.match(value => {
value();
return true;
}), 111).returns(1).once();
let c = 0;
return timer.promise(111, 'A').then(result => {
c++;
expect(c).to.equal(1);
expect(result).to.equal('A');
});
});
it('timeoutPromise - no race', () => {
windowMock.expects('setTimeout').withExactArgs(sinon.match(value => {
value();
return true;
}), 111).returns(1).once();
let c = 0;
return timer.timeoutPromise(111).then(result => {
c++;
assert.fail('must never be here: ' + result);
}).catch(reason => {
c++;
expect(c).to.equal(1);
expect(reason.message).to.contain('timeout');
});
});
it('timeoutPromise - race no timeout', () => {
windowMock.expects('setTimeout').withExactArgs(sinon.match(unusedValue => {
// No timeout
return true;
}), 111).returns(1).once();
let c = 0;
return timer.timeoutPromise(111, Promise.resolve('A')).then(result => {
c++;
expect(c).to.equal(1);
expect(result).to.equal('A');
});
});
it('timeoutPromise - race with timeout', () => {
windowMock.expects('setTimeout').withExactArgs(sinon.match(value => {
// Immediate timeout
value();
return true;
}), 111).returns(1).once();
let c = 0;
return timer.timeoutPromise(111, new Promise(() => {})).then(result => {
c++;
assert.fail('must never be here: ' + result);
}).catch(reason => {
c++;
expect(c).to.equal(1);
expect(reason.message).to.contain('timeout');
});
});
it('poll - resolves only when condition is true', done => {
const realTimer = new Timer(env.win);
let predicate = false;
realTimer.poll(10, () => {
return predicate;
}).then(() => {
expect(predicate).to.be.true;
done();
});
setTimeout(() => {
predicate = true;
}, 15);
});
it('poll - clears out interval when complete', done => {
const realTimer = new Timer(env.win);
const clearIntervalStub = sandbox.stub();
env.win.clearInterval = clearIntervalStub;
realTimer.poll(111, () => {
return true;
}).then(() => {
expect(clearIntervalStub).to.have.been.calledOnce;
done();
});
});
});
| burtcorp/amphtml | test/functional/test-timer.js | JavaScript | apache-2.0 | 4,657 |
// modules are defined as an array
// [ module function, map of requireuires ]
//
// map of requireuires is short require name -> numeric require
//
// anything defined in a previous bundle is accessed via the
// orig method which is the requireuire for previous bundles
(function outer (modules, cache, entry) {
// Save the require from previous bundle to this closure if any
var previousRequire = typeof require == "function" && require;
function findProxyquireifyName() {
var deps = Object.keys(modules)
.map(function (k) { return modules[k][1]; });
for (var i = 0; i < deps.length; i++) {
var pq = deps[i]['proxyquireify'];
if (pq) return pq;
}
}
var proxyquireifyName = findProxyquireifyName();
function newRequire(name, jumped){
// Find the proxyquireify module, if present
var pqify = (proxyquireifyName != null) && cache[proxyquireifyName];
// Proxyquireify provides a separate cache that is used when inside
// a proxyquire call, and is set to null outside a proxyquire call.
// This allows the regular caching semantics to work correctly both
// inside and outside proxyquire calls while keeping the cached
// modules isolated.
// When switching from one proxyquire call to another, it clears
// the cache to prevent contamination between different sets
// of stubs.
var currentCache = (pqify && pqify.exports._cache) || cache;
if(!currentCache[name]) {
if(!modules[name]) {
// if we cannot find the the module within our internal map or
// cache jump to the current global require ie. the last bundle
// that was added to the page.
var currentRequire = typeof require == "function" && require;
if (!jumped && currentRequire) return currentRequire(name, true);
// If there are other bundles on this page the require from the
// previous one is saved to 'previousRequire'. Repeat this as
// many times as there are bundles until the module is found or
// we exhaust the require chain.
if (previousRequire) return previousRequire(name, true);
var err = new Error('Cannot find module \'' + name + '\'');
err.code = 'MODULE_NOT_FOUND';
throw err;
}
var m = currentCache[name] = {exports:{}};
// The normal browserify require function
var req = function(x){
var id = modules[name][1][x];
return newRequire(id ? id : x);
};
// The require function substituted for proxyquireify
var moduleRequire = function(x){
var pqify = (proxyquireifyName != null) && cache[proxyquireifyName];
// Only try to use the proxyquireify version if it has been `require`d
if (pqify && pqify.exports._proxy) {
return pqify.exports._proxy(req, x);
} else {
return req(x);
}
};
modules[name][0].call(m.exports,moduleRequire,m,m.exports,outer,modules,currentCache,entry);
}
return currentCache[name].exports;
}
for(var i=0;i<entry.length;i++) newRequire(entry[i]);
// Override the current require with this new one
return newRequire;
})
({1:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var ctor = ( typeof Float32Array === 'function' ) ? Float32Array : void 0; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = ctor;
},{}],2:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Typed array constructor which returns a typed array representing an array of single-precision floating-point numbers in the platform byte order.
*
* @module @stdlib/array/float32
*
* @example
* var ctor = require( '@stdlib/array/float32' );
*
* var arr = new ctor( 10 );
* // returns <Float32Array>
*/
// MODULES //
var hasFloat32ArraySupport = require( '@stdlib/assert/has-float32array-support' );
var builtin = require( './float32array.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var ctor;
if ( hasFloat32ArraySupport() ) {
ctor = builtin;
} else {
ctor = polyfill;
}
// EXPORTS //
module.exports = ctor;
},{"./float32array.js":1,"./polyfill.js":3,"@stdlib/assert/has-float32array-support":33}],3:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// TODO: write polyfill
// MAIN //
/**
* Typed array which represents an array of single-precision floating-point numbers in the platform byte order.
*
* @throws {Error} not implemented
*/
function polyfill() {
throw new Error( 'not implemented' );
}
// EXPORTS //
module.exports = polyfill;
},{}],4:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var ctor = ( typeof Float64Array === 'function' ) ? Float64Array : void 0; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = ctor;
},{}],5:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Typed array constructor which returns a typed array representing an array of double-precision floating-point numbers in the platform byte order.
*
* @module @stdlib/array/float64
*
* @example
* var ctor = require( '@stdlib/array/float64' );
*
* var arr = new ctor( 10 );
* // returns <Float64Array>
*/
// MODULES //
var hasFloat64ArraySupport = require( '@stdlib/assert/has-float64array-support' );
var builtin = require( './float64array.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var ctor;
if ( hasFloat64ArraySupport() ) {
ctor = builtin;
} else {
ctor = polyfill;
}
// EXPORTS //
module.exports = ctor;
},{"./float64array.js":4,"./polyfill.js":6,"@stdlib/assert/has-float64array-support":36}],6:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// TODO: write polyfill
// MAIN //
/**
* Typed array which represents an array of double-precision floating-point numbers in the platform byte order.
*
* @throws {Error} not implemented
*/
function polyfill() {
throw new Error( 'not implemented' );
}
// EXPORTS //
module.exports = polyfill;
},{}],7:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Typed array constructor which returns a typed array representing an array of twos-complement 16-bit signed integers in the platform byte order.
*
* @module @stdlib/array/int16
*
* @example
* var ctor = require( '@stdlib/array/int16' );
*
* var arr = new ctor( 10 );
* // returns <Int16Array>
*/
// MODULES //
var hasInt16ArraySupport = require( '@stdlib/assert/has-int16array-support' );
var builtin = require( './int16array.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var ctor;
if ( hasInt16ArraySupport() ) {
ctor = builtin;
} else {
ctor = polyfill;
}
// EXPORTS //
module.exports = ctor;
},{"./int16array.js":8,"./polyfill.js":9,"@stdlib/assert/has-int16array-support":41}],8:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var ctor = ( typeof Int16Array === 'function' ) ? Int16Array : void 0; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = ctor;
},{}],9:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// TODO: write polyfill
// MAIN //
/**
* Typed array which represents an array of twos-complement 16-bit signed integers in the platform byte order.
*
* @throws {Error} not implemented
*/
function polyfill() {
throw new Error( 'not implemented' );
}
// EXPORTS //
module.exports = polyfill;
},{}],10:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Typed array constructor which returns a typed array representing an array of twos-complement 32-bit signed integers in the platform byte order.
*
* @module @stdlib/array/int32
*
* @example
* var ctor = require( '@stdlib/array/int32' );
*
* var arr = new ctor( 10 );
* // returns <Int32Array>
*/
// MODULES //
var hasInt32ArraySupport = require( '@stdlib/assert/has-int32array-support' );
var builtin = require( './int32array.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var ctor;
if ( hasInt32ArraySupport() ) {
ctor = builtin;
} else {
ctor = polyfill;
}
// EXPORTS //
module.exports = ctor;
},{"./int32array.js":11,"./polyfill.js":12,"@stdlib/assert/has-int32array-support":44}],11:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var ctor = ( typeof Int32Array === 'function' ) ? Int32Array : void 0; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = ctor;
},{}],12:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// TODO: write polyfill
// MAIN //
/**
* Typed array which represents an array of twos-complement 32-bit signed integers in the platform byte order.
*
* @throws {Error} not implemented
*/
function polyfill() {
throw new Error( 'not implemented' );
}
// EXPORTS //
module.exports = polyfill;
},{}],13:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Typed array constructor which returns a typed array representing an array of twos-complement 8-bit signed integers in the platform byte order.
*
* @module @stdlib/array/int8
*
* @example
* var ctor = require( '@stdlib/array/int8' );
*
* var arr = new ctor( 10 );
* // returns <Int8Array>
*/
// MODULES //
var hasInt8ArraySupport = require( '@stdlib/assert/has-int8array-support' );
var builtin = require( './int8array.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var ctor;
if ( hasInt8ArraySupport() ) {
ctor = builtin;
} else {
ctor = polyfill;
}
// EXPORTS //
module.exports = ctor;
},{"./int8array.js":14,"./polyfill.js":15,"@stdlib/assert/has-int8array-support":47}],14:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var ctor = ( typeof Int8Array === 'function' ) ? Int8Array : void 0; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = ctor;
},{}],15:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// TODO: write polyfill
// MAIN //
/**
* Typed array which represents an array of twos-complement 8-bit signed integers in the platform byte order.
*
* @throws {Error} not implemented
*/
function polyfill() {
throw new Error( 'not implemented' );
}
// EXPORTS //
module.exports = polyfill;
},{}],16:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var Int8Array = require( '@stdlib/array/int8' );
var Uint8Array = require( '@stdlib/array/uint8' );
var Uint8ClampedArray = require( '@stdlib/array/uint8c' );
var Int16Array = require( '@stdlib/array/int16' );
var Uint16Array = require( '@stdlib/array/uint16' );
var Int32Array = require( '@stdlib/array/int32' );
var Uint32Array = require( '@stdlib/array/uint32' );
var Float32Array = require( '@stdlib/array/float32' );
var Float64Array = require( '@stdlib/array/float64' );
// MAIN //
var CTORS = [
[ Float64Array, 'Float64Array' ],
[ Float32Array, 'Float32Array' ],
[ Int32Array, 'Int32Array' ],
[ Uint32Array, 'Uint32Array' ],
[ Int16Array, 'Int16Array' ],
[ Uint16Array, 'Uint16Array' ],
[ Int8Array, 'Int8Array' ],
[ Uint8Array, 'Uint8Array' ],
[ Uint8ClampedArray, 'Uint8ClampedArray' ]
];
// EXPORTS //
module.exports = CTORS;
},{"@stdlib/array/float32":2,"@stdlib/array/float64":5,"@stdlib/array/int16":7,"@stdlib/array/int32":10,"@stdlib/array/int8":13,"@stdlib/array/uint16":20,"@stdlib/array/uint32":23,"@stdlib/array/uint8":26,"@stdlib/array/uint8c":29}],17:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Return a JSON representation of a typed array.
*
* @module @stdlib/array/to-json
*
* @example
* var Float64Array = require( '@stdlib/array/float64' );
* var toJSON = require( '@stdlib/array/to-json' );
*
* var arr = new Float64Array( [ 5.0, 3.0 ] );
* var json = toJSON( arr );
* // returns { 'type': 'Float64Array', 'data': [ 5.0, 3.0 ] }
*/
// MODULES //
var toJSON = require( './to_json.js' );
// EXPORTS //
module.exports = toJSON;
},{"./to_json.js":18}],18:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isTypedArray = require( '@stdlib/assert/is-typed-array' );
var typeName = require( './type.js' );
// MAIN //
/**
* Returns a JSON representation of a typed array.
*
* ## Notes
*
* - We build a JSON object representing a typed array similar to how Node.js `Buffer` objects are represented. See [Buffer][1].
*
* [1]: https://nodejs.org/api/buffer.html#buffer_buf_tojson
*
* @param {TypedArray} arr - typed array to serialize
* @throws {TypeError} first argument must be a typed array
* @returns {Object} JSON representation
*
* @example
* var Float64Array = require( '@stdlib/array/float64' );
*
* var arr = new Float64Array( [ 5.0, 3.0 ] );
* var json = toJSON( arr );
* // returns { 'type': 'Float64Array', 'data': [ 5.0, 3.0 ] }
*/
function toJSON( arr ) {
var out;
var i;
if ( !isTypedArray( arr ) ) {
throw new TypeError( 'invalid argument. Must provide a typed array. Value: `' + arr + '`.' );
}
out = {};
out.type = typeName( arr );
out.data = [];
for ( i = 0; i < arr.length; i++ ) {
out.data.push( arr[ i ] );
}
return out;
}
// EXPORTS //
module.exports = toJSON;
},{"./type.js":19,"@stdlib/assert/is-typed-array":169}],19:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var instanceOf = require( '@stdlib/assert/instance-of' );
var ctorName = require( '@stdlib/utils/constructor-name' );
var getPrototypeOf = require( '@stdlib/utils/get-prototype-of' );
var CTORS = require( './ctors.js' );
// MAIN //
/**
* Returns the typed array type.
*
* @private
* @param {TypedArray} arr - typed array
* @returns {(string|void)} typed array type
*
* @example
* var Float64Array = require( '@stdlib/array/float64' );
*
* var arr = new Float64Array( 5 );
* var str = typeName( arr );
* // returns 'Float64Array'
*/
function typeName( arr ) {
var v;
var i;
// Check for typed array objects from the same realm (same Node.js `vm` or same `Window` object)...
for ( i = 0; i < CTORS.length; i++ ) {
if ( instanceOf( arr, CTORS[ i ][ 0 ] ) ) {
return CTORS[ i ][ 1 ];
}
}
// Walk the prototype tree until we find an object having a desired native class...
while ( arr ) {
v = ctorName( arr );
for ( i = 0; i < CTORS.length; i++ ) {
if ( v === CTORS[ i ][ 1 ] ) {
return CTORS[ i ][ 1 ];
}
}
arr = getPrototypeOf( arr );
}
}
// EXPORTS //
module.exports = typeName;
},{"./ctors.js":16,"@stdlib/assert/instance-of":71,"@stdlib/utils/constructor-name":418,"@stdlib/utils/get-prototype-of":447}],20:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Typed array constructor which returns a typed array representing an array of 16-bit unsigned integers in the platform byte order.
*
* @module @stdlib/array/uint16
*
* @example
* var ctor = require( '@stdlib/array/uint16' );
*
* var arr = new ctor( 10 );
* // returns <Uint16Array>
*/
// MODULES //
var hasUint16ArraySupport = require( '@stdlib/assert/has-uint16array-support' );
var builtin = require( './uint16array.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var ctor;
if ( hasUint16ArraySupport() ) {
ctor = builtin;
} else {
ctor = polyfill;
}
// EXPORTS //
module.exports = ctor;
},{"./polyfill.js":21,"./uint16array.js":22,"@stdlib/assert/has-uint16array-support":59}],21:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// TODO: write polyfill
// MAIN //
/**
* Typed array which represents an array of 16-bit unsigned integers in the platform byte order.
*
* @throws {Error} not implemented
*/
function polyfill() {
throw new Error( 'not implemented' );
}
// EXPORTS //
module.exports = polyfill;
},{}],22:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var ctor = ( typeof Uint16Array === 'function' ) ? Uint16Array : void 0; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = ctor;
},{}],23:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Typed array constructor which returns a typed array representing an array of 32-bit unsigned integers in the platform byte order.
*
* @module @stdlib/array/uint32
*
* @example
* var ctor = require( '@stdlib/array/uint32' );
*
* var arr = new ctor( 10 );
* // returns <Uint32Array>
*/
// MODULES //
var hasUint32ArraySupport = require( '@stdlib/assert/has-uint32array-support' );
var builtin = require( './uint32array.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var ctor;
if ( hasUint32ArraySupport() ) {
ctor = builtin;
} else {
ctor = polyfill;
}
// EXPORTS //
module.exports = ctor;
},{"./polyfill.js":24,"./uint32array.js":25,"@stdlib/assert/has-uint32array-support":62}],24:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// TODO: write polyfill
// MAIN //
/**
* Typed array which represents an array of 32-bit unsigned integers in the platform byte order.
*
* @throws {Error} not implemented
*/
function polyfill() {
throw new Error( 'not implemented' );
}
// EXPORTS //
module.exports = polyfill;
},{}],25:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var ctor = ( typeof Uint32Array === 'function' ) ? Uint32Array : void 0; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = ctor;
},{}],26:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Typed array constructor which returns a typed array representing an array of 8-bit unsigned integers in the platform byte order.
*
* @module @stdlib/array/uint8
*
* @example
* var ctor = require( '@stdlib/array/uint8' );
*
* var arr = new ctor( 10 );
* // returns <Uint8Array>
*/
// MODULES //
var hasUint8ArraySupport = require( '@stdlib/assert/has-uint8array-support' );
var builtin = require( './uint8array.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var ctor;
if ( hasUint8ArraySupport() ) {
ctor = builtin;
} else {
ctor = polyfill;
}
// EXPORTS //
module.exports = ctor;
},{"./polyfill.js":27,"./uint8array.js":28,"@stdlib/assert/has-uint8array-support":65}],27:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// TODO: write polyfill
// MAIN //
/**
* Typed array which represents an array of 8-bit unsigned integers in the platform byte order.
*
* @throws {Error} not implemented
*/
function polyfill() {
throw new Error( 'not implemented' );
}
// EXPORTS //
module.exports = polyfill;
},{}],28:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var ctor = ( typeof Uint8Array === 'function' ) ? Uint8Array : void 0; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = ctor;
},{}],29:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Typed array constructor which returns a typed array representing an array of 8-bit unsigned integers in the platform byte order clamped to 0-255.
*
* @module @stdlib/array/uint8c
*
* @example
* var ctor = require( '@stdlib/array/uint8c' );
*
* var arr = new ctor( 10 );
* // returns <Uint8ClampedArray>
*/
// MODULES //
var hasUint8ClampedArraySupport = require( '@stdlib/assert/has-uint8clampedarray-support' ); // eslint-disable-line id-length
var builtin = require( './uint8clampedarray.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var ctor;
if ( hasUint8ClampedArraySupport() ) {
ctor = builtin;
} else {
ctor = polyfill;
}
// EXPORTS //
module.exports = ctor;
},{"./polyfill.js":30,"./uint8clampedarray.js":31,"@stdlib/assert/has-uint8clampedarray-support":68}],30:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// TODO: write polyfill
// MAIN //
/**
* Typed array which represents an array of 8-bit unsigned integers in the platform byte order clamped to 0-255.
*
* @throws {Error} not implemented
*/
function polyfill() {
throw new Error( 'not implemented' );
}
// EXPORTS //
module.exports = polyfill;
},{}],31:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var ctor = ( typeof Uint8ClampedArray === 'function' ) ? Uint8ClampedArray : void 0; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = ctor;
},{}],32:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var main = ( typeof Float32Array === 'function' ) ? Float32Array : null; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = main;
},{}],33:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test for native `Float32Array` support.
*
* @module @stdlib/assert/has-float32array-support
*
* @example
* var hasFloat32ArraySupport = require( '@stdlib/assert/has-float32array-support' );
*
* var bool = hasFloat32ArraySupport();
* // returns <boolean>
*/
// MODULES //
var hasFloat32ArraySupport = require( './main.js' );
// EXPORTS //
module.exports = hasFloat32ArraySupport;
},{"./main.js":34}],34:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isFloat32Array = require( '@stdlib/assert/is-float32array' );
var PINF = require( '@stdlib/constants/float64/pinf' );
var GlobalFloat32Array = require( './float32array.js' );
// MAIN //
/**
* Tests for native `Float32Array` support.
*
* @returns {boolean} boolean indicating if an environment has `Float32Array` support
*
* @example
* var bool = hasFloat32ArraySupport();
* // returns <boolean>
*/
function hasFloat32ArraySupport() {
var bool;
var arr;
if ( typeof GlobalFloat32Array !== 'function' ) {
return false;
}
// Test basic support...
try {
arr = new GlobalFloat32Array( [ 1.0, 3.14, -3.14, 5.0e40 ] );
bool = (
isFloat32Array( arr ) &&
arr[ 0 ] === 1.0 &&
arr[ 1 ] === 3.140000104904175 &&
arr[ 2 ] === -3.140000104904175 &&
arr[ 3 ] === PINF
);
} catch ( err ) { // eslint-disable-line no-unused-vars
bool = false;
}
return bool;
}
// EXPORTS //
module.exports = hasFloat32ArraySupport;
},{"./float32array.js":32,"@stdlib/assert/is-float32array":98,"@stdlib/constants/float64/pinf":255}],35:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var main = ( typeof Float64Array === 'function' ) ? Float64Array : null; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = main;
},{}],36:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test for native `Float64Array` support.
*
* @module @stdlib/assert/has-float64array-support
*
* @example
* var hasFloat64ArraySupport = require( '@stdlib/assert/has-float64array-support' );
*
* var bool = hasFloat64ArraySupport();
* // returns <boolean>
*/
// MODULES //
var hasFloat64ArraySupport = require( './main.js' );
// EXPORTS //
module.exports = hasFloat64ArraySupport;
},{"./main.js":37}],37:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isFloat64Array = require( '@stdlib/assert/is-float64array' );
var GlobalFloat64Array = require( './float64array.js' );
// MAIN //
/**
* Tests for native `Float64Array` support.
*
* @returns {boolean} boolean indicating if an environment has `Float64Array` support
*
* @example
* var bool = hasFloat64ArraySupport();
* // returns <boolean>
*/
function hasFloat64ArraySupport() {
var bool;
var arr;
if ( typeof GlobalFloat64Array !== 'function' ) {
return false;
}
// Test basic support...
try {
arr = new GlobalFloat64Array( [ 1.0, 3.14, -3.14, NaN ] );
bool = (
isFloat64Array( arr ) &&
arr[ 0 ] === 1.0 &&
arr[ 1 ] === 3.14 &&
arr[ 2 ] === -3.14 &&
arr[ 3 ] !== arr[ 3 ]
);
} catch ( err ) { // eslint-disable-line no-unused-vars
bool = false;
}
return bool;
}
// EXPORTS //
module.exports = hasFloat64ArraySupport;
},{"./float64array.js":35,"@stdlib/assert/is-float64array":100}],38:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Dummy function.
*
* @private
*/
function foo() {
// No-op...
}
// EXPORTS //
module.exports = foo;
},{}],39:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test for native function `name` support.
*
* @module @stdlib/assert/has-function-name-support
*
* @example
* var hasFunctionNameSupport = require( '@stdlib/assert/has-function-name-support' );
*
* var bool = hasFunctionNameSupport();
* // returns <boolean>
*/
// MODULES //
var hasFunctionNameSupport = require( './main.js' );
// EXPORTS //
module.exports = hasFunctionNameSupport;
},{"./main.js":40}],40:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var foo = require( './foo.js' );
// MAIN //
/**
* Tests for native function `name` support.
*
* @returns {boolean} boolean indicating if an environment has function `name` support
*
* @example
* var bool = hasFunctionNameSupport();
* // returns <boolean>
*/
function hasFunctionNameSupport() {
return ( foo.name === 'foo' );
}
// EXPORTS //
module.exports = hasFunctionNameSupport;
},{"./foo.js":38}],41:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test for native `Int16Array` support.
*
* @module @stdlib/assert/has-int16array-support
*
* @example
* var hasInt16ArraySupport = require( '@stdlib/assert/has-int16array-support' );
*
* var bool = hasInt16ArraySupport();
* // returns <boolean>
*/
// MODULES //
var hasInt16ArraySupport = require( './main.js' );
// EXPORTS //
module.exports = hasInt16ArraySupport;
},{"./main.js":43}],42:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var main = ( typeof Int16Array === 'function' ) ? Int16Array : null; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = main;
},{}],43:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isInt16Array = require( '@stdlib/assert/is-int16array' );
var INT16_MAX = require( '@stdlib/constants/int16/max' );
var INT16_MIN = require( '@stdlib/constants/int16/min' );
var GlobalInt16Array = require( './int16array.js' );
// MAIN //
/**
* Tests for native `Int16Array` support.
*
* @returns {boolean} boolean indicating if an environment has `Int16Array` support
*
* @example
* var bool = hasInt16ArraySupport();
* // returns <boolean>
*/
function hasInt16ArraySupport() {
var bool;
var arr;
if ( typeof GlobalInt16Array !== 'function' ) {
return false;
}
// Test basic support...
try {
arr = new GlobalInt16Array( [ 1, 3.14, -3.14, INT16_MAX+1 ] );
bool = (
isInt16Array( arr ) &&
arr[ 0 ] === 1 &&
arr[ 1 ] === 3 && // truncation
arr[ 2 ] === -3 && // truncation
arr[ 3 ] === INT16_MIN // wrap around
);
} catch ( err ) { // eslint-disable-line no-unused-vars
bool = false;
}
return bool;
}
// EXPORTS //
module.exports = hasInt16ArraySupport;
},{"./int16array.js":42,"@stdlib/assert/is-int16array":104,"@stdlib/constants/int16/max":257,"@stdlib/constants/int16/min":258}],44:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test for native `Int32Array` support.
*
* @module @stdlib/assert/has-int32array-support
*
* @example
* var hasInt32ArraySupport = require( '@stdlib/assert/has-int32array-support' );
*
* var bool = hasInt32ArraySupport();
* // returns <boolean>
*/
// MODULES //
var hasInt32ArraySupport = require( './main.js' );
// EXPORTS //
module.exports = hasInt32ArraySupport;
},{"./main.js":46}],45:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var main = ( typeof Int32Array === 'function' ) ? Int32Array : null; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = main;
},{}],46:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isInt32Array = require( '@stdlib/assert/is-int32array' );
var INT32_MAX = require( '@stdlib/constants/int32/max' );
var INT32_MIN = require( '@stdlib/constants/int32/min' );
var GlobalInt32Array = require( './int32array.js' );
// MAIN //
/**
* Tests for native `Int32Array` support.
*
* @returns {boolean} boolean indicating if an environment has `Int32Array` support
*
* @example
* var bool = hasInt32ArraySupport();
* // returns <boolean>
*/
function hasInt32ArraySupport() {
var bool;
var arr;
if ( typeof GlobalInt32Array !== 'function' ) {
return false;
}
// Test basic support...
try {
arr = new GlobalInt32Array( [ 1, 3.14, -3.14, INT32_MAX+1 ] );
bool = (
isInt32Array( arr ) &&
arr[ 0 ] === 1 &&
arr[ 1 ] === 3 && // truncation
arr[ 2 ] === -3 && // truncation
arr[ 3 ] === INT32_MIN // wrap around
);
} catch ( err ) { // eslint-disable-line no-unused-vars
bool = false;
}
return bool;
}
// EXPORTS //
module.exports = hasInt32ArraySupport;
},{"./int32array.js":45,"@stdlib/assert/is-int32array":106,"@stdlib/constants/int32/max":259,"@stdlib/constants/int32/min":260}],47:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test for native `Int8Array` support.
*
* @module @stdlib/assert/has-int8array-support
*
* @example
* var hasInt8ArraySupport = require( '@stdlib/assert/has-int8array-support' );
*
* var bool = hasInt8ArraySupport();
* // returns <boolean>
*/
// MODULES //
var hasInt8ArraySupport = require( './main.js' );
// EXPORTS //
module.exports = hasInt8ArraySupport;
},{"./main.js":49}],48:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var main = ( typeof Int8Array === 'function' ) ? Int8Array : null; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = main;
},{}],49:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isInt8Array = require( '@stdlib/assert/is-int8array' );
var INT8_MAX = require( '@stdlib/constants/int8/max' );
var INT8_MIN = require( '@stdlib/constants/int8/min' );
var GlobalInt8Array = require( './int8array.js' );
// MAIN //
/**
* Tests for native `Int8Array` support.
*
* @returns {boolean} boolean indicating if an environment has `Int8Array` support
*
* @example
* var bool = hasInt8ArraySupport();
* // returns <boolean>
*/
function hasInt8ArraySupport() {
var bool;
var arr;
if ( typeof GlobalInt8Array !== 'function' ) {
return false;
}
// Test basic support...
try {
arr = new GlobalInt8Array( [ 1, 3.14, -3.14, INT8_MAX+1 ] );
bool = (
isInt8Array( arr ) &&
arr[ 0 ] === 1 &&
arr[ 1 ] === 3 && // truncation
arr[ 2 ] === -3 && // truncation
arr[ 3 ] === INT8_MIN // wrap around
);
} catch ( err ) { // eslint-disable-line no-unused-vars
bool = false;
}
return bool;
}
// EXPORTS //
module.exports = hasInt8ArraySupport;
},{"./int8array.js":48,"@stdlib/assert/is-int8array":108,"@stdlib/constants/int8/max":261,"@stdlib/constants/int8/min":262}],50:[function(require,module,exports){
(function (Buffer){(function (){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var main = ( typeof Buffer === 'function' ) ? Buffer : null; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = main;
}).call(this)}).call(this,require("buffer").Buffer)
},{"buffer":514}],51:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test for native `Buffer` support.
*
* @module @stdlib/assert/has-node-buffer-support
*
* @example
* var hasNodeBufferSupport = require( '@stdlib/assert/has-node-buffer-support' );
*
* var bool = hasNodeBufferSupport();
* // returns <boolean>
*/
// MODULES //
var hasNodeBufferSupport = require( './main.js' );
// EXPORTS //
module.exports = hasNodeBufferSupport;
},{"./main.js":52}],52:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isBuffer = require( '@stdlib/assert/is-buffer' );
var GlobalBuffer = require( './buffer.js' );
// MAIN //
/**
* Tests for native `Buffer` support.
*
* @returns {boolean} boolean indicating if an environment has `Buffer` support
*
* @example
* var bool = hasNodeBufferSupport();
* // returns <boolean>
*/
function hasNodeBufferSupport() {
var bool;
var b;
if ( typeof GlobalBuffer !== 'function' ) {
return false;
}
// Test basic support...
try {
if ( typeof GlobalBuffer.from === 'function' ) {
b = GlobalBuffer.from( [ 1, 2, 3, 4 ] );
} else {
b = new GlobalBuffer( [ 1, 2, 3, 4 ] ); // Note: this is deprecated behavior starting in Node v6 (see https://nodejs.org/api/buffer.html#buffer_new_buffer_array)
}
bool = (
isBuffer( b ) &&
b[ 0 ] === 1 &&
b[ 1 ] === 2 &&
b[ 2 ] === 3 &&
b[ 3 ] === 4
);
} catch ( err ) { // eslint-disable-line no-unused-vars
bool = false;
}
return bool;
}
// EXPORTS //
module.exports = hasNodeBufferSupport;
},{"./buffer.js":50,"@stdlib/assert/is-buffer":88}],53:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test whether an object has a specified property.
*
* @module @stdlib/assert/has-own-property
*
* @example
* var hasOwnProp = require( '@stdlib/assert/has-own-property' );
*
* var beep = {
* 'boop': true
* };
*
* var bool = hasOwnProp( beep, 'boop' );
* // returns true
*
* bool = hasOwnProp( beep, 'bop' );
* // returns false
*/
// MODULES //
var hasOwnProp = require( './main.js' );
// EXPORTS //
module.exports = hasOwnProp;
},{"./main.js":54}],54:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// FUNCTIONS //
var has = Object.prototype.hasOwnProperty;
// MAIN //
/**
* Tests if an object has a specified property.
*
* @param {*} value - value to test
* @param {*} property - property to test
* @returns {boolean} boolean indicating if an object has a specified property
*
* @example
* var beep = {
* 'boop': true
* };
*
* var bool = hasOwnProp( beep, 'boop' );
* // returns true
*
* @example
* var beep = {
* 'boop': true
* };
*
* var bool = hasOwnProp( beep, 'bap' );
* // returns false
*/
function hasOwnProp( value, property ) {
if (
value === void 0 ||
value === null
) {
return false;
}
return has.call( value, property );
}
// EXPORTS //
module.exports = hasOwnProp;
},{}],55:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test for native `Symbol` support.
*
* @module @stdlib/assert/has-symbol-support
*
* @example
* var hasSymbolSupport = require( '@stdlib/assert/has-symbol-support' );
*
* var bool = hasSymbolSupport();
* // returns <boolean>
*/
// MODULES //
var hasSymbolSupport = require( './main.js' );
// EXPORTS //
module.exports = hasSymbolSupport;
},{"./main.js":56}],56:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Tests for native `Symbol` support.
*
* @returns {boolean} boolean indicating if an environment has `Symbol` support
*
* @example
* var bool = hasSymbolSupport();
* // returns <boolean>
*/
function hasSymbolSupport() {
return (
typeof Symbol === 'function' &&
typeof Symbol( 'foo' ) === 'symbol'
);
}
// EXPORTS //
module.exports = hasSymbolSupport;
},{}],57:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test for native `toStringTag` support.
*
* @module @stdlib/assert/has-tostringtag-support
*
* @example
* var hasToStringTagSupport = require( '@stdlib/assert/has-tostringtag-support' );
*
* var bool = hasToStringTagSupport();
* // returns <boolean>
*/
// MODULES //
var hasToStringTagSupport = require( './main.js' );
// EXPORTS //
module.exports = hasToStringTagSupport;
},{"./main.js":58}],58:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var hasSymbols = require( '@stdlib/assert/has-symbol-support' );
// VARIABLES //
var FLG = hasSymbols();
// MAIN //
/**
* Tests for native `toStringTag` support.
*
* @returns {boolean} boolean indicating if an environment has `toStringTag` support
*
* @example
* var bool = hasToStringTagSupport();
* // returns <boolean>
*/
function hasToStringTagSupport() {
return ( FLG && typeof Symbol.toStringTag === 'symbol' );
}
// EXPORTS //
module.exports = hasToStringTagSupport;
},{"@stdlib/assert/has-symbol-support":55}],59:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test for native `Uint16Array` support.
*
* @module @stdlib/assert/has-uint16array-support
*
* @example
* var hasUint16ArraySupport = require( '@stdlib/assert/has-uint16array-support' );
*
* var bool = hasUint16ArraySupport();
* // returns <boolean>
*/
// MODULES //
var hasUint16ArraySupport = require( './main.js' );
// EXPORTS //
module.exports = hasUint16ArraySupport;
},{"./main.js":60}],60:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isUint16Array = require( '@stdlib/assert/is-uint16array' );
var UINT16_MAX = require( '@stdlib/constants/uint16/max' );
var GlobalUint16Array = require( './uint16array.js' );
// MAIN //
/**
* Tests for native `Uint16Array` support.
*
* @returns {boolean} boolean indicating if an environment has `Uint16Array` support
*
* @example
* var bool = hasUint16ArraySupport();
* // returns <boolean>
*/
function hasUint16ArraySupport() {
var bool;
var arr;
if ( typeof GlobalUint16Array !== 'function' ) {
return false;
}
// Test basic support...
try {
arr = [ 1, 3.14, -3.14, UINT16_MAX+1, UINT16_MAX+2 ];
arr = new GlobalUint16Array( arr );
bool = (
isUint16Array( arr ) &&
arr[ 0 ] === 1 &&
arr[ 1 ] === 3 && // truncation
arr[ 2 ] === UINT16_MAX-2 && // truncation and wrap around
arr[ 3 ] === 0 && // wrap around
arr[ 4 ] === 1 // wrap around
);
} catch ( err ) { // eslint-disable-line no-unused-vars
bool = false;
}
return bool;
}
// EXPORTS //
module.exports = hasUint16ArraySupport;
},{"./uint16array.js":61,"@stdlib/assert/is-uint16array":172,"@stdlib/constants/uint16/max":263}],61:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var main = ( typeof Uint16Array === 'function' ) ? Uint16Array : null; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = main;
},{}],62:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test for native `Uint32Array` support.
*
* @module @stdlib/assert/has-uint32array-support
*
* @example
* var hasUint32ArraySupport = require( '@stdlib/assert/has-uint32array-support' );
*
* var bool = hasUint32ArraySupport();
* // returns <boolean>
*/
// MODULES //
var hasUint32ArraySupport = require( './main.js' );
// EXPORTS //
module.exports = hasUint32ArraySupport;
},{"./main.js":63}],63:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isUint32Array = require( '@stdlib/assert/is-uint32array' );
var UINT32_MAX = require( '@stdlib/constants/uint32/max' );
var GlobalUint32Array = require( './uint32array.js' );
// MAIN //
/**
* Tests for native `Uint32Array` support.
*
* @returns {boolean} boolean indicating if an environment has `Uint32Array` support
*
* @example
* var bool = hasUint32ArraySupport();
* // returns <boolean>
*/
function hasUint32ArraySupport() {
var bool;
var arr;
if ( typeof GlobalUint32Array !== 'function' ) {
return false;
}
// Test basic support...
try {
arr = [ 1, 3.14, -3.14, UINT32_MAX+1, UINT32_MAX+2 ];
arr = new GlobalUint32Array( arr );
bool = (
isUint32Array( arr ) &&
arr[ 0 ] === 1 &&
arr[ 1 ] === 3 && // truncation
arr[ 2 ] === UINT32_MAX-2 && // truncation and wrap around
arr[ 3 ] === 0 && // wrap around
arr[ 4 ] === 1 // wrap around
);
} catch ( err ) { // eslint-disable-line no-unused-vars
bool = false;
}
return bool;
}
// EXPORTS //
module.exports = hasUint32ArraySupport;
},{"./uint32array.js":64,"@stdlib/assert/is-uint32array":174,"@stdlib/constants/uint32/max":264}],64:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var main = ( typeof Uint32Array === 'function' ) ? Uint32Array : null; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = main;
},{}],65:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test for native `Uint8Array` support.
*
* @module @stdlib/assert/has-uint8array-support
*
* @example
* var hasUint8ArraySupport = require( '@stdlib/assert/has-uint8array-support' );
*
* var bool = hasUint8ArraySupport();
* // returns <boolean>
*/
// MODULES //
var hasUint8ArraySupport = require( './main.js' );
// EXPORTS //
module.exports = hasUint8ArraySupport;
},{"./main.js":66}],66:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isUint8Array = require( '@stdlib/assert/is-uint8array' );
var UINT8_MAX = require( '@stdlib/constants/uint8/max' );
var GlobalUint8Array = require( './uint8array.js' );
// MAIN //
/**
* Tests for native `Uint8Array` support.
*
* @returns {boolean} boolean indicating if an environment has `Uint8Array` support
*
* @example
* var bool = hasUint8ArraySupport();
* // returns <boolean>
*/
function hasUint8ArraySupport() {
var bool;
var arr;
if ( typeof GlobalUint8Array !== 'function' ) {
return false;
}
// Test basic support...
try {
arr = [ 1, 3.14, -3.14, UINT8_MAX+1, UINT8_MAX+2 ];
arr = new GlobalUint8Array( arr );
bool = (
isUint8Array( arr ) &&
arr[ 0 ] === 1 &&
arr[ 1 ] === 3 && // truncation
arr[ 2 ] === UINT8_MAX-2 && // truncation and wrap around
arr[ 3 ] === 0 && // wrap around
arr[ 4 ] === 1 // wrap around
);
} catch ( err ) { // eslint-disable-line no-unused-vars
bool = false;
}
return bool;
}
// EXPORTS //
module.exports = hasUint8ArraySupport;
},{"./uint8array.js":67,"@stdlib/assert/is-uint8array":176,"@stdlib/constants/uint8/max":265}],67:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var main = ( typeof Uint8Array === 'function' ) ? Uint8Array : null; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = main;
},{}],68:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test for native `Uint8ClampedArray` support.
*
* @module @stdlib/assert/has-uint8clampedarray-support
*
* @example
* var hasUint8ClampedArraySupport = require( '@stdlib/assert/has-uint8clampedarray-support' );
*
* var bool = hasUint8ClampedArraySupport();
* // returns <boolean>
*/
// MODULES //
var hasUint8ClampedArraySupport = require( './main.js' );
// EXPORTS //
module.exports = hasUint8ClampedArraySupport;
},{"./main.js":69}],69:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isUint8ClampedArray = require( '@stdlib/assert/is-uint8clampedarray' );
var GlobalUint8ClampedArray = require( './uint8clampedarray.js' );
// MAIN //
/**
* Tests for native `Uint8ClampedArray` support.
*
* @returns {boolean} boolean indicating if an environment has `Uint8ClampedArray` support
*
* @example
* var bool = hasUint8ClampedArraySupport();
* // returns <boolean>
*/
function hasUint8ClampedArraySupport() { // eslint-disable-line id-length
var bool;
var arr;
if ( typeof GlobalUint8ClampedArray !== 'function' ) {
return false;
}
// Test basic support...
try {
arr = new GlobalUint8ClampedArray( [ -1, 0, 1, 3.14, 4.99, 255, 256 ] );
bool = (
isUint8ClampedArray( arr ) &&
arr[ 0 ] === 0 && // clamped
arr[ 1 ] === 0 &&
arr[ 2 ] === 1 &&
arr[ 3 ] === 3 && // round to nearest
arr[ 4 ] === 5 && // round to nearest
arr[ 5 ] === 255 &&
arr[ 6 ] === 255 // clamped
);
} catch ( err ) { // eslint-disable-line no-unused-vars
bool = false;
}
return bool;
}
// EXPORTS //
module.exports = hasUint8ClampedArraySupport;
},{"./uint8clampedarray.js":70,"@stdlib/assert/is-uint8clampedarray":178}],70:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var main = ( typeof Uint8ClampedArray === 'function' ) ? Uint8ClampedArray : null; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = main;
},{}],71:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test whether a value has in its prototype chain a specified constructor as a prototype property.
*
* @module @stdlib/assert/instance-of
*
* @example
* var instanceOf = require( '@stdlib/assert/instance-of' );
*
* var bool = instanceOf( [], Array );
* // returns true
*
* bool = instanceOf( {}, Object ); // exception
* // returns true
*
* bool = instanceOf( 'beep', String );
* // returns false
*
* bool = instanceOf( null, Object );
* // returns false
*
* bool = instanceOf( 5, Object );
* // returns false
*/
// MODULES //
var instanceOf = require( './main.js' );
// EXPORTS //
module.exports = instanceOf;
},{"./main.js":72}],72:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Tests whether a value has in its prototype chain a specified constructor as a prototype property.
*
* @param {*} value - value to test
* @param {Function} constructor - constructor to test against
* @throws {TypeError} constructor must be callable
* @returns {boolean} boolean indicating whether a value is an instance of a provided constructor
*
* @example
* var bool = instanceOf( [], Array );
* // returns true
*
* @example
* var bool = instanceOf( {}, Object ); // exception
* // returns true
*
* @example
* var bool = instanceOf( 'beep', String );
* // returns false
*
* @example
* var bool = instanceOf( null, Object );
* // returns false
*
* @example
* var bool = instanceOf( 5, Object );
* // returns false
*/
function instanceOf( value, constructor ) {
// TODO: replace with `isCallable` check
if ( typeof constructor !== 'function' ) {
throw new TypeError( 'invalid argument. `constructor` argument must be callable. Value: `'+constructor+'`.' );
}
return ( value instanceof constructor );
}
// EXPORTS //
module.exports = instanceOf;
},{}],73:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isArguments = require( './main.js' );
// VARIABLES //
var bool;
// FUNCTIONS //
/**
* Detects whether an environment returns the expected internal class of the `arguments` object.
*
* @private
* @returns {boolean} boolean indicating whether an environment behaves as expected
*
* @example
* var bool = detect();
* // returns <boolean>
*/
function detect() {
return isArguments( arguments );
}
// MAIN //
bool = detect();
// EXPORTS //
module.exports = bool;
},{"./main.js":75}],74:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is an `arguments` object.
*
* @module @stdlib/assert/is-arguments
*
* @example
* var isArguments = require( '@stdlib/assert/is-arguments' );
*
* function foo() {
* return arguments;
* }
*
* var bool = isArguments( foo() );
* // returns true
*
* bool = isArguments( [] );
* // returns false
*/
// MODULES //
var hasArgumentsClass = require( './detect.js' );
var main = require( './main.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var isArguments;
if ( hasArgumentsClass ) {
isArguments = main;
} else {
isArguments = polyfill;
}
// EXPORTS //
module.exports = isArguments;
},{"./detect.js":73,"./main.js":75,"./polyfill.js":76}],75:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var nativeClass = require( '@stdlib/utils/native-class' );
// MAIN //
/**
* Tests whether a value is an `arguments` object.
*
* @private
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether a value is an `arguments` object
*
* @example
* function foo() {
* return arguments;
* }
*
* var bool = isArguments( foo() );
* // returns true
*
* @example
* var bool = isArguments( [] );
* // returns false
*/
function isArguments( value ) {
return ( nativeClass( value ) === '[object Arguments]' );
}
// EXPORTS //
module.exports = isArguments;
},{"@stdlib/utils/native-class":481}],76:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var isEnumerableProperty = require( '@stdlib/assert/is-enumerable-property' );
var isArray = require( '@stdlib/assert/is-array' );
var isInteger = require( '@stdlib/math/base/assert/is-integer' );
var MAX_LENGTH = require( '@stdlib/constants/uint32/max' );
// MAIN //
/**
* Tests whether a value is an `arguments` object.
*
* @private
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether a value is an `arguments` object
*
* @example
* function foo() {
* return arguments;
* }
*
* var bool = isArguments( foo() );
* // returns true
*
* @example
* var bool = isArguments( [] );
* // returns false
*/
function isArguments( value ) {
return (
value !== null &&
typeof value === 'object' &&
!isArray( value ) &&
typeof value.length === 'number' &&
isInteger( value.length ) &&
value.length >= 0 &&
value.length <= MAX_LENGTH &&
hasOwnProp( value, 'callee' ) &&
!isEnumerableProperty( value, 'callee' )
);
}
// EXPORTS //
module.exports = isArguments;
},{"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-array":79,"@stdlib/assert/is-enumerable-property":93,"@stdlib/constants/uint32/max":264,"@stdlib/math/base/assert/is-integer":270}],77:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is array-like.
*
* @module @stdlib/assert/is-array-like
*
* @example
* var isArrayLike = require( '@stdlib/assert/is-array-like' );
*
* var bool = isArrayLike( [] );
* // returns true
*
* bool = isArrayLike( { 'length': 10 } );
* // returns true
*
* bool = isArrayLike( 'beep' );
* // returns true
*/
// MODULES //
var isArrayLike = require( './main.js' );
// EXPORTS //
module.exports = isArrayLike;
},{"./main.js":78}],78:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isInteger = require( '@stdlib/math/base/assert/is-integer' );
var MAX_LENGTH = require( '@stdlib/constants/array/max-array-length' );
// MAIN //
/**
* Tests if a value is array-like.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is array-like
*
* @example
* var bool = isArrayLike( [] );
* // returns true
*
* @example
* var bool = isArrayLike( {'length':10} );
* // returns true
*/
function isArrayLike( value ) {
return (
value !== void 0 &&
value !== null &&
typeof value !== 'function' &&
typeof value.length === 'number' &&
isInteger( value.length ) &&
value.length >= 0 &&
value.length <= MAX_LENGTH
);
}
// EXPORTS //
module.exports = isArrayLike;
},{"@stdlib/constants/array/max-array-length":243,"@stdlib/math/base/assert/is-integer":270}],79:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is an array.
*
* @module @stdlib/assert/is-array
*
* @example
* var isArray = require( '@stdlib/assert/is-array' );
*
* var bool = isArray( [] );
* // returns true
*
* bool = isArray( {} );
* // returns false
*/
// MODULES //
var isArray = require( './main.js' );
// EXPORTS //
module.exports = isArray;
},{"./main.js":80}],80:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var nativeClass = require( '@stdlib/utils/native-class' );
// VARIABLES //
var f;
// FUNCTIONS //
/**
* Tests if a value is an array.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is an array
*
* @example
* var bool = isArray( [] );
* // returns true
*
* @example
* var bool = isArray( {} );
* // returns false
*/
function isArray( value ) {
return ( nativeClass( value ) === '[object Array]' );
}
// MAIN //
if ( Array.isArray ) {
f = Array.isArray;
} else {
f = isArray;
}
// EXPORTS //
module.exports = f;
},{"@stdlib/utils/native-class":481}],81:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is a boolean.
*
* @module @stdlib/assert/is-boolean
*
* @example
* var isBoolean = require( '@stdlib/assert/is-boolean' );
*
* var bool = isBoolean( false );
* // returns true
*
* bool = isBoolean( new Boolean( false ) );
* // returns true
*
* @example
* // Use interface to check for boolean primitives...
* var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive;
*
* var bool = isBoolean( false );
* // returns true
*
* bool = isBoolean( new Boolean( true ) );
* // returns false
*
* @example
* // Use interface to check for boolean objects...
* var isBoolean = require( '@stdlib/assert/is-boolean' ).isObject;
*
* var bool = isBoolean( true );
* // returns false
*
* bool = isBoolean( new Boolean( false ) );
* // returns true
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var isBoolean = require( './main.js' );
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );
// MAIN //
setReadOnly( isBoolean, 'isPrimitive', isPrimitive );
setReadOnly( isBoolean, 'isObject', isObject );
// EXPORTS //
module.exports = isBoolean;
},{"./main.js":82,"./object.js":83,"./primitive.js":84,"@stdlib/utils/define-nonenumerable-read-only-property":428}],82:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );
// MAIN //
/**
* Tests if a value is a boolean.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is a boolean
*
* @example
* var bool = isBoolean( false );
* // returns true
*
* @example
* var bool = isBoolean( true );
* // returns true
*
* @example
* var bool = isBoolean( new Boolean( false ) );
* // returns true
*
* @example
* var bool = isBoolean( new Boolean( true ) );
* // returns true
*/
function isBoolean( value ) {
return ( isPrimitive( value ) || isObject( value ) );
}
// EXPORTS //
module.exports = isBoolean;
},{"./object.js":83,"./primitive.js":84}],83:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var hasToStringTag = require( '@stdlib/assert/has-tostringtag-support' );
var nativeClass = require( '@stdlib/utils/native-class' );
var test = require( './try2serialize.js' );
// VARIABLES //
var FLG = hasToStringTag();
// MAIN //
/**
* Tests if a value is a boolean object.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a boolean object
*
* @example
* var bool = isBoolean( true );
* // returns false
*
* @example
* var bool = isBoolean( new Boolean( false ) );
* // returns true
*/
function isBoolean( value ) {
if ( typeof value === 'object' ) {
if ( value instanceof Boolean ) {
return true;
}
if ( FLG ) {
return test( value );
}
return ( nativeClass( value ) === '[object Boolean]' );
}
return false;
}
// EXPORTS //
module.exports = isBoolean;
},{"./try2serialize.js":86,"@stdlib/assert/has-tostringtag-support":57,"@stdlib/utils/native-class":481}],84:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Tests if a value is a boolean primitive.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a boolean primitive
*
* @example
* var bool = isBoolean( true );
* // returns true
*
* @example
* var bool = isBoolean( false );
* // returns true
*
* @example
* var bool = isBoolean( new Boolean( true ) );
* // returns false
*/
function isBoolean( value ) {
return ( typeof value === 'boolean' );
}
// EXPORTS //
module.exports = isBoolean;
},{}],85:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// eslint-disable-next-line stdlib/no-redeclare
var toString = Boolean.prototype.toString; // non-generic
// EXPORTS //
module.exports = toString;
},{}],86:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var toString = require( './tostring.js' ); // eslint-disable-line stdlib/no-redeclare
// MAIN //
/**
* Attempts to serialize a value to a string.
*
* @private
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value can be serialized
*/
function test( value ) {
try {
toString.call( value );
return true;
} catch ( err ) { // eslint-disable-line no-unused-vars
return false;
}
}
// EXPORTS //
module.exports = test;
},{"./tostring.js":85}],87:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// EXPORTS //
module.exports = true;
},{}],88:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is a Buffer instance.
*
* @module @stdlib/assert/is-buffer
*
* @example
* var isBuffer = require( '@stdlib/assert/is-buffer' );
*
* var v = isBuffer( new Buffer( 'beep' ) );
* // returns true
*
* v = isBuffer( {} );
* // returns false
*/
// MODULES //
var isBuffer = require( './main.js' );
// EXPORTS //
module.exports = isBuffer;
},{"./main.js":89}],89:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isObjectLike = require( '@stdlib/assert/is-object-like' );
// MAIN //
/**
* Tests if a value is a Buffer instance.
*
* @param {*} value - value to validate
* @returns {boolean} boolean indicating if a value is a Buffer instance
*
* @example
* var v = isBuffer( new Buffer( 'beep' ) );
* // returns true
*
* @example
* var v = isBuffer( new Buffer( [1,2,3,4] ) );
* // returns true
*
* @example
* var v = isBuffer( {} );
* // returns false
*
* @example
* var v = isBuffer( [] );
* // returns false
*/
function isBuffer( value ) {
return (
isObjectLike( value ) &&
(
// eslint-disable-next-line no-underscore-dangle
value._isBuffer || // for envs missing Object.prototype.constructor (e.g., Safari 5-7)
(
value.constructor &&
// WARNING: `typeof` is not a foolproof check, as certain envs consider RegExp and NodeList instances to be functions
typeof value.constructor.isBuffer === 'function' &&
value.constructor.isBuffer( value )
)
)
);
}
// EXPORTS //
module.exports = isBuffer;
},{"@stdlib/assert/is-object-like":143}],90:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is a collection.
*
* @module @stdlib/assert/is-collection
*
* @example
* var isCollection = require( '@stdlib/assert/is-collection' );
*
* var bool = isCollection( [] );
* // returns true
*
* bool = isCollection( {} );
* // returns false
*/
// MODULES //
var isCollection = require( './main.js' );
// EXPORTS //
module.exports = isCollection;
},{"./main.js":91}],91:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isInteger = require( '@stdlib/math/base/assert/is-integer' );
var MAX_LENGTH = require( '@stdlib/constants/array/max-typed-array-length' );
// MAIN //
/**
* Tests if a value is a collection.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether a value is a collection
*
* @example
* var bool = isCollection( [] );
* // returns true
*
* @example
* var bool = isCollection( {} );
* // returns false
*/
function isCollection( value ) {
return (
typeof value === 'object' &&
value !== null &&
typeof value.length === 'number' &&
isInteger( value.length ) &&
value.length >= 0 &&
value.length <= MAX_LENGTH
);
}
// EXPORTS //
module.exports = isCollection;
},{"@stdlib/constants/array/max-typed-array-length":244,"@stdlib/math/base/assert/is-integer":270}],92:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isEnum = require( './native.js' );
// VARIABLES //
var bool;
// FUNCTIONS //
/**
* Detects whether an environment has a bug where String indices are not detected as "enumerable" properties. Observed in Node v0.10.
*
* @private
* @returns {boolean} boolean indicating whether an environment has the bug
*/
function detect() {
return !isEnum.call( 'beep', '0' );
}
// MAIN //
bool = detect();
// EXPORTS //
module.exports = bool;
},{"./native.js":95}],93:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test whether an object's own property is enumerable.
*
* @module @stdlib/assert/is-enumerable-property
*
* @example
* var isEnumerableProperty = require( '@stdlib/assert/is-enumerable-property' );
*
* var beep = {
* 'boop': true
* };
*
* var bool = isEnumerableProperty( beep, 'boop' );
* // returns true
*
* bool = isEnumerableProperty( beep, 'hasOwnProperty' );
* // returns false
*/
// MODULES //
var isEnumerableProperty = require( './main.js' );
// EXPORTS //
module.exports = isEnumerableProperty;
},{"./main.js":94}],94:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isString = require( '@stdlib/assert/is-string' );
var isnan = require( '@stdlib/assert/is-nan' ).isPrimitive;
var isInteger = require( '@stdlib/assert/is-integer' ).isPrimitive;
var isEnum = require( './native.js' );
var hasStringEnumBug = require( './has_string_enumerability_bug.js' );
// MAIN //
/**
* Tests if an object's own property is enumerable.
*
* @param {*} value - value to test
* @param {*} property - property to test
* @returns {boolean} boolean indicating if an object property is enumerable
*
* @example
* var beep = {
* 'boop': true
* };
*
* var bool = isEnumerableProperty( beep, 'boop' );
* // returns true
*
* @example
* var beep = {
* 'boop': true
* };
*
* var bool = isEnumerableProperty( beep, 'hasOwnProperty' );
* // returns false
*/
function isEnumerableProperty( value, property ) {
var bool;
if (
value === void 0 ||
value === null
) {
return false;
}
bool = isEnum.call( value, property );
if ( !bool && hasStringEnumBug && isString( value ) ) {
// Note: we only check for indices, as properties attached to a `String` object are properly detected as enumerable above.
property = +property;
return (
!isnan( property ) &&
isInteger( property ) &&
property >= 0 &&
property < value.length
);
}
return bool;
}
// EXPORTS //
module.exports = isEnumerableProperty;
},{"./has_string_enumerability_bug.js":92,"./native.js":95,"@stdlib/assert/is-integer":110,"@stdlib/assert/is-nan":118,"@stdlib/assert/is-string":162}],95:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Tests if an object's own property is enumerable.
*
* @private
* @name isEnumerableProperty
* @type {Function}
* @param {*} value - value to test
* @param {*} property - property to test
* @returns {boolean} boolean indicating if an object property is enumerable
*
* @example
* var beep = {
* 'boop': true
* };
*
* var bool = isEnumerableProperty( beep, 'boop' );
* // returns true
*
* @example
* var beep = {
* 'boop': true
* };
*
* var bool = isEnumerableProperty( beep, 'hasOwnProperty' );
* // returns false
*/
var isEnumerableProperty = Object.prototype.propertyIsEnumerable;
// EXPORTS //
module.exports = isEnumerableProperty;
},{}],96:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is an `Error` object.
*
* @module @stdlib/assert/is-error
*
* @example
* var isError = require( '@stdlib/assert/is-error' );
*
* var bool = isError( new Error( 'beep' ) );
* // returns true
*
* bool = isError( {} );
* // returns false
*/
// MODULES //
var isError = require( './main.js' );
// EXPORTS //
module.exports = isError;
},{"./main.js":97}],97:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var getPrototypeOf = require( '@stdlib/utils/get-prototype-of' );
var nativeClass = require( '@stdlib/utils/native-class' );
// MAIN //
/**
* Tests if a value is an `Error` object.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether a value is an `Error` object
*
* @example
* var bool = isError( new Error( 'beep' ) );
* // returns true
*
* @example
* var bool = isError( {} );
* // returns false
*/
function isError( value ) {
if ( typeof value !== 'object' || value === null ) {
return false;
}
// Check for `Error` objects from the same realm (same Node.js `vm` or same `Window` object)...
if ( value instanceof Error ) {
return true;
}
// Walk the prototype tree until we find an object having the desired native class...
while ( value ) {
if ( nativeClass( value ) === '[object Error]' ) {
return true;
}
value = getPrototypeOf( value );
}
return false;
}
// EXPORTS //
module.exports = isError;
},{"@stdlib/utils/get-prototype-of":447,"@stdlib/utils/native-class":481}],98:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is a Float32Array.
*
* @module @stdlib/assert/is-float32array
*
* @example
* var isFloat32Array = require( '@stdlib/assert/is-float32array' );
*
* var bool = isFloat32Array( new Float32Array( 10 ) );
* // returns true
*
* bool = isFloat32Array( [] );
* // returns false
*/
// MODULES //
var isFloat32Array = require( './main.js' );
// EXPORTS //
module.exports = isFloat32Array;
},{"./main.js":99}],99:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var nativeClass = require( '@stdlib/utils/native-class' );
// VARIABLES //
var hasFloat32Array = ( typeof Float32Array === 'function' );// eslint-disable-line stdlib/require-globals
// MAIN //
/**
* Tests if a value is a Float32Array.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is a Float32Array
*
* @example
* var bool = isFloat32Array( new Float32Array( 10 ) );
* // returns true
*
* @example
* var bool = isFloat32Array( [] );
* // returns false
*/
function isFloat32Array( value ) {
return (
( hasFloat32Array && value instanceof Float32Array ) || // eslint-disable-line stdlib/require-globals
nativeClass( value ) === '[object Float32Array]'
);
}
// EXPORTS //
module.exports = isFloat32Array;
},{"@stdlib/utils/native-class":481}],100:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is a Float64Array.
*
* @module @stdlib/assert/is-float64array
*
* @example
* var isFloat64Array = require( '@stdlib/assert/is-float64array' );
*
* var bool = isFloat64Array( new Float64Array( 10 ) );
* // returns true
*
* bool = isFloat64Array( [] );
* // returns false
*/
// MODULES //
var isFloat64Array = require( './main.js' );
// EXPORTS //
module.exports = isFloat64Array;
},{"./main.js":101}],101:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var nativeClass = require( '@stdlib/utils/native-class' );
// VARIABLES //
var hasFloat64Array = ( typeof Float64Array === 'function' ); // eslint-disable-line stdlib/require-globals
// MAIN //
/**
* Tests if a value is a Float64Array.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is a Float64Array
*
* @example
* var bool = isFloat64Array( new Float64Array( 10 ) );
* // returns true
*
* @example
* var bool = isFloat64Array( [] );
* // returns false
*/
function isFloat64Array( value ) {
return (
( hasFloat64Array && value instanceof Float64Array ) || // eslint-disable-line stdlib/require-globals
nativeClass( value ) === '[object Float64Array]'
);
}
// EXPORTS //
module.exports = isFloat64Array;
},{"@stdlib/utils/native-class":481}],102:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is a function.
*
* @module @stdlib/assert/is-function
*
* @example
* var isFunction = require( '@stdlib/assert/is-function' );
*
* function beep() {
* return 'beep';
* }
*
* var bool = isFunction( beep );
* // returns true
*/
// MODULES //
var isFunction = require( './main.js' );
// EXPORTS //
module.exports = isFunction;
},{"./main.js":103}],103:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var typeOf = require( '@stdlib/utils/type-of' );
// MAIN //
/**
* Tests if a value is a function.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is a function
*
* @example
* function beep() {
* return 'beep';
* }
*
* var bool = isFunction( beep );
* // returns true
*/
function isFunction( value ) {
// Note: cannot use `typeof` directly, as various browser engines incorrectly return `'function'` when operating on non-function objects, such as regular expressions and NodeLists.
return ( typeOf( value ) === 'function' );
}
// EXPORTS //
module.exports = isFunction;
},{"@stdlib/utils/type-of":508}],104:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is an Int16Array.
*
* @module @stdlib/assert/is-int16array
*
* @example
* var isInt16Array = require( '@stdlib/assert/is-int16array' );
*
* var bool = isInt16Array( new Int16Array( 10 ) );
* // returns true
*
* bool = isInt16Array( [] );
* // returns false
*/
// MODULES //
var isInt16Array = require( './main.js' );
// EXPORTS //
module.exports = isInt16Array;
},{"./main.js":105}],105:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var nativeClass = require( '@stdlib/utils/native-class' );
// VARIABLES //
var hasInt16Array = ( typeof Int16Array === 'function' ); // eslint-disable-line stdlib/require-globals
// MAIN //
/**
* Tests if a value is an Int16Array.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is an Int16Array
*
* @example
* var bool = isInt16Array( new Int16Array( 10 ) );
* // returns true
*
* @example
* var bool = isInt16Array( [] );
* // returns false
*/
function isInt16Array( value ) {
return (
( hasInt16Array && value instanceof Int16Array ) || // eslint-disable-line stdlib/require-globals
nativeClass( value ) === '[object Int16Array]'
);
}
// EXPORTS //
module.exports = isInt16Array;
},{"@stdlib/utils/native-class":481}],106:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is an Int32Array.
*
* @module @stdlib/assert/is-int32array
*
* @example
* var isInt32Array = require( '@stdlib/assert/is-int32array' );
*
* var bool = isInt32Array( new Int32Array( 10 ) );
* // returns true
*
* bool = isInt32Array( [] );
* // returns false
*/
// MODULES //
var isInt32Array = require( './main.js' );
// EXPORTS //
module.exports = isInt32Array;
},{"./main.js":107}],107:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var nativeClass = require( '@stdlib/utils/native-class' );
// VARIABLES //
var hasInt32Array = ( typeof Int32Array === 'function' ); // eslint-disable-line stdlib/require-globals
// MAIN //
/**
* Tests if a value is an Int32Array.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is an Int32Array
*
* @example
* var bool = isInt32Array( new Int32Array( 10 ) );
* // returns true
*
* @example
* var bool = isInt32Array( [] );
* // returns false
*/
function isInt32Array( value ) {
return (
( hasInt32Array && value instanceof Int32Array ) || // eslint-disable-line stdlib/require-globals
nativeClass( value ) === '[object Int32Array]'
);
}
// EXPORTS //
module.exports = isInt32Array;
},{"@stdlib/utils/native-class":481}],108:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is an Int8Array.
*
* @module @stdlib/assert/is-int8array
*
* @example
* var isInt8Array = require( '@stdlib/assert/is-int8array' );
*
* var bool = isInt8Array( new Int8Array( 10 ) );
* // returns true
*
* bool = isInt8Array( [] );
* // returns false
*/
// MODULES //
var isInt8Array = require( './main.js' );
// EXPORTS //
module.exports = isInt8Array;
},{"./main.js":109}],109:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var nativeClass = require( '@stdlib/utils/native-class' );
// VARIABLES //
var hasInt8Array = ( typeof Int8Array === 'function' ); // eslint-disable-line stdlib/require-globals
// MAIN //
/**
* Tests if a value is an Int8Array.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is an Int8Array
*
* @example
* var bool = isInt8Array( new Int8Array( 10 ) );
* // returns true
*
* @example
* var bool = isInt8Array( [] );
* // returns false
*/
function isInt8Array( value ) {
return (
( hasInt8Array && value instanceof Int8Array ) || // eslint-disable-line stdlib/require-globals
nativeClass( value ) === '[object Int8Array]'
);
}
// EXPORTS //
module.exports = isInt8Array;
},{"@stdlib/utils/native-class":481}],110:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is an integer.
*
* @module @stdlib/assert/is-integer
*
* @example
* var isInteger = require( '@stdlib/assert/is-integer' );
*
* var bool = isInteger( 5.0 );
* // returns true
*
* bool = isInteger( new Number( 5.0 ) );
* // returns true
*
* bool = isInteger( -3.14 );
* // returns false
*
* bool = isInteger( null );
* // returns false
*
* @example
* // Use interface to check for integer primitives...
* var isInteger = require( '@stdlib/assert/is-integer' ).isPrimitive;
*
* var bool = isInteger( -3.0 );
* // returns true
*
* bool = isInteger( new Number( -3.0 ) );
* // returns false
*
* @example
* // Use interface to check for integer objects...
* var isInteger = require( '@stdlib/assert/is-integer' ).isObject;
*
* var bool = isInteger( 3.0 );
* // returns false
*
* bool = isInteger( new Number( 3.0 ) );
* // returns true
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var isInteger = require( './main.js' );
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );
// MAIN //
setReadOnly( isInteger, 'isPrimitive', isPrimitive );
setReadOnly( isInteger, 'isObject', isObject );
// EXPORTS //
module.exports = isInteger;
},{"./main.js":112,"./object.js":113,"./primitive.js":114,"@stdlib/utils/define-nonenumerable-read-only-property":428}],111:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var PINF = require( '@stdlib/constants/float64/pinf' );
var NINF = require( '@stdlib/constants/float64/ninf' );
var isInt = require( '@stdlib/math/base/assert/is-integer' );
// MAIN //
/**
* Tests if a number primitive is an integer value.
*
* @private
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a number primitive is an integer value
*/
function isInteger( value ) {
return (
value < PINF &&
value > NINF &&
isInt( value )
);
}
// EXPORTS //
module.exports = isInteger;
},{"@stdlib/constants/float64/ninf":253,"@stdlib/constants/float64/pinf":255,"@stdlib/math/base/assert/is-integer":270}],112:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );
// MAIN //
/**
* Tests if a value is an integer.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is an integer
*
* @example
* var bool = isInteger( 5.0 );
* // returns true
*
* @example
* var bool = isInteger( new Number( 5.0 ) );
* // returns true
*
* @example
* var bool = isInteger( -3.14 );
* // returns false
*
* @example
* var bool = isInteger( null );
* // returns false
*/
function isInteger( value ) {
return ( isPrimitive( value ) || isObject( value ) );
}
// EXPORTS //
module.exports = isInteger;
},{"./object.js":113,"./primitive.js":114}],113:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isNumber = require( '@stdlib/assert/is-number' ).isObject;
var isInt = require( './integer.js' );
// MAIN //
/**
* Tests if a value is a number object having an integer value.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a number object having an integer value
*
* @example
* var bool = isInteger( 3.0 );
* // returns false
*
* @example
* var bool = isInteger( new Number( 3.0 ) );
* // returns true
*/
function isInteger( value ) {
return (
isNumber( value ) &&
isInt( value.valueOf() )
);
}
// EXPORTS //
module.exports = isInteger;
},{"./integer.js":111,"@stdlib/assert/is-number":137}],114:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isNumber = require( '@stdlib/assert/is-number' ).isPrimitive;
var isInt = require( './integer.js' );
// MAIN //
/**
* Tests if a value is a number primitive having an integer value.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a number primitive having an integer value
*
* @example
* var bool = isInteger( -3.0 );
* // returns true
*
* @example
* var bool = isInteger( new Number( -3.0 ) );
* // returns false
*/
function isInteger( value ) {
return (
isNumber( value ) &&
isInt( value )
);
}
// EXPORTS //
module.exports = isInteger;
},{"./integer.js":111,"@stdlib/assert/is-number":137}],115:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var Uint8Array = require( '@stdlib/array/uint8' );
var Uint16Array = require( '@stdlib/array/uint16' );
// MAIN //
var ctors = {
'uint16': Uint16Array,
'uint8': Uint8Array
};
// EXPORTS //
module.exports = ctors;
},{"@stdlib/array/uint16":20,"@stdlib/array/uint8":26}],116:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Return a boolean indicating if an environment is little endian.
*
* @module @stdlib/assert/is-little-endian
*
* @example
* var IS_LITTLE_ENDIAN = require( '@stdlib/assert/is-little-endian' );
*
* var bool = IS_LITTLE_ENDIAN;
* // returns <boolean>
*/
// MODULES //
var IS_LITTLE_ENDIAN = require( './main.js' );
// EXPORTS //
module.exports = IS_LITTLE_ENDIAN;
},{"./main.js":117}],117:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var ctors = require( './ctors.js' );
// VARIABLES //
var bool;
// FUNCTIONS //
/**
* Returns a boolean indicating if an environment is little endian.
*
* @private
* @returns {boolean} boolean indicating if an environment is little endian
*
* @example
* var bool = isLittleEndian();
* // returns <boolean>
*/
function isLittleEndian() {
var uint16view;
var uint8view;
uint16view = new ctors[ 'uint16' ]( 1 );
/*
* Set the uint16 view to a value having distinguishable lower and higher order words.
*
* 4660 => 0x1234 => 0x12 0x34 => '00010010 00110100' => (0x12,0x34) == (18,52)
*/
uint16view[ 0 ] = 0x1234;
// Create a uint8 view on top of the uint16 buffer:
uint8view = new ctors[ 'uint8' ]( uint16view.buffer );
// If little endian, the least significant byte will be first...
return ( uint8view[ 0 ] === 0x34 );
}
// MAIN //
bool = isLittleEndian();
// EXPORTS //
module.exports = bool;
},{"./ctors.js":115}],118:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is `NaN`.
*
* @module @stdlib/assert/is-nan
*
* @example
* var isnan = require( '@stdlib/assert/is-nan' );
*
* var bool = isnan( NaN );
* // returns true
*
* bool = isnan( new Number( NaN ) );
* // returns true
*
* bool = isnan( 3.14 );
* // returns false
*
* bool = isnan( null );
* // returns false
*
* @example
* var isnan = require( '@stdlib/assert/is-nan' ).isPrimitive;
*
* var bool = isnan( NaN );
* // returns true
*
* bool = isnan( 3.14 );
* // returns false
*
* bool = isnan( new Number( NaN ) );
* // returns false
*
* @example
* var isnan = require( '@stdlib/assert/is-nan' ).isObject;
*
* var bool = isnan( NaN );
* // returns false
*
* bool = isnan( new Number( NaN ) );
* // returns true
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var isnan = require( './main.js' );
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );
// MAIN //
setReadOnly( isnan, 'isPrimitive', isPrimitive );
setReadOnly( isnan, 'isObject', isObject );
// EXPORTS //
module.exports = isnan;
},{"./main.js":119,"./object.js":120,"./primitive.js":121,"@stdlib/utils/define-nonenumerable-read-only-property":428}],119:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );
// MAIN //
/**
* Tests if a value is `NaN`.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is `NaN`
*
* @example
* var bool = isnan( NaN );
* // returns true
*
* @example
* var bool = isnan( new Number( NaN ) );
* // returns true
*
* @example
* var bool = isnan( 3.14 );
* // returns false
*
* @example
* var bool = isnan( null );
* // returns false
*/
function isnan( value ) {
return ( isPrimitive( value ) || isObject( value ) );
}
// EXPORTS //
module.exports = isnan;
},{"./object.js":120,"./primitive.js":121}],120:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isNumber = require( '@stdlib/assert/is-number' ).isObject;
var isNan = require( '@stdlib/math/base/assert/is-nan' );
// MAIN //
/**
* Tests if a value is a number object having a value of `NaN`.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a number object having a value of `NaN`
*
* @example
* var bool = isnan( NaN );
* // returns false
*
* @example
* var bool = isnan( new Number( NaN ) );
* // returns true
*/
function isnan( value ) {
return (
isNumber( value ) &&
isNan( value.valueOf() )
);
}
// EXPORTS //
module.exports = isnan;
},{"@stdlib/assert/is-number":137,"@stdlib/math/base/assert/is-nan":272}],121:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isNumber = require( '@stdlib/assert/is-number' ).isPrimitive;
var isNan = require( '@stdlib/math/base/assert/is-nan' );
// MAIN //
/**
* Tests if a value is a `NaN` number primitive.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a `NaN` number primitive
*
* @example
* var bool = isnan( NaN );
* // returns true
*
* @example
* var bool = isnan( 3.14 );
* // returns false
*
* @example
* var bool = isnan( new Number( NaN ) );
* // returns false
*/
function isnan( value ) {
return (
isNumber( value ) &&
isNan( value )
);
}
// EXPORTS //
module.exports = isnan;
},{"@stdlib/assert/is-number":137,"@stdlib/math/base/assert/is-nan":272}],122:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is Node stream-like.
*
* @module @stdlib/assert/is-node-stream-like
*
* @example
* var transformStream = require( '@stdlib/streams/node/transform' );
* var isNodeStreamLike = require( '@stdlib/assert/is-node-stream-like' );
*
* var stream = transformStream();
*
* var bool = isNodeStreamLike( stream );
* // returns true
*
* bool = isNodeStreamLike( {} );
* // returns false
*/
// MODULES //
var isNodeStreamLike = require( './main.js' );
// EXPORTS //
module.exports = isNodeStreamLike;
},{"./main.js":123}],123:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Tests if a value is Node stream-like.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is Node stream-like
*
* @example
* var transformStream = require( '@stdlib/streams/node/transform' );
*
* var stream = transformStream();
*
* var bool = isNodeStreamLike( stream );
* // returns true
*
* bool = isNodeStreamLike( {} );
* // returns false
*/
function isNodeStreamLike( value ) {
return (
// Must be an object:
value !== null &&
typeof value === 'object' &&
// Should be an event emitter:
typeof value.on === 'function' &&
typeof value.once === 'function' &&
typeof value.emit === 'function' &&
typeof value.addListener === 'function' &&
typeof value.removeListener === 'function' &&
typeof value.removeAllListeners === 'function' &&
// Should have a `pipe` method (Node streams inherit from `Stream`, including writable streams):
typeof value.pipe === 'function'
);
}
// EXPORTS //
module.exports = isNodeStreamLike;
},{}],124:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is Node writable stream-like.
*
* @module @stdlib/assert/is-node-writable-stream-like
*
* @example
* var transformStream = require( '@stdlib/streams/node/transform' );
* var isNodeWritableStreamLike = require( '@stdlib/assert/is-node-writable-stream-like' );
*
* var stream = transformStream();
*
* var bool = isNodeWritableStreamLike( stream );
* // returns true
*
* bool = isNodeWritableStreamLike( {} );
* // returns false
*/
// MODULES //
var isNodeWritableStreamLike = require( './main.js' );
// EXPORTS //
module.exports = isNodeWritableStreamLike;
},{"./main.js":125}],125:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
/* eslint-disable no-underscore-dangle */
'use strict';
// MODULES //
var isNodeStreamLike = require( '@stdlib/assert/is-node-stream-like' );
// MAIN //
/**
* Tests if a value is Node writable stream-like.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is Node writable stream-like
*
* @example
* var transformStream = require( '@stdlib/streams/node/transform' );
*
* var stream = transformStream();
*
* var bool = isNodeWritableStreamLike( stream );
* // returns true
*
* bool = isNodeWritableStreamLike( {} );
* // returns false
*/
function isNodeWritableStreamLike( value ) {
return (
// Must be stream-like:
isNodeStreamLike( value ) &&
// Should have writable stream methods:
typeof value._write === 'function' &&
// Should have writable stream state:
typeof value._writableState === 'object'
);
}
// EXPORTS //
module.exports = isNodeWritableStreamLike;
},{"@stdlib/assert/is-node-stream-like":122}],126:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is an array-like object containing only nonnegative integers.
*
* @module @stdlib/assert/is-nonnegative-integer-array
*
* @example
* var isNonNegativeIntegerArray = require( '@stdlib/assert/is-nonnegative-integer-array' );
*
* var bool = isNonNegativeIntegerArray( [ 3.0, new Number(3.0) ] );
* // returns true
*
* bool = isNonNegativeIntegerArray( [ 3.0, '3.0' ] );
* // returns false
*
* @example
* var isNonNegativeIntegerArray = require( '@stdlib/assert/is-nonnegative-integer-array' ).primitives;
*
* var bool = isNonNegativeIntegerArray( [ 1.0, 0.0, 10.0 ] );
* // returns true
*
* bool = isNonNegativeIntegerArray( [ 3.0, new Number(1.0) ] );
* // returns false
*
* @example
* var isNonNegativeIntegerArray = require( '@stdlib/assert/is-nonnegative-integer-array' ).objects;
*
* var bool = isNonNegativeIntegerArray( [ new Number(3.0), new Number(1.0) ] );
* // returns true
*
* bool = isNonNegativeIntegerArray( [ 1.0, 0.0, 10.0 ] );
* // returns false
*/
// MODULES //
var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' );
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var arrayfun = require( '@stdlib/assert/tools/array-like-function' );
// MAIN //
var isNonNegativeIntegerArray = arrayfun( isNonNegativeInteger );
setReadOnly( isNonNegativeIntegerArray, 'primitives', arrayfun( isNonNegativeInteger.isPrimitive ) );
setReadOnly( isNonNegativeIntegerArray, 'objects', arrayfun( isNonNegativeInteger.isObject ) );
// EXPORTS //
module.exports = isNonNegativeIntegerArray;
},{"@stdlib/assert/is-nonnegative-integer":127,"@stdlib/assert/tools/array-like-function":183,"@stdlib/utils/define-nonenumerable-read-only-property":428}],127:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is a nonnegative integer.
*
* @module @stdlib/assert/is-nonnegative-integer
*
* @example
* var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' );
*
* var bool = isNonNegativeInteger( 5.0 );
* // returns true
*
* bool = isNonNegativeInteger( new Number( 5.0 ) );
* // returns true
*
* bool = isNonNegativeInteger( -5.0 );
* // returns false
*
* bool = isNonNegativeInteger( 3.14 );
* // returns false
*
* bool = isNonNegativeInteger( null );
* // returns false
*
* @example
* var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ).isPrimitive;
*
* var bool = isNonNegativeInteger( 3.0 );
* // returns true
*
* bool = isNonNegativeInteger( new Number( 3.0 ) );
* // returns false
*
* @example
* var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ).isObject;
*
* var bool = isNonNegativeInteger( 3.0 );
* // returns false
*
* bool = isNonNegativeInteger( new Number( 3.0 ) );
* // returns true
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var isNonNegativeInteger = require( './main.js' );
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );
// MAIN //
setReadOnly( isNonNegativeInteger, 'isPrimitive', isPrimitive );
setReadOnly( isNonNegativeInteger, 'isObject', isObject );
// EXPORTS //
module.exports = isNonNegativeInteger;
},{"./main.js":128,"./object.js":129,"./primitive.js":130,"@stdlib/utils/define-nonenumerable-read-only-property":428}],128:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );
// MAIN //
/**
* Tests if a value is a nonnegative integer.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is a nonnegative integer
*
* @example
* var bool = isNonNegativeInteger( 5.0 );
* // returns true
*
* @example
* var bool = isNonNegativeInteger( new Number( 5.0 ) );
* // returns true
*
* @example
* var bool = isNonNegativeInteger( -5.0 );
* // returns false
*
* @example
* var bool = isNonNegativeInteger( 3.14 );
* // returns false
*
* @example
* var bool = isNonNegativeInteger( null );
* // returns false
*/
function isNonNegativeInteger( value ) {
return ( isPrimitive( value ) || isObject( value ) );
}
// EXPORTS //
module.exports = isNonNegativeInteger;
},{"./object.js":129,"./primitive.js":130}],129:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isInteger = require( '@stdlib/assert/is-integer' ).isObject;
// MAIN //
/**
* Tests if a value is a number object having a nonnegative integer value.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a number object having a nonnegative integer value
*
* @example
* var bool = isNonNegativeInteger( 3.0 );
* // returns false
*
* @example
* var bool = isNonNegativeInteger( new Number( 3.0 ) );
* // returns true
*/
function isNonNegativeInteger( value ) {
return (
isInteger( value ) &&
value.valueOf() >= 0
);
}
// EXPORTS //
module.exports = isNonNegativeInteger;
},{"@stdlib/assert/is-integer":110}],130:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isInteger = require( '@stdlib/assert/is-integer' ).isPrimitive;
// MAIN //
/**
* Tests if a value is a number primitive having a nonnegative integer value.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a number primitive having a nonnegative integer value
*
* @example
* var bool = isNonNegativeInteger( 3.0 );
* // returns true
*
* @example
* var bool = isNonNegativeInteger( new Number( 3.0 ) );
* // returns false
*/
function isNonNegativeInteger( value ) {
return (
isInteger( value ) &&
value >= 0
);
}
// EXPORTS //
module.exports = isNonNegativeInteger;
},{"@stdlib/assert/is-integer":110}],131:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is a nonnegative number.
*
* @module @stdlib/assert/is-nonnegative-number
*
* @example
* var isNonNegativeNumber = require( '@stdlib/assert/is-nonnegative-number' );
*
* var bool = isNonNegativeNumber( 5.0 );
* // returns true
*
* bool = isNonNegativeNumber( new Number( 5.0 ) );
* // returns true
*
* bool = isNonNegativeNumber( 3.14 );
* // returns true
*
* bool = isNonNegativeNumber( -5.0 );
* // returns false
*
* bool = isNonNegativeNumber( null );
* // returns false
*
* @example
* var isNonNegativeNumber = require( '@stdlib/assert/is-nonnegative-number' ).isPrimitive;
*
* var bool = isNonNegativeNumber( 3.0 );
* // returns true
*
* bool = isNonNegativeNumber( new Number( 3.0 ) );
* // returns false
*
* @example
* var isNonNegativeNumber = require( '@stdlib/assert/is-nonnegative-number' ).isObject;
*
* var bool = isNonNegativeNumber( 3.0 );
* // returns false
*
* bool = isNonNegativeNumber( new Number( 3.0 ) );
* // returns true
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var isNonNegativeNumber = require( './main.js' );
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );
// MAIN //
setReadOnly( isNonNegativeNumber, 'isPrimitive', isPrimitive );
setReadOnly( isNonNegativeNumber, 'isObject', isObject );
// EXPORTS //
module.exports = isNonNegativeNumber;
},{"./main.js":132,"./object.js":133,"./primitive.js":134,"@stdlib/utils/define-nonenumerable-read-only-property":428}],132:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );
// MAIN //
/**
* Tests if a value is a nonnegative number.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is a nonnegative number
*
* @example
* var bool = isNonNegativeNumber( 5.0 );
* // returns true
*
* @example
* var bool = isNonNegativeNumber( new Number( 5.0 ) );
* // returns true
*
* @example
* var bool = isNonNegativeNumber( 3.14 );
* // returns true
*
* @example
* var bool = isNonNegativeNumber( -5.0 );
* // returns false
*
* @example
* var bool = isNonNegativeNumber( null );
* // returns false
*/
function isNonNegativeNumber( value ) {
return ( isPrimitive( value ) || isObject( value ) );
}
// EXPORTS //
module.exports = isNonNegativeNumber;
},{"./object.js":133,"./primitive.js":134}],133:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isNumber = require( '@stdlib/assert/is-number' ).isObject;
// MAIN //
/**
* Tests if a value is a number object having a nonnegative value.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a number object having a nonnegative number value
*
* @example
* var bool = isNonNegativeNumber( 3.0 );
* // returns false
*
* @example
* var bool = isNonNegativeNumber( new Number( 3.0 ) );
* // returns true
*/
function isNonNegativeNumber( value ) {
return (
isNumber( value ) &&
value.valueOf() >= 0.0
);
}
// EXPORTS //
module.exports = isNonNegativeNumber;
},{"@stdlib/assert/is-number":137}],134:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isNumber = require( '@stdlib/assert/is-number' ).isPrimitive;
// MAIN //
/**
* Tests if a value is a number primitive having a nonnegative value.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a number primitive having a nonnegative number value
*
* @example
* var bool = isNonNegativeNumber( 3.0 );
* // returns true
*
* @example
* var bool = isNonNegativeNumber( new Number( 3.0 ) );
* // returns false
*/
function isNonNegativeNumber( value ) {
return (
isNumber( value ) &&
value >= 0.0
);
}
// EXPORTS //
module.exports = isNonNegativeNumber;
},{"@stdlib/assert/is-number":137}],135:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is `null`.
*
* @module @stdlib/assert/is-null
*
* @example
* var isNull = require( '@stdlib/assert/is-null' );
*
* var value = null;
*
* var bool = isNull( value );
* // returns true
*/
// MODULES //
var isNull = require( './main.js' );
// EXPORTS //
module.exports = isNull;
},{"./main.js":136}],136:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Tests if a value is `null`.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is null
*
* @example
* var bool = isNull( null );
* // returns true
*
* bool = isNull( true );
* // returns false
*/
function isNull( value ) {
return value === null;
}
// EXPORTS //
module.exports = isNull;
},{}],137:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is a number.
*
* @module @stdlib/assert/is-number
*
* @example
* var isNumber = require( '@stdlib/assert/is-number' );
*
* var bool = isNumber( 3.14 );
* // returns true
*
* bool = isNumber( new Number( 3.14 ) );
* // returns true
*
* bool = isNumber( NaN );
* // returns true
*
* bool = isNumber( null );
* // returns false
*
* @example
* var isNumber = require( '@stdlib/assert/is-number' ).isPrimitive;
*
* var bool = isNumber( 3.14 );
* // returns true
*
* bool = isNumber( NaN );
* // returns true
*
* bool = isNumber( new Number( 3.14 ) );
* // returns false
*
* @example
* var isNumber = require( '@stdlib/assert/is-number' ).isObject;
*
* var bool = isNumber( 3.14 );
* // returns false
*
* bool = isNumber( new Number( 3.14 ) );
* // returns true
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var isNumber = require( './main.js' );
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );
// MAIN //
setReadOnly( isNumber, 'isPrimitive', isPrimitive );
setReadOnly( isNumber, 'isObject', isObject );
// EXPORTS //
module.exports = isNumber;
},{"./main.js":138,"./object.js":139,"./primitive.js":140,"@stdlib/utils/define-nonenumerable-read-only-property":428}],138:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );
// MAIN //
/**
* Tests if a value is a number.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is a number
*
* @example
* var bool = isNumber( 3.14 );
* // returns true
*
* @example
* var bool = isNumber( new Number( 3.14 ) );
* // returns true
*
* @example
* var bool = isNumber( NaN );
* // returns true
*
* @example
* var bool = isNumber( null );
* // returns false
*/
function isNumber( value ) {
return ( isPrimitive( value ) || isObject( value ) );
}
// EXPORTS //
module.exports = isNumber;
},{"./object.js":139,"./primitive.js":140}],139:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var hasToStringTag = require( '@stdlib/assert/has-tostringtag-support' );
var nativeClass = require( '@stdlib/utils/native-class' );
var Number = require( '@stdlib/number/ctor' );
var test = require( './try2serialize.js' );
// VARIABLES //
var FLG = hasToStringTag();
// MAIN //
/**
* Tests if a value is a number object.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a number object
*
* @example
* var bool = isNumber( 3.14 );
* // returns false
*
* @example
* var bool = isNumber( new Number( 3.14 ) );
* // returns true
*/
function isNumber( value ) {
if ( typeof value === 'object' ) {
if ( value instanceof Number ) {
return true;
}
if ( FLG ) {
return test( value );
}
return ( nativeClass( value ) === '[object Number]' );
}
return false;
}
// EXPORTS //
module.exports = isNumber;
},{"./try2serialize.js":142,"@stdlib/assert/has-tostringtag-support":57,"@stdlib/number/ctor":341,"@stdlib/utils/native-class":481}],140:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Tests if a value is a number primitive.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a number primitive
*
* @example
* var bool = isNumber( 3.14 );
* // returns true
*
* @example
* var bool = isNumber( NaN );
* // returns true
*
* @example
* var bool = isNumber( new Number( 3.14 ) );
* // returns false
*/
function isNumber( value ) {
return ( typeof value === 'number' );
}
// EXPORTS //
module.exports = isNumber;
},{}],141:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var Number = require( '@stdlib/number/ctor' );
// MAIN //
// eslint-disable-next-line stdlib/no-redeclare
var toString = Number.prototype.toString; // non-generic
// EXPORTS //
module.exports = toString;
},{"@stdlib/number/ctor":341}],142:[function(require,module,exports){
arguments[4][86][0].apply(exports,arguments)
},{"./tostring.js":141,"dup":86}],143:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is object-like.
*
* @module @stdlib/assert/is-object-like
*
* @example
* var isObjectLike = require( '@stdlib/assert/is-object-like' );
*
* var bool = isObjectLike( {} );
* // returns true
*
* bool = isObjectLike( [] );
* // returns true
*
* bool = isObjectLike( null );
* // returns false
*
* @example
* var isObjectLike = require( '@stdlib/assert/is-object-like' ).isObjectLikeArray;
*
* var bool = isObjectLike( [ {}, [] ] );
* // returns true
*
* bool = isObjectLike( [ {}, '3.0' ] );
* // returns false
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var arrayfun = require( '@stdlib/assert/tools/array-function' );
var isObjectLike = require( './main.js' );
// MAIN //
setReadOnly( isObjectLike, 'isObjectLikeArray', arrayfun( isObjectLike ) );
// EXPORTS //
module.exports = isObjectLike;
},{"./main.js":144,"@stdlib/assert/tools/array-function":181,"@stdlib/utils/define-nonenumerable-read-only-property":428}],144:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Tests if a value is object-like.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether a value is object-like
*
* @example
* var bool = isObjectLike( {} );
* // returns true
*
* @example
* var bool = isObjectLike( [] );
* // returns true
*
* @example
* var bool = isObjectLike( null );
* // returns false
*/
function isObjectLike( value ) {
return (
value !== null &&
typeof value === 'object'
);
}
// EXPORTS //
module.exports = isObjectLike;
},{}],145:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is an object.
*
* @module @stdlib/assert/is-object
*
* @example
* var isObject = require( '@stdlib/assert/is-object' );
*
* var bool = isObject( {} );
* // returns true
*
* bool = isObject( true );
* // returns false
*/
// MODULES //
var isObject = require( './main.js' );
// EXPORTS //
module.exports = isObject;
},{"./main.js":146}],146:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isArray = require( '@stdlib/assert/is-array' );
// MAIN //
/**
* Tests if a value is an object; e.g., `{}`.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is an object
*
* @example
* var bool = isObject( {} );
* // returns true
*
* @example
* var bool = isObject( null );
* // returns false
*/
function isObject( value ) {
return (
typeof value === 'object' &&
value !== null &&
!isArray( value )
);
}
// EXPORTS //
module.exports = isObject;
},{"@stdlib/assert/is-array":79}],147:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is a plain object.
*
* @module @stdlib/assert/is-plain-object
*
* @example
* var isPlainObject = require( '@stdlib/assert/is-plain-object' );
*
* var bool = isPlainObject( {} );
* // returns true
*
* bool = isPlainObject( null );
* // returns false
*/
// MODULES //
var isPlainObject = require( './main.js' );
// EXPORTS //
module.exports = isPlainObject;
},{"./main.js":148}],148:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isObject = require( '@stdlib/assert/is-object' );
var isFunction = require( '@stdlib/assert/is-function' );
var getPrototypeOf = require( '@stdlib/utils/get-prototype-of' );
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var nativeClass = require( '@stdlib/utils/native-class' );
// VARIABLES //
var objectPrototype = Object.prototype;
// FUNCTIONS //
/**
* Tests that an object only has own properties.
*
* @private
* @param {Object} obj - value to test
* @returns {boolean} boolean indicating if an object only has own properties
*/
function ownProps( obj ) {
var key;
// NOTE: possibility of perf boost if key enumeration order is known (see http://stackoverflow.com/questions/18531624/isplainobject-thing).
for ( key in obj ) {
if ( !hasOwnProp( obj, key ) ) {
return false;
}
}
return true;
}
// MAIN //
/**
* Tests if a value is a plain object.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is a plain object
*
* @example
* var bool = isPlainObject( {} );
* // returns true
*
* @example
* var bool = isPlainObject( null );
* // returns false
*/
function isPlainObject( value ) {
var proto;
// Screen for obvious non-objects...
if ( !isObject( value ) ) {
return false;
}
// Objects with no prototype (e.g., `Object.create( null )`) are plain...
proto = getPrototypeOf( value );
if ( !proto ) {
return true;
}
// Objects having a prototype are plain if and only if they are constructed with a global `Object` function and the prototype points to the prototype of a plain object...
return (
// Cannot have own `constructor` property:
!hasOwnProp( value, 'constructor' ) &&
// Prototype `constructor` property must be a function (see also https://bugs.jquery.com/ticket/9897 and http://stackoverflow.com/questions/18531624/isplainobject-thing):
hasOwnProp( proto, 'constructor' ) &&
isFunction( proto.constructor ) &&
nativeClass( proto.constructor ) === '[object Function]' &&
// Test for object-specific method:
hasOwnProp( proto, 'isPrototypeOf' ) &&
isFunction( proto.isPrototypeOf ) &&
(
// Test if the prototype matches the global `Object` prototype (same realm):
proto === objectPrototype ||
// Test that all properties are own properties (cross-realm; *most* likely a plain object):
ownProps( value )
)
);
}
// EXPORTS //
module.exports = isPlainObject;
},{"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-function":102,"@stdlib/assert/is-object":145,"@stdlib/utils/get-prototype-of":447,"@stdlib/utils/native-class":481}],149:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is a positive integer.
*
* @module @stdlib/assert/is-positive-integer
*
* @example
* var isPositiveInteger = require( '@stdlib/assert/is-positive-integer' );
*
* var bool = isPositiveInteger( 5.0 );
* // returns true
*
* bool = isPositiveInteger( new Number( 5.0 ) );
* // returns true
*
* bool = isPositiveInteger( -5.0 );
* // returns false
*
* bool = isPositiveInteger( 3.14 );
* // returns false
*
* bool = isPositiveInteger( null );
* // returns false
*
* @example
* var isPositiveInteger = require( '@stdlib/assert/is-positive-integer' ).isPrimitive;
*
* var bool = isPositiveInteger( 3.0 );
* // returns true
*
* bool = isPositiveInteger( new Number( 3.0 ) );
* // returns false
*
* @example
* var isPositiveInteger = require( '@stdlib/assert/is-positive-integer' ).isObject;
*
* var bool = isPositiveInteger( 3.0 );
* // returns false
*
* bool = isPositiveInteger( new Number( 3.0 ) );
* // returns true
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var isPositiveInteger = require( './main.js' );
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );
// MAIN //
setReadOnly( isPositiveInteger, 'isPrimitive', isPrimitive );
setReadOnly( isPositiveInteger, 'isObject', isObject );
// EXPORTS //
module.exports = isPositiveInteger;
},{"./main.js":150,"./object.js":151,"./primitive.js":152,"@stdlib/utils/define-nonenumerable-read-only-property":428}],150:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );
// MAIN //
/**
* Tests if a value is a positive integer.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is a positive integer
*
* @example
* var bool = isPositiveInteger( 5.0 );
* // returns true
*
* @example
* var bool = isPositiveInteger( new Number( 5.0 ) );
* // returns true
*
* @example
* var bool = isPositiveInteger( 0.0 );
* // returns false
*
* @example
* var bool = isPositiveInteger( -5.0 );
* // returns false
*
* @example
* var bool = isPositiveInteger( 3.14 );
* // returns false
*
* @example
* var bool = isPositiveInteger( null );
* // returns false
*/
function isPositiveInteger( value ) {
return ( isPrimitive( value ) || isObject( value ) );
}
// EXPORTS //
module.exports = isPositiveInteger;
},{"./object.js":151,"./primitive.js":152}],151:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isInteger = require( '@stdlib/assert/is-integer' ).isObject;
// MAIN //
/**
* Tests if a value is a number object having a positive integer value.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a number object having a positive integer value
*
* @example
* var bool = isPositiveInteger( 3.0 );
* // returns false
*
* @example
* var bool = isPositiveInteger( new Number( 3.0 ) );
* // returns true
*/
function isPositiveInteger( value ) {
return (
isInteger( value ) &&
value.valueOf() > 0.0
);
}
// EXPORTS //
module.exports = isPositiveInteger;
},{"@stdlib/assert/is-integer":110}],152:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isInteger = require( '@stdlib/assert/is-integer' ).isPrimitive;
// MAIN //
/**
* Tests if a value is a number primitive having a positive integer value.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a number primitive having a positive integer value
*
* @example
* var bool = isPositiveInteger( 3.0 );
* // returns true
*
* @example
* var bool = isPositiveInteger( new Number( 3.0 ) );
* // returns false
*/
function isPositiveInteger( value ) {
return (
isInteger( value ) &&
value > 0.0
);
}
// EXPORTS //
module.exports = isPositiveInteger;
},{"@stdlib/assert/is-integer":110}],153:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is a positive number.
*
* @module @stdlib/assert/is-positive-number
*
* @example
* var isPositiveNumber = require( '@stdlib/assert/is-positive-number' );
*
* var bool = isPositiveNumber( 5.0 );
* // returns true
*
* bool = isPositiveNumber( new Number( 5.0 ) );
* // returns true
*
* bool = isPositiveNumber( 3.14 );
* // returns true
*
* bool = isPositiveNumber( -5.0 );
* // returns false
*
* bool = isPositiveNumber( null );
* // returns false
*
* @example
* var isPositiveNumber = require( '@stdlib/assert/is-positive-number' ).isPrimitive;
*
* var bool = isPositiveNumber( 3.0 );
* // returns true
*
* bool = isPositiveNumber( new Number( 3.0 ) );
* // returns false
*
* @example
* var isPositiveNumber = require( '@stdlib/assert/is-positive-number' ).isObject;
*
* var bool = isPositiveNumber( 3.0 );
* // returns false
*
* bool = isPositiveNumber( new Number( 3.0 ) );
* // returns true
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var isPositiveNumber = require( './main.js' );
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );
// MAIN //
setReadOnly( isPositiveNumber, 'isPrimitive', isPrimitive );
setReadOnly( isPositiveNumber, 'isObject', isObject );
// EXPORTS //
module.exports = isPositiveNumber;
},{"./main.js":154,"./object.js":155,"./primitive.js":156,"@stdlib/utils/define-nonenumerable-read-only-property":428}],154:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );
// MAIN //
/**
* Tests if a value is a positive number.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is a positive number
*
* @example
* var bool = isPositiveNumber( 5.0 );
* // returns true
*
* @example
* var bool = isPositiveNumber( new Number( 5.0 ) );
* // returns true
*
* @example
* var bool = isPositiveNumber( 3.14 );
* // returns true
*
* @example
* var bool = isPositiveNumber( -5.0 );
* // returns false
*
* @example
* var bool = isPositiveNumber( null );
* // returns false
*/
function isPositiveNumber( value ) {
return ( isPrimitive( value ) || isObject( value ) );
}
// EXPORTS //
module.exports = isPositiveNumber;
},{"./object.js":155,"./primitive.js":156}],155:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isNumber = require( '@stdlib/assert/is-number' ).isObject;
// MAIN //
/**
* Tests if a value is a number object having a positive value.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a number object having a positive value
*
* @example
* var bool = isPositiveNumber( 3.0 );
* // returns false
*
* @example
* var bool = isPositiveNumber( new Number( 3.0 ) );
* // returns true
*/
function isPositiveNumber( value ) {
return (
isNumber( value ) &&
value.valueOf() > 0.0
);
}
// EXPORTS //
module.exports = isPositiveNumber;
},{"@stdlib/assert/is-number":137}],156:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isNumber = require( '@stdlib/assert/is-number' ).isPrimitive;
// MAIN //
/**
* Tests if a value is a number primitive having a positive value.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a number primitive having a positive value
*
* @example
* var bool = isPositiveNumber( 3.0 );
* // returns true
*
* @example
* var bool = isPositiveNumber( new Number( 3.0 ) );
* // returns false
*/
function isPositiveNumber( value ) {
return (
isNumber( value ) &&
value > 0.0
);
}
// EXPORTS //
module.exports = isPositiveNumber;
},{"@stdlib/assert/is-number":137}],157:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
var exec = RegExp.prototype.exec; // non-generic
// EXPORTS //
module.exports = exec;
},{}],158:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is a regular expression.
*
* @module @stdlib/assert/is-regexp
*
* @example
* var isRegExp = require( '@stdlib/assert/is-regexp' );
*
* var bool = isRegExp( /\.+/ );
* // returns true
*
* bool = isRegExp( {} );
* // returns false
*/
// MODULES //
var isRegExp = require( './main.js' );
// EXPORTS //
module.exports = isRegExp;
},{"./main.js":159}],159:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var hasToStringTag = require( '@stdlib/assert/has-tostringtag-support' );
var nativeClass = require( '@stdlib/utils/native-class' );
var test = require( './try2exec.js' );
// VARIABLES //
var FLG = hasToStringTag();
// MAIN //
/**
* Tests if a value is a regular expression.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is a regular expression
*
* @example
* var bool = isRegExp( /\.+/ );
* // returns true
*
* @example
* var bool = isRegExp( {} );
* // returns false
*/
function isRegExp( value ) {
if ( typeof value === 'object' ) {
if ( value instanceof RegExp ) {
return true;
}
if ( FLG ) {
return test( value );
}
return ( nativeClass( value ) === '[object RegExp]' );
}
return false;
}
// EXPORTS //
module.exports = isRegExp;
},{"./try2exec.js":160,"@stdlib/assert/has-tostringtag-support":57,"@stdlib/utils/native-class":481}],160:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var exec = require( './exec.js' );
// MAIN //
/**
* Attempts to call a `RegExp` method.
*
* @private
* @param {*} value - value to test
* @returns {boolean} boolean indicating if able to call a `RegExp` method
*/
function test( value ) {
try {
exec.call( value );
return true;
} catch ( err ) { // eslint-disable-line no-unused-vars
return false;
}
}
// EXPORTS //
module.exports = test;
},{"./exec.js":157}],161:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is an array of strings.
*
* @module @stdlib/assert/is-string-array
*
* @example
* var isStringArray = require( '@stdlib/assert/is-string-array' );
*
* var bool = isStringArray( [ 'abc', 'def' ] );
* // returns true
*
* bool = isStringArray( [ 'abc', 123 ] );
* // returns false
*
* @example
* var isStringArray = require( '@stdlib/assert/is-string-array' ).primitives;
*
* var bool = isStringArray( [ 'abc', 'def' ] );
* // returns true
*
* bool = isStringArray( [ 'abc', new String( 'def' ) ] );
* // returns false
*
* @example
* var isStringArray = require( '@stdlib/assert/is-string-array' ).objects;
*
* var bool = isStringArray( [ new String( 'abc' ), new String( 'def' ) ] );
* // returns true
*
* bool = isStringArray( [ new String( 'abc' ), 'def' ] );
* // returns false
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var arrayfun = require( '@stdlib/assert/tools/array-function' );
var isString = require( '@stdlib/assert/is-string' );
// MAIN //
var isStringArray = arrayfun( isString );
setReadOnly( isStringArray, 'primitives', arrayfun( isString.isPrimitive ) );
setReadOnly( isStringArray, 'objects', arrayfun( isString.isObject ) );
// EXPORTS //
module.exports = isStringArray;
},{"@stdlib/assert/is-string":162,"@stdlib/assert/tools/array-function":181,"@stdlib/utils/define-nonenumerable-read-only-property":428}],162:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is a string.
*
* @module @stdlib/assert/is-string
*
* @example
* var isString = require( '@stdlib/assert/is-string' );
*
* var bool = isString( 'beep' );
* // returns true
*
* bool = isString( new String( 'beep' ) );
* // returns true
*
* bool = isString( 5 );
* // returns false
*
* @example
* var isString = require( '@stdlib/assert/is-string' ).isObject;
*
* var bool = isString( new String( 'beep' ) );
* // returns true
*
* bool = isString( 'beep' );
* // returns false
*
* @example
* var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
*
* var bool = isString( 'beep' );
* // returns true
*
* bool = isString( new String( 'beep' ) );
* // returns false
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var isString = require( './main.js' );
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );
// MAIN //
setReadOnly( isString, 'isPrimitive', isPrimitive );
setReadOnly( isString, 'isObject', isObject );
// EXPORTS //
module.exports = isString;
},{"./main.js":163,"./object.js":164,"./primitive.js":165,"@stdlib/utils/define-nonenumerable-read-only-property":428}],163:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );
// MAIN //
/**
* Tests if a value is a string.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is a string
*
* @example
* var bool = isString( new String( 'beep' ) );
* // returns true
*
* @example
* var bool = isString( 'beep' );
* // returns true
*/
function isString( value ) {
return ( isPrimitive( value ) || isObject( value ) );
}
// EXPORTS //
module.exports = isString;
},{"./object.js":164,"./primitive.js":165}],164:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var hasToStringTag = require( '@stdlib/assert/has-tostringtag-support' );
var nativeClass = require( '@stdlib/utils/native-class' );
var test = require( './try2valueof.js' );
// VARIABLES //
var FLG = hasToStringTag();
// MAIN //
/**
* Tests if a value is a string object.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a string object
*
* @example
* var bool = isString( new String( 'beep' ) );
* // returns true
*
* @example
* var bool = isString( 'beep' );
* // returns false
*/
function isString( value ) {
if ( typeof value === 'object' ) {
if ( value instanceof String ) {
return true;
}
if ( FLG ) {
return test( value );
}
return ( nativeClass( value ) === '[object String]' );
}
return false;
}
// EXPORTS //
module.exports = isString;
},{"./try2valueof.js":166,"@stdlib/assert/has-tostringtag-support":57,"@stdlib/utils/native-class":481}],165:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Tests if a value is a string primitive.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a string primitive
*
* @example
* var bool = isString( 'beep' );
* // returns true
*
* @example
* var bool = isString( new String( 'beep' ) );
* // returns false
*/
function isString( value ) {
return ( typeof value === 'string' );
}
// EXPORTS //
module.exports = isString;
},{}],166:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var valueOf = require( './valueof.js' ); // eslint-disable-line stdlib/no-redeclare
// MAIN //
/**
* Attempts to extract a string value.
*
* @private
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a string can be extracted
*/
function test( value ) {
try {
valueOf.call( value );
return true;
} catch ( err ) { // eslint-disable-line no-unused-vars
return false;
}
}
// EXPORTS //
module.exports = test;
},{"./valueof.js":167}],167:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// eslint-disable-next-line stdlib/no-redeclare
var valueOf = String.prototype.valueOf; // non-generic
// EXPORTS //
module.exports = valueOf;
},{}],168:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var Int8Array = require( '@stdlib/array/int8' );
var Uint8Array = require( '@stdlib/array/uint8' );
var Uint8ClampedArray = require( '@stdlib/array/uint8c' );
var Int16Array = require( '@stdlib/array/int16' );
var Uint16Array = require( '@stdlib/array/uint16' );
var Int32Array = require( '@stdlib/array/int32' );
var Uint32Array = require( '@stdlib/array/uint32' );
var Float32Array = require( '@stdlib/array/float32' );
var Float64Array = require( '@stdlib/array/float64' );
// MAIN //
var CTORS = [
Float64Array,
Float32Array,
Int32Array,
Uint32Array,
Int16Array,
Uint16Array,
Int8Array,
Uint8Array,
Uint8ClampedArray
];
// EXPORTS //
module.exports = CTORS;
},{"@stdlib/array/float32":2,"@stdlib/array/float64":5,"@stdlib/array/int16":7,"@stdlib/array/int32":10,"@stdlib/array/int8":13,"@stdlib/array/uint16":20,"@stdlib/array/uint32":23,"@stdlib/array/uint8":26,"@stdlib/array/uint8c":29}],169:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is a typed array.
*
* @module @stdlib/assert/is-typed-array
*
* @example
* var Int8Array = require( '@stdlib/array/int8' );
* var isTypedArray = require( '@stdlib/assert/is-typed-array' );
*
* var bool = isTypedArray( new Int8Array( 10 ) );
* // returns true
*/
// MODULES //
var isTypedArray = require( './main.js' );
// EXPORTS //
module.exports = isTypedArray;
},{"./main.js":170}],170:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var ctorName = require( '@stdlib/utils/constructor-name' );
var fcnName = require( '@stdlib/utils/function-name' );
var getPrototypeOf = require( '@stdlib/utils/get-prototype-of' );
var hasFloat64ArraySupport = require( '@stdlib/assert/has-float64array-support' );
var Float64Array = require( '@stdlib/array/float64' );
var CTORS = require( './ctors.js' );
var NAMES = require( './names.json' );
// VARIABLES //
// Abstract `TypedArray` class:
var TypedArray = ( hasFloat64ArraySupport() ) ? getPrototypeOf( Float64Array ) : Dummy; // eslint-disable-line max-len
// Ensure abstract typed array class has expected name:
TypedArray = ( fcnName( TypedArray ) === 'TypedArray' ) ? TypedArray : Dummy;
// FUNCTIONS //
/**
* Dummy constructor.
*
* @private
*/
function Dummy() {} // eslint-disable-line no-empty-function
// MAIN //
/**
* Tests if a value is a typed array.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a typed array
*
* @example
* var Int8Array = require( '@stdlib/array/int8' );
*
* var bool = isTypedArray( new Int8Array( 10 ) );
* // returns true
*/
function isTypedArray( value ) {
var v;
var i;
if ( typeof value !== 'object' || value === null ) {
return false;
}
// Check for the abstract class...
if ( value instanceof TypedArray ) {
return true;
}
// Check for typed array objects from the same realm (same Node.js `vm` or same `Window` object)...
for ( i = 0; i < CTORS.length; i++ ) {
if ( value instanceof CTORS[ i ] ) {
return true;
}
}
// Walk the prototype tree until we find an object having a desired class...
while ( value ) {
v = ctorName( value );
for ( i = 0; i < NAMES.length; i++ ) {
if ( NAMES[ i ] === v ) {
return true;
}
}
value = getPrototypeOf( value );
}
return false;
}
// EXPORTS //
module.exports = isTypedArray;
},{"./ctors.js":168,"./names.json":171,"@stdlib/array/float64":5,"@stdlib/assert/has-float64array-support":36,"@stdlib/utils/constructor-name":418,"@stdlib/utils/function-name":444,"@stdlib/utils/get-prototype-of":447}],171:[function(require,module,exports){
module.exports=[
"Int8Array",
"Uint8Array",
"Uint8ClampedArray",
"Int16Array",
"Uint16Array",
"Int32Array",
"Uint32Array",
"Float32Array",
"Float64Array"
]
},{}],172:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is a Uint16Array.
*
* @module @stdlib/assert/is-uint16array
*
* @example
* var isUint16Array = require( '@stdlib/assert/is-uint16array' );
*
* var bool = isUint16Array( new Uint16Array( 10 ) );
* // returns true
*
* bool = isUint16Array( [] );
* // returns false
*/
// MODULES //
var isUint16Array = require( './main.js' );
// EXPORTS //
module.exports = isUint16Array;
},{"./main.js":173}],173:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var nativeClass = require( '@stdlib/utils/native-class' );
// VARIABLES //
var hasUint16Array = ( typeof Uint16Array === 'function' ); // eslint-disable-line stdlib/require-globals
// MAIN //
/**
* Tests if a value is a Uint16Array.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is a Uint16Array
*
* @example
* var bool = isUint16Array( new Uint16Array( 10 ) );
* // returns true
*
* @example
* var bool = isUint16Array( [] );
* // returns false
*/
function isUint16Array( value ) {
return (
( hasUint16Array && value instanceof Uint16Array ) || // eslint-disable-line stdlib/require-globals
nativeClass( value ) === '[object Uint16Array]'
);
}
// EXPORTS //
module.exports = isUint16Array;
},{"@stdlib/utils/native-class":481}],174:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is a Uint32Array.
*
* @module @stdlib/assert/is-uint32array
*
* @example
* var isUint32Array = require( '@stdlib/assert/is-uint32array' );
*
* var bool = isUint32Array( new Uint32Array( 10 ) );
* // returns true
*
* bool = isUint32Array( [] );
* // returns false
*/
// MODULES //
var isUint32Array = require( './main.js' );
// EXPORTS //
module.exports = isUint32Array;
},{"./main.js":175}],175:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var nativeClass = require( '@stdlib/utils/native-class' );
// VARIABLES //
var hasUint32Array = ( typeof Uint32Array === 'function' ); // eslint-disable-line stdlib/require-globals
// MAIN //
/**
* Tests if a value is a Uint32Array.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is a Uint32Array
*
* @example
* var bool = isUint32Array( new Uint32Array( 10 ) );
* // returns true
*
* @example
* var bool = isUint32Array( [] );
* // returns false
*/
function isUint32Array( value ) {
return (
( hasUint32Array && value instanceof Uint32Array ) || // eslint-disable-line stdlib/require-globals
nativeClass( value ) === '[object Uint32Array]'
);
}
// EXPORTS //
module.exports = isUint32Array;
},{"@stdlib/utils/native-class":481}],176:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is a Uint8Array.
*
* @module @stdlib/assert/is-uint8array
*
* @example
* var isUint8Array = require( '@stdlib/assert/is-uint8array' );
*
* var bool = isUint8Array( new Uint8Array( 10 ) );
* // returns true
*
* bool = isUint8Array( [] );
* // returns false
*/
// MODULES //
var isUint8Array = require( './main.js' );
// EXPORTS //
module.exports = isUint8Array;
},{"./main.js":177}],177:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var nativeClass = require( '@stdlib/utils/native-class' );
// VARIABLES //
var hasUint8Array = ( typeof Uint8Array === 'function' ); // eslint-disable-line stdlib/require-globals
// MAIN //
/**
* Tests if a value is a Uint8Array.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is a Uint8Array
*
* @example
* var bool = isUint8Array( new Uint8Array( 10 ) );
* // returns true
*
* @example
* var bool = isUint8Array( [] );
* // returns false
*/
function isUint8Array( value ) {
return (
( hasUint8Array && value instanceof Uint8Array ) || // eslint-disable-line stdlib/require-globals
nativeClass( value ) === '[object Uint8Array]'
);
}
// EXPORTS //
module.exports = isUint8Array;
},{"@stdlib/utils/native-class":481}],178:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a value is a Uint8ClampedArray.
*
* @module @stdlib/assert/is-uint8clampedarray
*
* @example
* var isUint8ClampedArray = require( '@stdlib/assert/is-uint8clampedarray' );
*
* var bool = isUint8ClampedArray( new Uint8ClampedArray( 10 ) );
* // returns true
*
* bool = isUint8ClampedArray( [] );
* // returns false
*/
// MODULES //
var isUint8ClampedArray = require( './main.js' );
// EXPORTS //
module.exports = isUint8ClampedArray;
},{"./main.js":179}],179:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var nativeClass = require( '@stdlib/utils/native-class' );
// VARIABLES //
var hasUint8ClampedArray = ( typeof Uint8ClampedArray === 'function' ); // eslint-disable-line stdlib/require-globals
// MAIN //
/**
* Tests if a value is a Uint8ClampedArray.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether value is a Uint8ClampedArray
*
* @example
* var bool = isUint8ClampedArray( new Uint8ClampedArray( 10 ) );
* // returns true
*
* @example
* var bool = isUint8ClampedArray( [] );
* // returns false
*/
function isUint8ClampedArray( value ) {
return (
( hasUint8ClampedArray && value instanceof Uint8ClampedArray ) || // eslint-disable-line stdlib/require-globals
nativeClass( value ) === '[object Uint8ClampedArray]'
);
}
// EXPORTS //
module.exports = isUint8ClampedArray;
},{"@stdlib/utils/native-class":481}],180:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isArray = require( '@stdlib/assert/is-array' );
// MAIN //
/**
* Returns a function which tests if every element in an array passes a test condition.
*
* @param {Function} predicate - function to apply
* @throws {TypeError} must provide a function
* @returns {Function} an array function
*
* @example
* var isOdd = require( '@stdlib/assert/is-odd' );
*
* var arr1 = [ 1, 3, 5, 7 ];
* var arr2 = [ 3, 5, 8 ];
*
* var validate = arrayfcn( isOdd );
*
* var bool = validate( arr1 );
* // returns true
*
* bool = validate( arr2 );
* // returns false
*/
function arrayfcn( predicate ) {
if ( typeof predicate !== 'function' ) {
throw new TypeError( 'invalid argument. Must provide a function. Value: `' + predicate + '`.' );
}
return every;
/**
* Tests if every element in an array passes a test condition.
*
* @private
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether a value is an array for which all elements pass a test condition
*/
function every( value ) {
var len;
var i;
if ( !isArray( value ) ) {
return false;
}
len = value.length;
if ( len === 0 ) {
return false;
}
for ( i = 0; i < len; i++ ) {
if ( predicate( value[ i ] ) === false ) {
return false;
}
}
return true;
}
}
// EXPORTS //
module.exports = arrayfcn;
},{"@stdlib/assert/is-array":79}],181:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Return a function which tests if every element in an array passes a test condition.
*
* @module @stdlib/assert/tools/array-function
*
* @example
* var isOdd = require( '@stdlib/assert/is-odd' );
* var arrayfcn = require( '@stdlib/assert/tools/array-function' );
*
* var arr1 = [ 1, 3, 5, 7 ];
* var arr2 = [ 3, 5, 8 ];
*
* var validate = arrayfcn( isOdd );
*
* var bool = validate( arr1 );
* // returns true
*
* bool = validate( arr2 );
* // returns false
*/
// MODULES //
var arrayfcn = require( './arrayfcn.js' );
// EXPORTS //
module.exports = arrayfcn;
},{"./arrayfcn.js":180}],182:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isArrayLike = require( '@stdlib/assert/is-array-like' );
// MAIN //
/**
* Returns a function which tests if every element in an array-like object passes a test condition.
*
* @param {Function} predicate - function to apply
* @throws {TypeError} must provide a function
* @returns {Function} an array-like object function
*
* @example
* var isOdd = require( '@stdlib/assert/is-odd' );
*
* var arr1 = [ 1, 3, 5, 7 ];
* var arr2 = [ 3, 5, 8 ];
*
* var validate = arraylikefcn( isOdd );
*
* var bool = validate( arr1 );
* // returns true
*
* bool = validate( arr2 );
* // returns false
*/
function arraylikefcn( predicate ) {
if ( typeof predicate !== 'function' ) {
throw new TypeError( 'invalid argument. Must provide a function. Value: `' + predicate + '`.' );
}
return every;
/**
* Tests if every element in an array-like object passes a test condition.
*
* @private
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether a value is an array-like object for which all elements pass a test condition
*/
function every( value ) {
var len;
var i;
if ( !isArrayLike( value ) ) {
return false;
}
len = value.length;
if ( len === 0 ) {
return false;
}
for ( i = 0; i < len; i++ ) {
if ( predicate( value[ i ] ) === false ) {
return false;
}
}
return true;
}
}
// EXPORTS //
module.exports = arraylikefcn;
},{"@stdlib/assert/is-array-like":77}],183:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Return a function which tests if every element in an array-like object passes a test condition.
*
* @module @stdlib/assert/tools/array-like-function
*
* @example
* var isOdd = require( '@stdlib/assert/is-odd' );
* var arraylikefcn = require( '@stdlib/assert/tools/array-like-function' );
*
* var arr1 = [ 1, 3, 5, 7 ];
* var arr2 = [ 3, 5, 8 ];
*
* var validate = arraylikefcn( isOdd );
*
* var bool = validate( arr1 );
* // returns true
*
* bool = validate( arr2 );
* // returns false
*/
// MODULES //
var arraylikefcn = require( './arraylikefcn.js' );
// EXPORTS //
module.exports = arraylikefcn;
},{"./arraylikefcn.js":182}],184:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var TransformStream = require( '@stdlib/streams/node/transform' );
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var isFunction = require( '@stdlib/assert/is-function' );
var createHarness = require( './harness' );
var harness = require( './get_harness.js' );
// VARIABLES //
var listeners = [];
// FUNCTIONS //
/**
* Callback invoked when a harness finishes running all benchmarks.
*
* @private
*/
function done() {
var len;
var f;
var i;
len = listeners.length;
// Inform all the listeners that the harness has finished...
for ( i = 0; i < len; i++ ) {
f = listeners.shift();
f();
}
}
/**
* Creates a results stream.
*
* @private
* @param {Options} [options] - stream options
* @throws {Error} must provide valid stream options
* @returns {TransformStream} results stream
*/
function createStream( options ) {
var stream;
var bench;
var opts;
if ( arguments.length ) {
opts = options;
} else {
opts = {};
}
// If we have already created a harness, calling this function simply creates another results stream...
if ( harness.cached ) {
bench = harness();
return bench.createStream( opts );
}
stream = new TransformStream( opts );
opts.stream = stream;
// Create a harness which uses the created output stream:
harness( opts, done );
return stream;
}
/**
* Adds a listener for when a harness finishes running all benchmarks.
*
* @private
* @param {Callback} clbk - listener
* @throws {TypeError} must provide a function
* @throws {Error} must provide a listener only once
* @returns {void}
*/
function onFinish( clbk ) {
var i;
if ( !isFunction( clbk ) ) {
throw new TypeError( 'invalid argument. Must provide a function. Value: `'+clbk+'`.' );
}
// Allow adding a listener only once...
for ( i = 0; i < listeners.length; i++ ) {
if ( clbk === listeners[ i ] ) {
throw new Error( 'invalid argument. Attempted to add duplicate listener.' );
}
}
listeners.push( clbk );
}
// MAIN //
/**
* Runs a benchmark.
*
* @param {string} name - benchmark name
* @param {Options} [options] - benchmark options
* @param {boolean} [options.skip=false] - boolean indicating whether to skip a benchmark
* @param {(PositiveInteger|null)} [options.iterations=null] - number of iterations
* @param {PositiveInteger} [options.repeats=3] - number of repeats
* @param {PositiveInteger} [options.timeout=300000] - number of milliseconds before a benchmark automatically fails
* @param {Function} [benchmark] - function containing benchmark code
* @throws {TypeError} first argument must be a string
* @throws {TypeError} options argument must be an object
* @throws {TypeError} must provide valid options
* @throws {TypeError} benchmark argument must a function
* @returns {Benchmark} benchmark harness
*
* @example
* bench( 'beep', function benchmark( b ) {
* var x;
* var i;
* b.tic();
* for ( i = 0; i < b.iterations; i++ ) {
* x = Math.sin( Math.random() );
* if ( x !== x ) {
* b.ok( false, 'should not return NaN' );
* }
* }
* b.toc();
* if ( x !== x ) {
* b.ok( false, 'should not return NaN' );
* }
* b.end();
* });
*/
function bench( name, options, benchmark ) {
var h = harness( done );
if ( arguments.length < 2 ) {
h( name );
} else if ( arguments.length === 2 ) {
h( name, options );
} else {
h( name, options, benchmark );
}
return bench;
}
/**
* Creates a benchmark harness.
*
* @name createHarness
* @memberof bench
* @type {Function}
* @param {Options} [options] - harness options
* @param {Callback} [clbk] - callback to invoke when a harness finishes running all benchmarks
* @throws {TypeError} options argument must be an object
* @throws {TypeError} must provide valid options
* @throws {TypeError} callback argument must be a function
* @returns {Function} benchmark harness
*/
setReadOnly( bench, 'createHarness', createHarness );
/**
* Creates a results stream.
*
* @name createStream
* @memberof bench
* @type {Function}
* @param {Options} [options] - stream options
* @throws {Error} must provide valid stream options
* @returns {TransformStream} results stream
*/
setReadOnly( bench, 'createStream', createStream );
/**
* Adds a listener for when a harness finishes running all benchmarks.
*
* @name onFinish
* @memberof bench
* @type {Function}
* @param {Callback} clbk - listener
* @throws {TypeError} must provide a function
* @throws {Error} must provide a listener only once
* @returns {void}
*/
setReadOnly( bench, 'onFinish', onFinish );
// EXPORTS //
module.exports = bench;
},{"./get_harness.js":206,"./harness":207,"@stdlib/assert/is-function":102,"@stdlib/streams/node/transform":400,"@stdlib/utils/define-nonenumerable-read-only-property":428}],185:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
// MAIN //
/**
* Generates an assertion.
*
* @private
* @param {boolean} ok - assertion outcome
* @param {Options} opts - options
*/
function assert( ok, opts ) {
/* eslint-disable no-invalid-this, no-unused-vars */ // TODO: remove no-unused-vars once `err` is used
var result;
var err;
result = {
'id': this._count,
'ok': ok,
'skip': opts.skip,
'todo': opts.todo,
'name': opts.message || '(unnamed assert)',
'operator': opts.operator
};
if ( hasOwnProp( opts, 'actual' ) ) {
result.actual = opts.actual;
}
if ( hasOwnProp( opts, 'expected' ) ) {
result.expected = opts.expected;
}
if ( !ok ) {
result.error = opts.error || new Error( this.name );
err = new Error( 'exception' );
// TODO: generate an exception in order to locate the calling function (https://github.com/substack/tape/blob/master/lib/test.js#L215)
}
this._count += 1;
this.emit( 'result', result );
}
// EXPORTS //
module.exports = assert;
},{"@stdlib/assert/has-own-property":53}],186:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// EXPORTS //
module.exports = clearTimeout;
},{}],187:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var trim = require( '@stdlib/string/trim' );
var replace = require( '@stdlib/string/replace' );
var EOL = require( '@stdlib/regexp/eol' ).REGEXP;
// VARIABLES //
var RE_COMMENT = /^#\s*/;
// MAIN //
/**
* Writes a comment.
*
* @private
* @param {string} msg - comment message
*/
function comment( msg ) {
/* eslint-disable no-invalid-this */
var lines;
var i;
msg = trim( msg );
lines = msg.split( EOL );
for ( i = 0; i < lines.length; i++ ) {
msg = trim( lines[ i ] );
msg = replace( msg, RE_COMMENT, '' );
this.emit( 'result', msg );
}
}
// EXPORTS //
module.exports = comment;
},{"@stdlib/regexp/eol":384,"@stdlib/string/replace":406,"@stdlib/string/trim":408}],188:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Asserts that `actual` is deeply equal to `expected`.
*
* @private
* @param {*} actual - actual value
* @param {*} expected - expected value
* @param {string} [msg] message
*/
function deepEqual( actual, expected, msg ) {
/* eslint-disable no-invalid-this */
this.comment( 'actual: '+actual+'. expected: '+expected+'. msg: '+msg+'.' );
// TODO: implement
}
// EXPORTS //
module.exports = deepEqual;
},{}],189:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var nextTick = require( './../utils/next_tick.js' );
// MAIN //
/**
* Ends a benchmark.
*
* @private
*/
function end() {
/* eslint-disable no-invalid-this */
var self = this;
if ( this._ended ) {
this.fail( '.end() called more than once' );
} else {
// Prevents releasing the zalgo when running synchronous benchmarks.
nextTick( onTick );
}
this._ended = true;
this._running = false;
/**
* Callback invoked upon a subsequent tick of the event loop.
*
* @private
*/
function onTick() {
self.emit( 'end' );
}
}
// EXPORTS //
module.exports = end;
},{"./../utils/next_tick.js":226}],190:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Returns a `boolean` indicating if a benchmark has ended.
*
* @private
* @returns {boolean} boolean indicating if a benchmark has ended
*/
function ended() {
/* eslint-disable no-invalid-this */
return this._ended;
}
// EXPORTS //
module.exports = ended;
},{}],191:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Asserts that `actual` is strictly equal to `expected`.
*
* @private
* @param {*} actual - actual value
* @param {*} expected - expected value
* @param {string} [msg] - message
*/
function equal( actual, expected, msg ) {
/* eslint-disable no-invalid-this */
this._assert( actual === expected, {
'message': msg || 'should be equal',
'operator': 'equal',
'expected': expected,
'actual': actual
});
}
// EXPORTS //
module.exports = equal;
},{}],192:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Forcefully ends a benchmark.
*
* @private
* @returns {void}
*/
function exit() {
/* eslint-disable no-invalid-this */
if ( this._exited ) {
// If we have already "exited", do not create more failing assertions when one should suffice...
return;
}
// Only "exit" when a benchmark has either not yet been run or is currently running. If a benchmark has already ended, no need to generate a failing assertion.
if ( !this._ended ) {
this._exited = true;
this.fail( 'benchmark exited without ending' );
// Allow running benchmarks to call `end` on their own...
if ( !this._running ) {
this.end();
}
}
}
// EXPORTS //
module.exports = exit;
},{}],193:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Generates a failing assertion.
*
* @private
* @param {string} msg - message
*/
function fail( msg ) {
/* eslint-disable no-invalid-this */
this._assert( false, {
'message': msg,
'operator': 'fail'
});
}
// EXPORTS //
module.exports = fail;
},{}],194:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var EventEmitter = require( 'events' ).EventEmitter;
var inherit = require( '@stdlib/utils/inherit' );
var defineProperty = require( '@stdlib/utils/define-property' );
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var tic = require( '@stdlib/time/tic' );
var toc = require( '@stdlib/time/toc' );
var run = require( './run.js' );
var exit = require( './exit.js' );
var ended = require( './ended.js' );
var assert = require( './assert.js' );
var comment = require( './comment.js' );
var skip = require( './skip.js' );
var todo = require( './todo.js' );
var fail = require( './fail.js' );
var pass = require( './pass.js' );
var ok = require( './ok.js' );
var notOk = require( './not_ok.js' );
var equal = require( './equal.js' );
var notEqual = require( './not_equal.js' );
var deepEqual = require( './deep_equal.js' );
var notDeepEqual = require( './not_deep_equal.js' );
var end = require( './end.js' );
// MAIN //
/**
* Benchmark constructor.
*
* @constructor
* @param {string} name - benchmark name
* @param {Options} opts - benchmark options
* @param {boolean} opts.skip - boolean indicating whether to skip a benchmark
* @param {PositiveInteger} opts.iterations - number of iterations
* @param {PositiveInteger} opts.timeout - number of milliseconds before a benchmark automatically fails
* @param {Function} [benchmark] - function containing benchmark code
* @returns {Benchmark} Benchmark instance
*
* @example
* var bench = new Benchmark( 'beep', function benchmark( b ) {
* var x;
* var i;
* b.comment( 'Running benchmarks...' );
* b.tic();
* for ( i = 0; i < b.iterations; i++ ) {
* x = Math.sin( Math.random() );
* if ( x !== x ) {
* b.ok( false, 'should not return NaN' );
* }
* }
* b.toc();
* if ( x !== x ) {
* b.ok( false, 'should not return NaN' );
* }
* b.comment( 'Finished running benchmarks.' );
* b.end();
* });
*/
function Benchmark( name, opts, benchmark ) {
var hasTicked;
var hasTocked;
var self;
var time;
if ( !( this instanceof Benchmark ) ) {
return new Benchmark( name, opts, benchmark );
}
self = this;
hasTicked = false;
hasTocked = false;
EventEmitter.call( this );
// Private properties:
setReadOnly( this, '_benchmark', benchmark );
setReadOnly( this, '_skip', opts.skip );
defineProperty( this, '_ended', {
'configurable': false,
'enumerable': false,
'writable': true,
'value': false
});
defineProperty( this, '_running', {
'configurable': false,
'enumerable': false,
'writable': true,
'value': false
});
defineProperty( this, '_exited', {
'configurable': false,
'enumerable': false,
'writable': true,
'value': false
});
defineProperty( this, '_count', {
'configurable': false,
'enumerable': false,
'writable': true,
'value': 0
});
// Read-only:
setReadOnly( this, 'name', name );
setReadOnly( this, 'tic', start );
setReadOnly( this, 'toc', stop );
setReadOnly( this, 'iterations', opts.iterations );
setReadOnly( this, 'timeout', opts.timeout );
return this;
/**
* Starts a benchmark timer.
*
* ## Notes
*
* - Using a scoped variable prevents nefarious mutation by bad actors hoping to manipulate benchmark results.
* - The one attack vector which remains is manipulation of the `require` cache for `tic` and `toc`.
* - One way to combat cache manipulation is by comparing the checksum of `Function#toString()` against known values.
*
* @private
*/
function start() {
if ( hasTicked ) {
self.fail( '.tic() called more than once' );
} else {
self.emit( 'tic' );
hasTicked = true;
time = tic();
}
}
/**
* Stops a benchmark timer.
*
* @private
* @returns {void}
*/
function stop() {
var elapsed;
var secs;
var rate;
var out;
if ( hasTicked === false ) {
return self.fail( '.toc() called before .tic()' );
}
elapsed = toc( time );
if ( hasTocked ) {
return self.fail( '.toc() called more than once' );
}
hasTocked = true;
self.emit( 'toc' );
secs = elapsed[ 0 ] + ( elapsed[ 1 ]/1e9 );
rate = self.iterations / secs;
out = {
'ok': true,
'operator': 'result',
'iterations': self.iterations,
'elapsed': secs,
'rate': rate
};
self.emit( 'result', out );
}
}
/*
* Inherit from the `EventEmitter` prototype.
*/
inherit( Benchmark, EventEmitter );
/**
* Runs a benchmark.
*
* @private
* @name run
* @memberof Benchmark.prototype
* @type {Function}
*/
setReadOnly( Benchmark.prototype, 'run', run );
/**
* Forcefully ends a benchmark.
*
* @private
* @name exit
* @memberof Benchmark.prototype
* @type {Function}
*/
setReadOnly( Benchmark.prototype, 'exit', exit );
/**
* Returns a `boolean` indicating if a benchmark has ended.
*
* @private
* @name ended
* @memberof Benchmark.prototype
* @type {Function}
* @returns {boolean} boolean indicating if a benchmark has ended
*/
setReadOnly( Benchmark.prototype, 'ended', ended );
/**
* Generates an assertion.
*
* @private
* @name _assert
* @memberof Benchmark.prototype
* @type {Function}
* @param {boolean} ok - assertion outcome
* @param {Options} opts - options
*/
setReadOnly( Benchmark.prototype, '_assert', assert );
/**
* Writes a comment.
*
* @name comment
* @memberof Benchmark.prototype
* @type {Function}
* @param {string} msg - comment message
*/
setReadOnly( Benchmark.prototype, 'comment', comment );
/**
* Generates an assertion which will be skipped.
*
* @name skip
* @memberof Benchmark.prototype
* @type {Function}
* @param {*} value - value
* @param {string} msg - message
*/
setReadOnly( Benchmark.prototype, 'skip', skip );
/**
* Generates an assertion which should be implemented.
*
* @name todo
* @memberof Benchmark.prototype
* @type {Function}
* @param {*} value - value
* @param {string} msg - message
*/
setReadOnly( Benchmark.prototype, 'todo', todo );
/**
* Generates a failing assertion.
*
* @name fail
* @memberof Benchmark.prototype
* @type {Function}
* @param {string} msg - message
*/
setReadOnly( Benchmark.prototype, 'fail', fail );
/**
* Generates a passing assertion.
*
* @name pass
* @memberof Benchmark.prototype
* @type {Function}
* @param {string} msg - message
*/
setReadOnly( Benchmark.prototype, 'pass', pass );
/**
* Asserts that a `value` is truthy.
*
* @name ok
* @memberof Benchmark.prototype
* @type {Function}
* @param {*} value - value
* @param {string} [msg] - message
*/
setReadOnly( Benchmark.prototype, 'ok', ok );
/**
* Asserts that a `value` is falsy.
*
* @name notOk
* @memberof Benchmark.prototype
* @type {Function}
* @param {*} value - value
* @param {string} [msg] - message
*/
setReadOnly( Benchmark.prototype, 'notOk', notOk );
/**
* Asserts that `actual` is strictly equal to `expected`.
*
* @name equal
* @memberof Benchmark.prototype
* @type {Function}
* @param {*} actual - actual value
* @param {*} expected - expected value
* @param {string} [msg] - message
*/
setReadOnly( Benchmark.prototype, 'equal', equal );
/**
* Asserts that `actual` is not strictly equal to `expected`.
*
* @name notEqual
* @memberof Benchmark.prototype
* @type {Function}
* @param {*} actual - actual value
* @param {*} expected - expected value
* @param {string} [msg] - message
*/
setReadOnly( Benchmark.prototype, 'notEqual', notEqual );
/**
* Asserts that `actual` is deeply equal to `expected`.
*
* @name deepEqual
* @memberof Benchmark.prototype
* @type {Function}
* @param {*} actual - actual value
* @param {*} expected - expected value
* @param {string} [msg] message
*/
setReadOnly( Benchmark.prototype, 'deepEqual', deepEqual );
/**
* Asserts that `actual` is not deeply equal to `expected`.
*
* @name notDeepEqual
* @memberof Benchmark.prototype
* @type {Function}
* @param {*} actual - actual value
* @param {*} expected - expected value
* @param {string} [msg] message
*/
setReadOnly( Benchmark.prototype, 'notDeepEqual', notDeepEqual );
/**
* Ends a benchmark.
*
* @name end
* @memberof Benchmark.prototype
* @type {Function}
*/
setReadOnly( Benchmark.prototype, 'end', end );
// EXPORTS //
module.exports = Benchmark;
},{"./assert.js":185,"./comment.js":187,"./deep_equal.js":188,"./end.js":189,"./ended.js":190,"./equal.js":191,"./exit.js":192,"./fail.js":193,"./not_deep_equal.js":195,"./not_equal.js":196,"./not_ok.js":197,"./ok.js":198,"./pass.js":199,"./run.js":200,"./skip.js":202,"./todo.js":203,"@stdlib/time/tic":410,"@stdlib/time/toc":414,"@stdlib/utils/define-nonenumerable-read-only-property":428,"@stdlib/utils/define-property":435,"@stdlib/utils/inherit":460,"events":513}],195:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Asserts that `actual` is not deeply equal to `expected`.
*
* @private
* @param {*} actual - actual value
* @param {*} expected - expected value
* @param {string} [msg] message
*/
function notDeepEqual( actual, expected, msg ) {
/* eslint-disable no-invalid-this */
this.comment( 'actual: '+actual+'. expected: '+expected+'. msg: '+msg+'.' );
// TODO: implement
}
// EXPORTS //
module.exports = notDeepEqual;
},{}],196:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Asserts that `actual` is not strictly equal to `expected`.
*
* @private
* @param {*} actual - actual value
* @param {*} expected - expected value
* @param {string} [msg] - message
*/
function notEqual( actual, expected, msg ) {
/* eslint-disable no-invalid-this */
this._assert( actual !== expected, {
'message': msg || 'should not be equal',
'operator': 'notEqual',
'expected': expected,
'actual': actual
});
}
// EXPORTS //
module.exports = notEqual;
},{}],197:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Asserts that a `value` is falsy.
*
* @private
* @param {*} value - value
* @param {string} [msg] - message
*/
function notOk( value, msg ) {
/* eslint-disable no-invalid-this */
this._assert( !value, {
'message': msg || 'should be falsy',
'operator': 'notOk',
'expected': false,
'actual': value
});
}
// EXPORTS //
module.exports = notOk;
},{}],198:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Asserts that a `value` is truthy.
*
* @private
* @param {*} value - value
* @param {string} [msg] - message
*/
function ok( value, msg ) {
/* eslint-disable no-invalid-this */
this._assert( !!value, {
'message': msg || 'should be truthy',
'operator': 'ok',
'expected': true,
'actual': value
});
}
// EXPORTS //
module.exports = ok;
},{}],199:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Generates a passing assertion.
*
* @private
* @param {string} msg - message
*/
function pass( msg ) {
/* eslint-disable no-invalid-this */
this._assert( true, {
'message': msg,
'operator': 'pass'
});
}
// EXPORTS //
module.exports = pass;
},{}],200:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var timeout = require( './set_timeout.js' );
var clear = require( './clear_timeout.js' );
// MAIN //
/**
* Runs a benchmark.
*
* @private
* @returns {void}
*/
function run() {
/* eslint-disable no-invalid-this */
var self;
var id;
if ( this._skip ) {
this.comment( 'SKIP '+this.name );
return this.end();
}
if ( !this._benchmark ) {
this.comment( 'TODO '+this.name );
return this.end();
}
self = this;
this._running = true;
id = timeout( onTimeout, this.timeout );
this.once( 'end', endTimeout );
this.emit( 'prerun' );
this._benchmark( this );
this.emit( 'run' );
/**
* Callback invoked once a timeout ends.
*
* @private
*/
function onTimeout() {
self.fail( 'benchmark timed out after '+self.timeout+'ms' );
}
/**
* Clears a timeout.
*
* @private
*/
function endTimeout() {
clear( id );
}
}
// EXPORTS //
module.exports = run;
},{"./clear_timeout.js":186,"./set_timeout.js":201}],201:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// EXPORTS //
module.exports = setTimeout;
},{}],202:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Generates an assertion which will be skipped.
*
* @private
* @param {*} value - value
* @param {string} msg - message
*/
function skip( value, msg ) {
/* eslint-disable no-invalid-this */
this._assert( true, {
'message': msg,
'operator': 'skip',
'skip': true
});
}
// EXPORTS //
module.exports = skip;
},{}],203:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Generates an assertion which should be implemented.
*
* @private
* @param {*} value - value
* @param {string} msg - message
*/
function todo( value, msg ) {
/* eslint-disable no-invalid-this */
this._assert( !!value, {
'message': msg,
'operator': 'todo',
'todo': true
});
}
// EXPORTS //
module.exports = todo;
},{}],204:[function(require,module,exports){
module.exports={
"skip": false,
"iterations": null,
"repeats": 3,
"timeout": 300000
}
},{}],205:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isFunction = require( '@stdlib/assert/is-function' );
var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive;
var isObject = require( '@stdlib/assert/is-plain-object' );
var isNodeWritableStreamLike = require( '@stdlib/assert/is-node-writable-stream-like' );
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var pick = require( '@stdlib/utils/pick' );
var omit = require( '@stdlib/utils/omit' );
var noop = require( '@stdlib/utils/noop' );
var createHarness = require( './harness' );
var logStream = require( './log' );
var canEmitExit = require( './utils/can_emit_exit.js' );
var proc = require( './utils/process.js' );
// MAIN //
/**
* Creates a benchmark harness which supports closing when a process exits.
*
* @private
* @param {Options} [options] - function options
* @param {boolean} [options.autoclose] - boolean indicating whether to automatically close a harness after a harness finishes running all benchmarks
* @param {Stream} [options.stream] - output writable stream
* @param {Callback} [clbk] - callback to invoke when a harness finishes running all benchmarks
* @throws {TypeError} options argument must be an object
* @throws {TypeError} must provide valid options
* @throws {TypeError} callback argument must be a function
* @returns {Function} benchmark harness
*
* @example
* var proc = require( 'process' );
* var bench = createExitHarness( onFinish );
*
* function onFinish() {
* bench.close();
* }
*
* bench( 'beep', function benchmark( b ) {
* var x;
* var i;
* b.tic();
* for ( i = 0; i < b.iterations; i++ ) {
* x = Math.sin( Math.random() );
* if ( x !== x ) {
* b.ok( false, 'should not return NaN' );
* }
* }
* b.toc();
* if ( x !== x ) {
* b.ok( false, 'should not return NaN' );
* }
* b.end();
* });
*
* @example
* var stdout = require( '@stdlib/streams/node/stdout' );
*
* var stream = createExitHarness().createStream();
* stream.pipe( stdout );
*/
function createExitHarness() {
var exitCode;
var pipeline;
var harness;
var options;
var stream;
var topts;
var opts;
var clbk;
if ( arguments.length === 0 ) {
options = {};
clbk = noop;
} else if ( arguments.length === 1 ) {
if ( isFunction( arguments[ 0 ] ) ) {
options = {};
clbk = arguments[ 0 ];
} else if ( isObject( arguments[ 0 ] ) ) {
options = arguments[ 0 ];
clbk = noop;
} else {
throw new TypeError( 'invalid argument. Must provide either an options object or a callback function. Value: `'+arguments[ 0 ]+'`.' );
}
} else {
options = arguments[ 0 ];
if ( !isObject( options ) ) {
throw new TypeError( 'invalid argument. First argument must be an object. Value: `'+options+'`.' );
}
clbk = arguments[ 1 ];
if ( !isFunction( clbk ) ) {
throw new TypeError( 'invalid argument. Second argument must be a function. Value: `'+clbk+'`.' );
}
}
opts = {};
if ( hasOwnProp( options, 'autoclose' ) ) {
opts.autoclose = options.autoclose;
if ( !isBoolean( opts.autoclose ) ) {
throw new TypeError( 'invalid option. `autoclose` option must be a boolean primitive. Option: `'+opts.autoclose+'`.' );
}
}
if ( hasOwnProp( options, 'stream' ) ) {
opts.stream = options.stream;
if ( !isNodeWritableStreamLike( opts.stream ) ) {
throw new TypeError( 'invalid option. `stream` option must be a writable stream. Option: `'+opts.stream+'`.' );
}
}
exitCode = 0;
// Create a new harness:
topts = pick( opts, [ 'autoclose' ] );
harness = createHarness( topts, done );
// Create a results stream:
topts = omit( options, [ 'autoclose', 'stream' ] );
stream = harness.createStream( topts );
// Pipe results to an output stream:
pipeline = stream.pipe( opts.stream || logStream() );
// If a process can emit an 'exit' event, capture errors in order to set the exit code...
if ( canEmitExit ) {
pipeline.on( 'error', onError );
proc.on( 'exit', onExit );
}
return harness;
/**
* Callback invoked when a harness finishes.
*
* @private
* @returns {void}
*/
function done() {
return clbk();
}
/**
* Callback invoked upon a stream `error` event.
*
* @private
* @param {Error} error - error object
*/
function onError() {
exitCode = 1;
}
/**
* Callback invoked upon an `exit` event.
*
* @private
* @param {integer} code - exit code
*/
function onExit( code ) {
if ( code !== 0 ) {
// Allow the process to exit...
return;
}
harness.close();
proc.exit( exitCode || harness.exitCode );
}
}
// EXPORTS //
module.exports = createExitHarness;
},{"./harness":207,"./log":213,"./utils/can_emit_exit.js":224,"./utils/process.js":227,"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-boolean":81,"@stdlib/assert/is-function":102,"@stdlib/assert/is-node-writable-stream-like":124,"@stdlib/assert/is-plain-object":147,"@stdlib/utils/noop":488,"@stdlib/utils/omit":490,"@stdlib/utils/pick":492}],206:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var canEmitExit = require( './utils/can_emit_exit.js' );
var createExitHarness = require( './exit_harness.js' );
// VARIABLES //
var harness;
// MAIN //
/**
* Returns a benchmark harness. If a harness has already been created, returns the cached harness.
*
* @private
* @param {Options} [options] - harness options
* @param {Callback} [clbk] - callback to invoke when a harness finishes running all benchmarks
* @returns {Function} benchmark harness
*/
function getHarness( options, clbk ) {
var opts;
var cb;
if ( harness ) {
return harness;
}
if ( arguments.length > 1 ) {
opts = options;
cb = clbk;
} else {
opts = {};
cb = options;
}
opts.autoclose = !canEmitExit;
harness = createExitHarness( opts, cb );
// Update state:
getHarness.cached = true;
return harness;
}
// EXPORTS //
module.exports = getHarness;
},{"./exit_harness.js":205,"./utils/can_emit_exit.js":224}],207:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var setReadOnlyAccessor = require( '@stdlib/utils/define-nonenumerable-read-only-accessor' );
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var isFunction = require( '@stdlib/assert/is-function' );
var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive;
var isObject = require( '@stdlib/assert/is-plain-object' );
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var copy = require( '@stdlib/utils/copy' );
var Benchmark = require( './../benchmark-class' );
var Runner = require( './../runner' );
var nextTick = require( './../utils/next_tick.js' );
var DEFAULTS = require( './../defaults.json' );
var validate = require( './validate.js' );
var init = require( './init.js' );
// MAIN //
/**
* Creates a benchmark harness.
*
* @param {Options} [options] - function options
* @param {boolean} [options.autoclose] - boolean indicating whether to automatically close a harness after a harness finishes running all benchmarks
* @param {Callback} [clbk] - callback to invoke when a harness finishes running all benchmarks
* @throws {TypeError} options argument must be an object
* @throws {TypeError} must provide valid options
* @throws {TypeError} callback argument must be a function
* @returns {Function} benchmark harness
*
* @example
* var bench = createHarness( onFinish );
*
* function onFinish() {
* bench.close();
* console.log( 'Exit code: %d', bench.exitCode );
* }
*
* bench( 'beep', function benchmark( b ) {
* var x;
* var i;
* b.tic();
* for ( i = 0; i < b.iterations; i++ ) {
* x = Math.sin( Math.random() );
* if ( x !== x ) {
* b.ok( false, 'should not return NaN' );
* }
* }
* b.toc();
* if ( x !== x ) {
* b.ok( false, 'should not return NaN' );
* }
* b.end();
* });
*
* @example
* var stdout = require( '@stdlib/streams/node/stdout' );
*
* var stream = createHarness().createStream();
* stream.pipe( stdout );
*/
function createHarness( options, clbk ) {
var exitCode;
var runner;
var queue;
var opts;
var cb;
opts = {};
if ( arguments.length === 1 ) {
if ( isFunction( options ) ) {
cb = options;
} else if ( isObject( options ) ) {
opts = options;
} else {
throw new TypeError( 'invalid argument. Must provide either an options object or a callback function. Value: `'+options+'`.' );
}
} else if ( arguments.length > 1 ) {
if ( !isObject( options ) ) {
throw new TypeError( 'invalid argument. First argument must be an object. Value: `'+options+'`.' );
}
if ( hasOwnProp( options, 'autoclose' ) ) {
opts.autoclose = options.autoclose;
if ( !isBoolean( opts.autoclose ) ) {
throw new TypeError( 'invalid option. `autoclose` option must be a boolean primitive. Option: `'+opts.autoclose+'`.' );
}
}
cb = clbk;
if ( !isFunction( cb ) ) {
throw new TypeError( 'invalid argument. Second argument must be a function. Value: `'+cb+'`.' );
}
}
runner = new Runner();
if ( opts.autoclose ) {
runner.once( 'done', close );
}
if ( cb ) {
runner.once( 'done', cb );
}
exitCode = 0;
queue = [];
/**
* Benchmark harness.
*
* @private
* @param {string} name - benchmark name
* @param {Options} [options] - benchmark options
* @param {boolean} [options.skip=false] - boolean indicating whether to skip a benchmark
* @param {(PositiveInteger|null)} [options.iterations=null] - number of iterations
* @param {PositiveInteger} [options.repeats=3] - number of repeats
* @param {PositiveInteger} [options.timeout=300000] - number of milliseconds before a benchmark automatically fails
* @param {Function} [benchmark] - function containing benchmark code
* @throws {TypeError} first argument must be a string
* @throws {TypeError} options argument must be an object
* @throws {TypeError} must provide valid options
* @throws {TypeError} benchmark argument must a function
* @throws {Error} benchmark error
* @returns {Function} benchmark harness
*/
function harness( name, options, benchmark ) {
var opts;
var err;
var b;
if ( !isString( name ) ) {
throw new TypeError( 'invalid argument. First argument must be a string. Value: `'+name+'`.' );
}
opts = copy( DEFAULTS );
if ( arguments.length === 2 ) {
if ( isFunction( options ) ) {
b = options;
} else {
err = validate( opts, options );
if ( err ) {
throw err;
}
}
} else if ( arguments.length > 2 ) {
err = validate( opts, options );
if ( err ) {
throw err;
}
b = benchmark;
if ( !isFunction( b ) ) {
throw new TypeError( 'invalid argument. Third argument must be a function. Value: `'+b+'`.' );
}
}
// Add the benchmark to the initialization queue:
queue.push( [ name, opts, b ] );
// Perform initialization on the next turn of the event loop (note: this allows all benchmarks to be "registered" within the same turn of the loop; otherwise, we run the risk of registration-execution race conditions (i.e., a benchmark registers and executes before other benchmarks can register, depleting the benchmark queue and leading the harness to close)):
if ( queue.length === 1 ) {
nextTick( initialize );
}
return harness;
}
/**
* Initializes each benchmark.
*
* @private
* @returns {void}
*/
function initialize() {
var idx = -1;
return next();
/**
* Initialize the next benchmark.
*
* @private
* @returns {void}
*/
function next() {
var args;
idx += 1;
// If all benchmarks have been initialized, begin running the benchmarks:
if ( idx === queue.length ) {
queue.length = 0;
return runner.run();
}
// Initialize the next benchmark:
args = queue[ idx ];
init( args[ 0 ], args[ 1 ], args[ 2 ], onInit );
}
/**
* Callback invoked after performing initialization tasks.
*
* @private
* @param {string} name - benchmark name
* @param {Options} opts - benchmark options
* @param {(Function|undefined)} benchmark - function containing benchmark code
* @returns {void}
*/
function onInit( name, opts, benchmark ) {
var b;
var i;
// Create a `Benchmark` instance for each repeat to ensure each benchmark has its own state...
for ( i = 0; i < opts.repeats; i++ ) {
b = new Benchmark( name, opts, benchmark );
b.on( 'result', onResult );
runner.push( b );
}
return next();
}
}
/**
* Callback invoked upon a `result` event.
*
* @private
* @param {(string|Object)} result - result
*/
function onResult( result ) {
if (
!isString( result ) &&
!result.ok &&
!result.todo
) {
exitCode = 1;
}
}
/**
* Returns a results stream.
*
* @private
* @param {Object} [options] - options
* @returns {TransformStream} transform stream
*/
function createStream( options ) {
if ( arguments.length ) {
return runner.createStream( options );
}
return runner.createStream();
}
/**
* Closes a benchmark harness.
*
* @private
*/
function close() {
runner.close();
}
/**
* Forcefully exits a benchmark harness.
*
* @private
*/
function exit() {
runner.exit();
}
/**
* Returns the harness exit code.
*
* @private
* @returns {NonNegativeInteger} exit code
*/
function getExitCode() {
return exitCode;
}
setReadOnly( harness, 'createStream', createStream );
setReadOnly( harness, 'close', close );
setReadOnly( harness, 'exit', exit );
setReadOnlyAccessor( harness, 'exitCode', getExitCode );
return harness;
}
// EXPORTS //
module.exports = createHarness;
},{"./../benchmark-class":194,"./../defaults.json":204,"./../runner":221,"./../utils/next_tick.js":226,"./init.js":208,"./validate.js":211,"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-boolean":81,"@stdlib/assert/is-function":102,"@stdlib/assert/is-plain-object":147,"@stdlib/assert/is-string":162,"@stdlib/utils/copy":422,"@stdlib/utils/define-nonenumerable-read-only-accessor":426,"@stdlib/utils/define-nonenumerable-read-only-property":428}],208:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var pretest = require( './pretest.js' );
var iterations = require( './iterations.js' );
// MAIN //
/**
* Performs benchmark initialization tasks.
*
* @private
* @param {string} name - benchmark name
* @param {Options} opts - benchmark options
* @param {(Function|undefined)} benchmark - function containing benchmark code
* @param {Callback} clbk - callback to invoke after completing initialization tasks
* @returns {void}
*/
function init( name, opts, benchmark, clbk ) {
// If no benchmark function, then the benchmark is considered a "todo", so no need to repeat multiple times...
if ( !benchmark ) {
opts.repeats = 1;
return clbk( name, opts, benchmark );
}
// If the `skip` option to `true`, no need to initialize or repeat multiple times as will not be running the benchmark:
if ( opts.skip ) {
opts.repeats = 1;
return clbk( name, opts, benchmark );
}
// Perform pretests:
pretest( name, opts, benchmark, onPreTest );
/**
* Callback invoked upon completing pretests.
*
* @private
* @param {Error} [error] - error object
* @returns {void}
*/
function onPreTest( error ) {
// If the pretests failed, don't run the benchmark multiple times...
if ( error ) {
opts.repeats = 1;
opts.iterations = 1;
return clbk( name, opts, benchmark );
}
// If a user specified an iteration number, we can begin running benchmarks...
if ( opts.iterations ) {
return clbk( name, opts, benchmark );
}
// Determine iteration number:
iterations( name, opts, benchmark, onIterations );
}
/**
* Callback invoked upon determining an iteration number.
*
* @private
* @param {(Error|null)} error - error object
* @param {PositiveInteger} iter - number of iterations
* @returns {void}
*/
function onIterations( error, iter ) {
// If provided an error, then a benchmark failed, and, similar to pretests, don't run the benchmark multiple times...
if ( error ) {
opts.repeats = 1;
opts.iterations = 1;
return clbk( name, opts, benchmark );
}
opts.iterations = iter;
return clbk( name, opts, benchmark );
}
}
// EXPORTS //
module.exports = init;
},{"./iterations.js":209,"./pretest.js":210}],209:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var copy = require( '@stdlib/utils/copy' );
var Benchmark = require( './../benchmark-class' );
// VARIABLES //
var MIN_TIME = 0.1; // seconds
var ITERATIONS = 10; // 10^1
var MAX_ITERATIONS = 10000000000; // 10^10
// MAIN //
/**
* Determines the number of iterations.
*
* @private
* @param {string} name - benchmark name
* @param {Options} options - benchmark options
* @param {(Function|undefined)} benchmark - function containing benchmark code
* @param {Callback} clbk - callback to invoke after determining number of iterations
* @returns {void}
*/
function iterations( name, options, benchmark, clbk ) {
var opts;
var time;
// Elapsed time (in seconds):
time = 0;
// Create a local copy:
opts = copy( options );
opts.iterations = ITERATIONS;
// Begin running benchmarks:
return next();
/**
* Run a new benchmark.
*
* @private
*/
function next() {
var b = new Benchmark( name, opts, benchmark );
b.on( 'result', onResult );
b.once( 'end', onEnd );
b.run();
}
/**
* Callback invoked upon a `result` event.
*
* @private
* @param {(string|Object)} result - result
*/
function onResult( result ) {
if ( !isString( result ) && result.operator === 'result' ) {
time = result.elapsed;
}
}
/**
* Callback invoked upon an `end` event.
*
* @private
* @returns {void}
*/
function onEnd() {
if (
time < MIN_TIME &&
opts.iterations < MAX_ITERATIONS
) {
opts.iterations *= 10;
return next();
}
clbk( null, opts.iterations );
}
}
// EXPORTS //
module.exports = iterations;
},{"./../benchmark-class":194,"@stdlib/assert/is-string":162,"@stdlib/utils/copy":422}],210:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var copy = require( '@stdlib/utils/copy' );
var Benchmark = require( './../benchmark-class' );
// MAIN //
/**
* Runs pretests to sanity check and/or catch failures.
*
* @private
* @param {string} name - benchmark name
* @param {Options} options - benchmark options
* @param {(Function|undefined)} benchmark - function containing benchmark code
* @param {Callback} clbk - callback to invoke after completing pretests
*/
function pretest( name, options, benchmark, clbk ) {
var fail;
var opts;
var tic;
var toc;
var b;
// Counters to determine the number of `tic` and `toc` events:
tic = 0;
toc = 0;
// Local copy:
opts = copy( options );
opts.iterations = 1;
// Pretest to check for minimum requirements and/or errors...
b = new Benchmark( name, opts, benchmark );
b.on( 'result', onResult );
b.on( 'tic', onTic );
b.on( 'toc', onToc );
b.once( 'end', onEnd );
b.run();
/**
* Callback invoked upon a `result` event.
*
* @private
* @param {(string|Object)} result - result
*/
function onResult( result ) {
if (
!isString( result ) &&
!result.ok &&
!result.todo
) {
fail = true;
}
}
/**
* Callback invoked upon a `tic` event.
*
* @private
*/
function onTic() {
tic += 1;
}
/**
* Callback invoked upon a `toc` event.
*
* @private
*/
function onToc() {
toc += 1;
}
/**
* Callback invoked upon an `end` event.
*
* @private
* @returns {void}
*/
function onEnd() {
var err;
if ( fail ) {
// Possibility that failure is intermittent, but we will assume that the usual case is that the failure would persist across all repeats and no sense failing multiple times when once suffices.
err = new Error( 'benchmark failed' );
} else if ( tic !== 1 || toc !== 1 ) {
// Unable to do anything definitive with timing information (e.g., a tic with no toc or vice versa, or benchmark function calls neither tic nor toc).
err = new Error( 'invalid benchmark' );
}
if ( err ) {
return clbk( err );
}
return clbk();
}
}
// EXPORTS //
module.exports = pretest;
},{"./../benchmark-class":194,"@stdlib/assert/is-string":162,"@stdlib/utils/copy":422}],211:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isObject = require( '@stdlib/assert/is-plain-object' );
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive;
var isNull = require( '@stdlib/assert/is-null' );
var isPositiveInteger = require( '@stdlib/assert/is-positive-integer' ).isPrimitive;
// MAIN //
/**
* Validates function options.
*
* @private
* @param {Object} opts - destination object
* @param {Options} options - function options
* @param {boolean} [options.skip] - boolean indicating whether to skip a benchmark
* @param {(PositiveInteger|null)} [options.iterations] - number of iterations
* @param {PositiveInteger} [options.repeats] - number of repeats
* @param {PositiveInteger} [options.timeout] - number of milliseconds before a benchmark automatically fails
* @returns {(Error|null)} error object or null
*
* @example
* var opts = {};
* var options = {
* 'skip': false,
* 'iterations': 1e6,
* 'repeats': 3,
* 'timeout': 10000
* };
*
* var err = validate( opts, options );
* if ( err ) {
* throw err;
* }
*/
function validate( opts, options ) {
if ( !isObject( options ) ) {
return new TypeError( 'invalid argument. Options argument must be an object. Value: `' + options + '`.' );
}
if ( hasOwnProp( options, 'skip' ) ) {
opts.skip = options.skip;
if ( !isBoolean( opts.skip ) ) {
return new TypeError( 'invalid option. `skip` option must be a boolean primitive. Option: `' + opts.skip + '`.' );
}
}
if ( hasOwnProp( options, 'iterations' ) ) {
opts.iterations = options.iterations;
if (
!isPositiveInteger( opts.iterations ) &&
!isNull( opts.iterations )
) {
return new TypeError( 'invalid option. `iterations` option must be either a positive integer or `null`. Option: `' + opts.iterations + '`.' );
}
}
if ( hasOwnProp( options, 'repeats' ) ) {
opts.repeats = options.repeats;
if ( !isPositiveInteger( opts.repeats ) ) {
return new TypeError( 'invalid option. `repeats` option must be a positive integer. Option: `' + opts.repeats + '`.' );
}
}
if ( hasOwnProp( options, 'timeout' ) ) {
opts.timeout = options.timeout;
if ( !isPositiveInteger( opts.timeout ) ) {
return new TypeError( 'invalid option. `timeout` option must be a positive integer. Option: `' + opts.timeout + '`.' );
}
}
return null;
}
// EXPORTS //
module.exports = validate;
},{"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-boolean":81,"@stdlib/assert/is-null":135,"@stdlib/assert/is-plain-object":147,"@stdlib/assert/is-positive-integer":149}],212:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Benchmark harness.
*
* @module @stdlib/bench/harness
*
* @example
* var bench = require( '@stdlib/bench/harness' );
*
* bench( 'beep', function benchmark( b ) {
* var x;
* var i;
* b.tic();
* for ( i = 0; i < b.iterations; i++ ) {
* x = Math.sin( Math.random() );
* if ( x !== x ) {
* b.ok( false, 'should not return NaN' );
* }
* }
* b.toc();
* if ( x !== x ) {
* b.ok( false, 'should not return NaN' );
* }
* b.end();
* });
*/
// MODULES //
var bench = require( './bench.js' );
// EXPORTS //
module.exports = bench;
},{"./bench.js":184}],213:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var TransformStream = require( '@stdlib/streams/node/transform' );
var fromCodePoint = require( '@stdlib/string/from-code-point' );
var log = require( './log.js' );
// MAIN //
/**
* Returns a Transform stream for logging to the console.
*
* @private
* @returns {TransformStream} transform stream
*/
function createStream() {
var stream;
var line;
stream = new TransformStream({
'transform': transform,
'flush': flush
});
line = '';
return stream;
/**
* Callback invoked upon receiving a new chunk.
*
* @private
* @param {(Buffer|string)} chunk - chunk
* @param {string} enc - Buffer encoding
* @param {Callback} clbk - callback to invoke after transforming the streamed chunk
*/
function transform( chunk, enc, clbk ) {
var c;
var i;
for ( i = 0; i < chunk.length; i++ ) {
c = fromCodePoint( chunk[ i ] );
if ( c === '\n' ) {
flush();
} else {
line += c;
}
}
clbk();
}
/**
* Callback to flush data to `stdout`.
*
* @private
* @param {Callback} [clbk] - callback to invoke after processing data
* @returns {void}
*/
function flush( clbk ) {
try {
log( line );
} catch ( err ) {
stream.emit( 'error', err );
}
line = '';
if ( clbk ) {
return clbk();
}
}
}
// EXPORTS //
module.exports = createStream;
},{"./log.js":214,"@stdlib/streams/node/transform":400,"@stdlib/string/from-code-point":404}],214:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Writes a string to the console.
*
* @private
* @param {string} str - string to write
*/
function log( str ) {
console.log( str ); // eslint-disable-line no-console
}
// EXPORTS //
module.exports = log;
},{}],215:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Removes any pending benchmarks.
*
* @private
*/
function clear() {
/* eslint-disable no-invalid-this */
this._benchmarks.length = 0;
}
// EXPORTS //
module.exports = clear;
},{}],216:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Closes a benchmark runner.
*
* @private
* @returns {void}
*/
function closeRunner() {
/* eslint-disable no-invalid-this */
var self = this;
if ( this._closed ) {
return;
}
this._closed = true;
if ( this._benchmarks.length ) {
this.clear();
this._stream.write( '# WARNING: harness closed before completion.\n' );
} else {
this._stream.write( '#\n' );
this._stream.write( '1..'+this.total+'\n' );
this._stream.write( '# total '+this.total+'\n' );
this._stream.write( '# pass '+this.pass+'\n' );
if ( this.fail ) {
this._stream.write( '# fail '+this.fail+'\n' );
}
if ( this.skip ) {
this._stream.write( '# skip '+this.skip+'\n' );
}
if ( this.todo ) {
this._stream.write( '# todo '+this.todo+'\n' );
}
if ( !this.fail ) {
this._stream.write( '#\n# ok\n' );
}
}
this._stream.once( 'close', onClose );
this._stream.destroy();
/**
* Callback invoked upon a `close` event.
*
* @private
*/
function onClose() {
self.emit( 'close' );
}
}
// EXPORTS //
module.exports = closeRunner;
},{}],217:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
/* eslint-disable no-underscore-dangle */
'use strict';
// MODULES //
var TransformStream = require( '@stdlib/streams/node/transform' );
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var nextTick = require( './../utils/next_tick.js' );
// VARIABLES //
var TAP_HEADER = 'TAP version 13';
// MAIN //
/**
* Creates a results stream.
*
* @private
* @param {Options} [options] - stream options
* @throws {TypeError} options argument must be an object
* @throws {TypeError} must provide valid options
* @returns {TransformStream} transform stream
*/
function createStream( options ) {
/* eslint-disable no-invalid-this */
var stream;
var opts;
var self;
var id;
self = this;
if ( arguments.length ) {
opts = options;
} else {
opts = {};
}
stream = new TransformStream( opts );
if ( opts.objectMode ) {
id = 0;
this.on( '_push', onPush );
this.on( 'done', onDone );
} else {
stream.write( TAP_HEADER+'\n' );
this._stream.pipe( stream );
}
this.on( '_run', onRun );
return stream;
/**
* Runs the next benchmark.
*
* @private
*/
function next() {
nextTick( onTick );
}
/**
* Callback invoked upon the next tick.
*
* @private
* @returns {void}
*/
function onTick() {
var b = self._benchmarks.shift();
if ( b ) {
b.run();
if ( !b.ended() ) {
return b.once( 'end', next );
}
return next();
}
self._running = false;
self.emit( 'done' );
}
/**
* Callback invoked upon a run event.
*
* @private
* @returns {void}
*/
function onRun() {
if ( !self._running ) {
self._running = true;
return next();
}
}
/**
* Callback invoked upon a push event.
*
* @private
* @param {Benchmark} b - benchmark
*/
function onPush( b ) {
var bid = id;
id += 1;
b.once( 'prerun', onPreRun );
b.on( 'result', onResult );
b.on( 'end', onEnd );
/**
* Callback invoked upon a `prerun` event.
*
* @private
*/
function onPreRun() {
var row = {
'type': 'benchmark',
'name': b.name,
'id': bid
};
stream.write( row );
}
/**
* Callback invoked upon a `result` event.
*
* @private
* @param {(Object|string)} res - result
*/
function onResult( res ) {
if ( isString( res ) ) {
res = {
'benchmark': bid,
'type': 'comment',
'name': res
};
} else if ( res.operator === 'result' ) {
res.benchmark = bid;
res.type = 'result';
} else {
res.benchmark = bid;
res.type = 'assert';
}
stream.write( res );
}
/**
* Callback invoked upon an `end` event.
*
* @private
*/
function onEnd() {
stream.write({
'benchmark': bid,
'type': 'end'
});
}
}
/**
* Callback invoked upon a `done` event.
*
* @private
*/
function onDone() {
stream.destroy();
}
}
// EXPORTS //
module.exports = createStream;
},{"./../utils/next_tick.js":226,"@stdlib/assert/is-string":162,"@stdlib/streams/node/transform":400}],218:[function(require,module,exports){
/* eslint-disable stdlib/jsdoc-require-throws-tags */
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var replace = require( '@stdlib/string/replace' );
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var reEOL = require( '@stdlib/regexp/eol' );
// VARIABLES //
var RE_WHITESPACE = /\s+/g;
// MAIN //
/**
* Encodes an assertion.
*
* @private
* @param {Object} result - result
* @param {PositiveInteger} count - result count
* @returns {string} encoded assertion
*/
function encodeAssertion( result, count ) {
var actualStack;
var errorStack;
var expected;
var actual;
var indent;
var stack;
var lines;
var out;
var i;
out = '';
if ( !result.ok ) {
out += 'not ';
}
// Add result count:
out += 'ok ' + count;
// Add description:
if ( result.name ) {
out += ' ' + replace( result.name.toString(), RE_WHITESPACE, ' ' );
}
// Append directives:
if ( result.skip ) {
out += ' # SKIP';
} else if ( result.todo ) {
out += ' # TODO';
}
out += '\n';
if ( result.ok ) {
return out;
}
// Format diagnostics as YAML...
indent = ' ';
out += indent + '---\n';
out += indent + 'operator: ' + result.operator + '\n';
if (
hasOwnProp( result, 'actual' ) ||
hasOwnProp( result, 'expected' )
) {
// TODO: inspect object logic (https://github.com/substack/tape/blob/master/lib/results.js#L145)
expected = result.expected;
actual = result.actual;
if ( actual !== actual && expected !== expected ) {
throw new Error( 'TODO: remove me' );
}
}
if ( result.at ) {
out += indent + 'at: ' + result.at + '\n';
}
if ( result.actual ) {
actualStack = result.actual.stack;
}
if ( result.error ) {
errorStack = result.error.stack;
}
if ( actualStack ) {
stack = actualStack;
} else {
stack = errorStack;
}
if ( stack ) {
lines = stack.toString().split( reEOL.REGEXP );
out += indent + 'stack: |-\n';
for ( i = 0; i < lines.length; i++ ) {
out += indent + ' ' + lines[ i ] + '\n';
}
}
out += indent + '...\n';
return out;
}
// EXPORTS //
module.exports = encodeAssertion;
},{"@stdlib/assert/has-own-property":53,"@stdlib/regexp/eol":384,"@stdlib/string/replace":406}],219:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// VARIABLES //
var YAML_INDENT = ' ';
var YAML_BEGIN = YAML_INDENT + '---\n';
var YAML_END = YAML_INDENT + '...\n';
// MAIN //
/**
* Encodes a result as a YAML block.
*
* @private
* @param {Object} result - result
* @returns {string} encoded result
*/
function encodeResult( result ) {
var out = YAML_BEGIN;
out += YAML_INDENT + 'iterations: '+result.iterations+'\n';
out += YAML_INDENT + 'elapsed: '+result.elapsed+'\n';
out += YAML_INDENT + 'rate: '+result.rate+'\n';
out += YAML_END;
return out;
}
// EXPORTS //
module.exports = encodeResult;
},{}],220:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Forcefully exits a benchmark runner.
*
* @private
*/
function exit() {
/* eslint-disable no-invalid-this */
var self;
var i;
for ( i = 0; i < this._benchmarks.length; i++ ) {
this._benchmarks[ i ].exit();
}
self = this;
this.clear();
this._stream.once( 'close', onClose );
this._stream.destroy();
/**
* Callback invoked upon a `close` event.
*
* @private
*/
function onClose() {
self.emit( 'close' );
}
}
// EXPORTS //
module.exports = exit;
},{}],221:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var EventEmitter = require( 'events' ).EventEmitter;
var inherit = require( '@stdlib/utils/inherit' );
var defineProperty = require( '@stdlib/utils/define-property' );
var TransformStream = require( '@stdlib/streams/node/transform' );
var push = require( './push.js' );
var createStream = require( './create_stream.js' );
var run = require( './run.js' );
var clear = require( './clear.js' );
var close = require( './close.js' ); // eslint-disable-line stdlib/no-redeclare
var exit = require( './exit.js' );
// MAIN //
/**
* Benchmark runner.
*
* @private
* @constructor
* @returns {Runner} Runner instance
*
* @example
* var runner = new Runner();
*/
function Runner() {
if ( !( this instanceof Runner ) ) {
return new Runner();
}
EventEmitter.call( this );
// Private properties:
defineProperty( this, '_benchmarks', {
'value': [],
'configurable': false,
'writable': false,
'enumerable': false
});
defineProperty( this, '_stream', {
'value': new TransformStream(),
'configurable': false,
'writable': false,
'enumerable': false
});
defineProperty( this, '_closed', {
'value': false,
'configurable': false,
'writable': true,
'enumerable': false
});
defineProperty( this, '_running', {
'value': false,
'configurable': false,
'writable': true,
'enumerable': false
});
// Public properties:
defineProperty( this, 'total', {
'value': 0,
'configurable': false,
'writable': true,
'enumerable': true
});
defineProperty( this, 'fail', {
'value': 0,
'configurable': false,
'writable': true,
'enumerable': true
});
defineProperty( this, 'pass', {
'value': 0,
'configurable': false,
'writable': true,
'enumerable': true
});
defineProperty( this, 'skip', {
'value': 0,
'configurable': false,
'writable': true,
'enumerable': true
});
defineProperty( this, 'todo', {
'value': 0,
'configurable': false,
'writable': true,
'enumerable': true
});
return this;
}
/*
* Inherit from the `EventEmitter` prototype.
*/
inherit( Runner, EventEmitter );
/**
* Adds a new benchmark.
*
* @private
* @memberof Runner.prototype
* @function push
* @param {Benchmark} b - benchmark
*/
defineProperty( Runner.prototype, 'push', {
'value': push,
'configurable': false,
'writable': false,
'enumerable': false
});
/**
* Creates a results stream.
*
* @private
* @memberof Runner.prototype
* @function createStream
* @param {Options} [options] - stream options
* @returns {TransformStream} transform stream
*/
defineProperty( Runner.prototype, 'createStream', {
'value': createStream,
'configurable': false,
'writable': false,
'enumerable': false
});
/**
* Runs pending benchmarks.
*
* @private
* @memberof Runner.prototype
* @function run
*/
defineProperty( Runner.prototype, 'run', {
'value': run,
'configurable': false,
'writable': false,
'enumerable': false
});
/**
* Removes any pending benchmarks.
*
* @private
* @memberof Runner.prototype
* @function clear
*/
defineProperty( Runner.prototype, 'clear', {
'value': clear,
'configurable': false,
'writable': false,
'enumerable': false
});
/**
* Closes a benchmark runner.
*
* @private
* @memberof Runner.prototype
* @function close
*/
defineProperty( Runner.prototype, 'close', {
'value': close,
'configurable': false,
'writable': false,
'enumerable': false
});
/**
* Forcefully exits a benchmark runner.
*
* @private
* @memberof Runner.prototype
* @function exit
*/
defineProperty( Runner.prototype, 'exit', {
'value': exit,
'configurable': false,
'writable': false,
'enumerable': false
});
// EXPORTS //
module.exports = Runner;
},{"./clear.js":215,"./close.js":216,"./create_stream.js":217,"./exit.js":220,"./push.js":222,"./run.js":223,"@stdlib/streams/node/transform":400,"@stdlib/utils/define-property":435,"@stdlib/utils/inherit":460,"events":513}],222:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
/* eslint-disable no-underscore-dangle */
'use strict';
// MODULES //
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var encodeAssertion = require( './encode_assertion.js' );
var encodeResult = require( './encode_result.js' );
// MAIN //
/**
* Adds a new benchmark.
*
* @private
* @param {Benchmark} b - benchmark
*/
function push( b ) {
/* eslint-disable no-invalid-this */
var self = this;
this._benchmarks.push( b );
b.once( 'prerun', onPreRun );
b.on( 'result', onResult );
this.emit( '_push', b );
/**
* Callback invoked upon a `prerun` event.
*
* @private
*/
function onPreRun() {
self._stream.write( '# '+b.name+'\n' );
}
/**
* Callback invoked upon a `result` event.
*
* @private
* @param {(Object|string)} res - result
* @returns {void}
*/
function onResult( res ) {
// Check for a comment...
if ( isString( res ) ) {
return self._stream.write( '# '+res+'\n' );
}
if ( res.operator === 'result' ) {
res = encodeResult( res );
return self._stream.write( res );
}
self.total += 1;
if ( res.ok ) {
if ( res.skip ) {
self.skip += 1;
} else if ( res.todo ) {
self.todo += 1;
}
self.pass += 1;
}
// According to the TAP spec, todos pass even if not "ok"...
else if ( res.todo ) {
self.pass += 1;
self.todo += 1;
}
// Everything else is a failure...
else {
self.fail += 1;
}
res = encodeAssertion( res, self.total );
self._stream.write( res );
}
}
// EXPORTS //
module.exports = push;
},{"./encode_assertion.js":218,"./encode_result.js":219,"@stdlib/assert/is-string":162}],223:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Runs pending benchmarks.
*
* @private
*/
function run() {
/* eslint-disable no-invalid-this */
this.emit( '_run' );
}
// EXPORTS //
module.exports = run;
},{}],224:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var IS_BROWSER = require( '@stdlib/assert/is-browser' );
var canExit = require( './can_exit.js' );
// MAIN //
var bool = ( !IS_BROWSER && canExit );
// EXPORTS //
module.exports = bool;
},{"./can_exit.js":225,"@stdlib/assert/is-browser":87}],225:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var proc = require( './process.js' );
// MAIN //
var bool = ( proc && typeof proc.exit === 'function' );
// EXPORTS //
module.exports = bool;
},{"./process.js":227}],226:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Runs a function on a subsequent turn of the event loop.
*
* ## Notes
*
* - `process.nextTick` is only Node.js.
* - `setImmediate` is non-standard.
* - Everything else is browser based (e.g., mutation observer, requestAnimationFrame, etc).
* - Only API which is universal is `setTimeout`.
* - Note that `0` is not actually `0ms`. Browser environments commonly have a minimum delay of `4ms`. This is acceptable. Here, the main intent of this function is to give the runtime a chance to run garbage collection, clear state, and tend to any other pending tasks before returning control to benchmark tasks. The larger aim (attainable or not) is to provide each benchmark run with as much of a fresh state as possible.
*
*
* @private
* @param {Function} fcn - function to run upon a subsequent turn of the event loop
*/
function nextTick( fcn ) {
setTimeout( fcn, 0 );
}
// EXPORTS //
module.exports = nextTick;
},{}],227:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var proc = require( 'process' );
// EXPORTS //
module.exports = proc;
},{"process":524}],228:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Benchmark harness.
*
* @module @stdlib/bench
*
* @example
* var bench = require( '@stdlib/bench' );
*
* bench( 'beep', function benchmark( b ) {
* var x;
* var i;
* b.tic();
* for ( i = 0; i < b.iterations; i++ ) {
* x = Math.sin( Math.random() );
* if ( x !== x ) {
* b.ok( false, 'should not return NaN' );
* }
* }
* b.toc();
* if ( x !== x ) {
* b.ok( false, 'should not return NaN' );
* }
* b.end();
* });
*/
// MODULES //
var bench = require( '@stdlib/bench/harness' );
// EXPORTS //
module.exports = bench;
},{"@stdlib/bench/harness":212}],229:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* BLAS level 1 routine to copy values from `x` into `y`.
*
* @module @stdlib/blas/base/gcopy
*
* @example
* var gcopy = require( '@stdlib/blas/base/gcopy' );
*
* var x = [ 1.0, 2.0, 3.0, 4.0, 5.0 ];
* var y = [ 6.0, 7.0, 8.0, 9.0, 10.0 ];
*
* gcopy( x.length, x, 1, y, 1 );
* // y => [ 1.0, 2.0, 3.0, 4.0, 5.0 ]
*
* @example
* var gcopy = require( '@stdlib/blas/base/gcopy' );
*
* var x = [ 1.0, 2.0, 3.0, 4.0, 5.0 ];
* var y = [ 6.0, 7.0, 8.0, 9.0, 10.0 ];
*
* gcopy.ndarray( x.length, x, 1, 0, y, 1, 0 );
* // y => [ 1.0, 2.0, 3.0, 4.0, 5.0 ]
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var gcopy = require( './main.js' );
var ndarray = require( './ndarray.js' );
// MAIN //
setReadOnly( gcopy, 'ndarray', ndarray );
// EXPORTS //
module.exports = gcopy;
},{"./main.js":230,"./ndarray.js":231,"@stdlib/utils/define-nonenumerable-read-only-property":428}],230:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// VARIABLES //
var M = 8;
// MAIN //
/**
* Copies values from `x` into `y`.
*
* @param {PositiveInteger} N - number of values to copy
* @param {NumericArray} x - input array
* @param {integer} strideX - `x` stride length
* @param {NumericArray} y - destination array
* @param {integer} strideY - `y` stride length
* @returns {NumericArray} `y`
*
* @example
* var x = [ 1.0, 2.0, 3.0, 4.0, 5.0 ];
* var y = [ 6.0, 7.0, 8.0, 9.0, 10.0 ];
*
* gcopy( x.length, x, 1, y, 1 );
* // y => [ 1.0, 2.0, 3.0, 4.0, 5.0 ]
*/
function gcopy( N, x, strideX, y, strideY ) {
var ix;
var iy;
var m;
var i;
if ( N <= 0 ) {
return y;
}
// Use unrolled loops if both strides are equal to `1`...
if ( strideX === 1 && strideY === 1 ) {
m = N % M;
// If we have a remainder, run a clean-up loop...
if ( m > 0 ) {
for ( i = 0; i < m; i++ ) {
y[ i ] = x[ i ];
}
}
if ( N < M ) {
return y;
}
for ( i = m; i < N; i += M ) {
y[ i ] = x[ i ];
y[ i+1 ] = x[ i+1 ];
y[ i+2 ] = x[ i+2 ];
y[ i+3 ] = x[ i+3 ];
y[ i+4 ] = x[ i+4 ];
y[ i+5 ] = x[ i+5 ];
y[ i+6 ] = x[ i+6 ];
y[ i+7 ] = x[ i+7 ];
}
return y;
}
if ( strideX < 0 ) {
ix = (1-N) * strideX;
} else {
ix = 0;
}
if ( strideY < 0 ) {
iy = (1-N) * strideY;
} else {
iy = 0;
}
for ( i = 0; i < N; i++ ) {
y[ iy ] = x[ ix ];
ix += strideX;
iy += strideY;
}
return y;
}
// EXPORTS //
module.exports = gcopy;
},{}],231:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// VARIABLES //
var M = 8;
// MAIN //
/**
* Copies values from `x` into `y`.
*
* @param {PositiveInteger} N - number of values to copy
* @param {NumericArray} x - input array
* @param {integer} strideX - `x` stride length
* @param {NonNegativeInteger} offsetX - starting `x` index
* @param {NumericArray} y - destination array
* @param {integer} strideY - `y` stride length
* @param {NonNegativeInteger} offsetY - starting `y` index
* @returns {NumericArray} `y`
*
* @example
* var x = [ 1.0, 2.0, 3.0, 4.0, 5.0 ];
* var y = [ 6.0, 7.0, 8.0, 9.0, 10.0 ];
*
* gcopy( x.length, x, 1, 0, y, 1, 0 );
* // y => [ 1.0, 2.0, 3.0, 4.0, 5.0 ]
*/
function gcopy( N, x, strideX, offsetX, y, strideY, offsetY ) {
var ix;
var iy;
var m;
var i;
if ( N <= 0 ) {
return y;
}
ix = offsetX;
iy = offsetY;
// Use unrolled loops if both strides are equal to `1`...
if ( strideX === 1 && strideY === 1 ) {
m = N % M;
// If we have a remainder, run a clean-up loop...
if ( m > 0 ) {
for ( i = 0; i < m; i++ ) {
y[ iy ] = x[ ix ];
ix += strideX;
iy += strideY;
}
}
if ( N < M ) {
return y;
}
for ( i = m; i < N; i += M ) {
y[ iy ] = x[ ix ];
y[ iy+1 ] = x[ ix+1 ];
y[ iy+2 ] = x[ ix+2 ];
y[ iy+3 ] = x[ ix+3 ];
y[ iy+4 ] = x[ ix+4 ];
y[ iy+5 ] = x[ ix+5 ];
y[ iy+6 ] = x[ ix+6 ];
y[ iy+7 ] = x[ ix+7 ];
ix += M;
iy += M;
}
return y;
}
for ( i = 0; i < N; i++ ) {
y[ iy ] = x[ ix ];
ix += strideX;
iy += strideY;
}
return y;
}
// EXPORTS //
module.exports = gcopy;
},{}],232:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var ctor = require( 'buffer' ).Buffer; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = ctor;
},{"buffer":514}],233:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Buffer constructor.
*
* @module @stdlib/buffer/ctor
*
* @example
* var ctor = require( '@stdlib/buffer/ctor' );
*
* var b = new ctor( [ 1, 2, 3, 4 ] );
* // returns <Buffer>
*/
// MODULES //
var hasNodeBufferSupport = require( '@stdlib/assert/has-node-buffer-support' );
var main = require( './buffer.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var ctor;
if ( hasNodeBufferSupport() ) {
ctor = main;
} else {
ctor = polyfill;
}
// EXPORTS //
module.exports = ctor;
},{"./buffer.js":232,"./polyfill.js":234,"@stdlib/assert/has-node-buffer-support":51}],234:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// TODO: write (browser) polyfill
// MAIN //
/**
* Buffer constructor.
*
* @throws {Error} not implemented
*/
function polyfill() {
throw new Error( 'not implemented' );
}
// EXPORTS //
module.exports = polyfill;
},{}],235:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isFunction = require( '@stdlib/assert/is-function' );
var Buffer = require( '@stdlib/buffer/ctor' );
// MAIN //
var bool = isFunction( Buffer.from );
// EXPORTS //
module.exports = bool;
},{"@stdlib/assert/is-function":102,"@stdlib/buffer/ctor":233}],236:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Copy buffer data to a new `Buffer` instance.
*
* @module @stdlib/buffer/from-buffer
*
* @example
* var fromArray = require( '@stdlib/buffer/from-array' );
* var copyBuffer = require( '@stdlib/buffer/from-buffer' );
*
* var b1 = fromArray( [ 1, 2, 3, 4 ] );
* // returns <Buffer>
*
* var b2 = copyBuffer( b1 );
* // returns <Buffer>
*/
// MODULES //
var hasFrom = require( './has_from.js' );
var main = require( './main.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var copyBuffer;
if ( hasFrom ) {
copyBuffer = main;
} else {
copyBuffer = polyfill;
}
// EXPORTS //
module.exports = copyBuffer;
},{"./has_from.js":235,"./main.js":237,"./polyfill.js":238}],237:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isBuffer = require( '@stdlib/assert/is-buffer' );
var Buffer = require( '@stdlib/buffer/ctor' );
// MAIN //
/**
* Copies buffer data to a new `Buffer` instance.
*
* @param {Buffer} buffer - buffer from which to copy
* @throws {TypeError} must provide a `Buffer` instance
* @returns {Buffer} new `Buffer` instance
*
* @example
* var fromArray = require( '@stdlib/buffer/from-array' );
*
* var b1 = fromArray( [ 1, 2, 3, 4 ] );
* // returns <Buffer>
*
* var b2 = fromBuffer( b1 );
* // returns <Buffer>
*/
function fromBuffer( buffer ) {
if ( !isBuffer( buffer ) ) {
throw new TypeError( 'invalid argument. Must provide a Buffer. Value: `' + buffer + '`' );
}
return Buffer.from( buffer );
}
// EXPORTS //
module.exports = fromBuffer;
},{"@stdlib/assert/is-buffer":88,"@stdlib/buffer/ctor":233}],238:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isBuffer = require( '@stdlib/assert/is-buffer' );
var Buffer = require( '@stdlib/buffer/ctor' );
// MAIN //
/**
* Copies buffer data to a new `Buffer` instance.
*
* @param {Buffer} buffer - buffer from which to copy
* @throws {TypeError} must provide a `Buffer` instance
* @returns {Buffer} new `Buffer` instance
*
* @example
* var fromArray = require( '@stdlib/buffer/from-array' );
*
* var b1 = fromArray( [ 1, 2, 3, 4 ] );
* // returns <Buffer>
*
* var b2 = fromBuffer( b1 );
* // returns <Buffer>
*/
function fromBuffer( buffer ) {
if ( !isBuffer( buffer ) ) {
throw new TypeError( 'invalid argument. Must provide a Buffer. Value: `' + buffer + '`' );
}
return new Buffer( buffer ); // eslint-disable-line no-buffer-constructor
}
// EXPORTS //
module.exports = fromBuffer;
},{"@stdlib/assert/is-buffer":88,"@stdlib/buffer/ctor":233}],239:[function(require,module,exports){
arguments[4][235][0].apply(exports,arguments)
},{"@stdlib/assert/is-function":102,"@stdlib/buffer/ctor":233,"dup":235}],240:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Allocate a buffer containing a provided string.
*
* @module @stdlib/buffer/from-string
*
* @example
* var string2buffer = require( '@stdlib/buffer/from-string' );
*
* var buf = string2buffer( 'beep boop' );
* // returns <Buffer>
*/
// MODULES //
var hasFrom = require( './has_from.js' );
var main = require( './main.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var string2buffer;
if ( hasFrom ) {
string2buffer = main;
} else {
string2buffer = polyfill;
}
// EXPORTS //
module.exports = string2buffer;
},{"./has_from.js":239,"./main.js":241,"./polyfill.js":242}],241:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var Buffer = require( '@stdlib/buffer/ctor' );
// MAIN //
/**
* Allocates a buffer containing a provided string.
*
* @param {string} str - input string
* @param {string} [encoding="utf8"] - character encoding
* @throws {TypeError} first argument must be a string
* @throws {TypeError} second argument must be a string
* @throws {TypeError} second argument must be a valid encoding
* @returns {Buffer} new `Buffer` instance
*
* @example
* var buf = fromString( 'beep boop' );
* // returns <Buffer>
*/
function fromString( str, encoding ) {
if ( !isString( str ) ) {
throw new TypeError( 'invalid argument. First argument must be a string. Value: `' + str + '`' );
}
if ( arguments.length > 1 ) {
if ( !isString( encoding ) ) {
throw new TypeError( 'invalid argument. Second argument must be a string. Value: `' + encoding + '`' );
}
return Buffer.from( str, encoding );
}
return Buffer.from( str, 'utf8' );
}
// EXPORTS //
module.exports = fromString;
},{"@stdlib/assert/is-string":162,"@stdlib/buffer/ctor":233}],242:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var Buffer = require( '@stdlib/buffer/ctor' );
// MAIN //
/**
* Allocates a buffer containing a provided string.
*
* @param {string} str - input string
* @param {string} [encoding="utf8"] - character encoding
* @throws {TypeError} first argument must be a string
* @throws {TypeError} second argument must be a string
* @throws {TypeError} second argument must be a valid encoding
* @returns {Buffer} new `Buffer` instance
*
* @example
* var buf = fromString( 'beep boop' );
* // returns <Buffer>
*/
function fromString( str, encoding ) {
if ( !isString( str ) ) {
throw new TypeError( 'invalid argument. First argument must be a string. Value: `' + str + '`' );
}
if ( arguments.length > 1 ) {
if ( !isString( encoding ) ) {
throw new TypeError( 'invalid argument. Second argument must be a string. Value: `' + encoding + '`' );
}
return new Buffer( str, encoding ); // eslint-disable-line no-buffer-constructor
}
return new Buffer( str, 'utf8' ); // eslint-disable-line no-buffer-constructor
}
// EXPORTS //
module.exports = fromString;
},{"@stdlib/assert/is-string":162,"@stdlib/buffer/ctor":233}],243:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Maximum length of a generic array.
*
* @module @stdlib/constants/array/max-array-length
*
* @example
* var MAX_ARRAY_LENGTH = require( '@stdlib/constants/array/max-array-length' );
* // returns 4294967295
*/
// MAIN //
/**
* Maximum length of a generic array.
*
* ```tex
* 2^{32} - 1
* ```
*
* @constant
* @type {uinteger32}
* @default 4294967295
*/
var MAX_ARRAY_LENGTH = 4294967295>>>0; // asm type annotation
// EXPORTS //
module.exports = MAX_ARRAY_LENGTH;
},{}],244:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Maximum length of a typed array.
*
* @module @stdlib/constants/array/max-typed-array-length
*
* @example
* var MAX_TYPED_ARRAY_LENGTH = require( '@stdlib/constants/array/max-typed-array-length' );
* // returns 9007199254740991
*/
// MAIN //
/**
* Maximum length of a typed array.
*
* ```tex
* 2^{53} - 1
* ```
*
* @constant
* @type {number}
* @default 9007199254740991
*/
var MAX_TYPED_ARRAY_LENGTH = 9007199254740991;
// EXPORTS //
module.exports = MAX_TYPED_ARRAY_LENGTH;
},{}],245:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* The bias of a double-precision floating-point number's exponent.
*
* @module @stdlib/constants/float64/exponent-bias
* @type {integer32}
*
* @example
* var FLOAT64_EXPONENT_BIAS = require( '@stdlib/constants/float64/exponent-bias' );
* // returns 1023
*/
// MAIN //
/**
* Bias of a double-precision floating-point number's exponent.
*
* ## Notes
*
* The bias can be computed via
*
* ```tex
* \mathrm{bias} = 2^{k-1} - 1
* ```
*
* where \\(k\\) is the number of bits in the exponent; here, \\(k = 11\\).
*
* @constant
* @type {integer32}
* @default 1023
* @see [IEEE 754]{@link https://en.wikipedia.org/wiki/IEEE_754-1985}
*/
var FLOAT64_EXPONENT_BIAS = 1023|0; // asm type annotation
// EXPORTS //
module.exports = FLOAT64_EXPONENT_BIAS;
},{}],246:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* High word mask for the exponent of a double-precision floating-point number.
*
* @module @stdlib/constants/float64/high-word-exponent-mask
* @type {uinteger32}
*
* @example
* var FLOAT64_HIGH_WORD_EXPONENT_MASK = require( '@stdlib/constants/float64/high-word-exponent-mask' );
* // returns 2146435072
*/
// MAIN //
/**
* High word mask for the exponent of a double-precision floating-point number.
*
* ## Notes
*
* The high word mask for the exponent of a double-precision floating-point number is an unsigned 32-bit integer with the value \\( 2146435072 \\), which corresponds to the bit sequence
*
* ```binarystring
* 0 11111111111 00000000000000000000
* ```
*
* @constant
* @type {uinteger32}
* @default 0x7ff00000
* @see [IEEE 754]{@link https://en.wikipedia.org/wiki/IEEE_754-1985}
*/
var FLOAT64_HIGH_WORD_EXPONENT_MASK = 0x7ff00000;
// EXPORTS //
module.exports = FLOAT64_HIGH_WORD_EXPONENT_MASK;
},{}],247:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* High word mask for the significand of a double-precision floating-point number.
*
* @module @stdlib/constants/float64/high-word-significand-mask
* @type {uinteger32}
*
* @example
* var FLOAT64_HIGH_WORD_SIGNIFICAND_MASK = require( '@stdlib/constants/float64/high-word-significand-mask' );
* // returns 1048575
*/
// MAIN //
/**
* High word mask for the significand of a double-precision floating-point number.
*
* ## Notes
*
* The high word mask for the significand of a double-precision floating-point number is an unsigned 32-bit integer with the value \\( 1048575 \\), which corresponds to the bit sequence
*
* ```binarystring
* 0 00000000000 11111111111111111111
* ```
*
* @constant
* @type {uinteger32}
* @default 0x000fffff
* @see [IEEE 754]{@link https://en.wikipedia.org/wiki/IEEE_754-1985}
*/
var FLOAT64_HIGH_WORD_SIGNIFICAND_MASK = 0x000fffff;
// EXPORTS //
module.exports = FLOAT64_HIGH_WORD_SIGNIFICAND_MASK;
},{}],248:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Natural logarithm of the square root of `2π`.
*
* @module @stdlib/constants/float64/ln-sqrt-two-pi
* @type {number}
*
* @example
* var LN_SQRT_TWO_PI = require( '@stdlib/constants/float64/ln-sqrt-two-pi' );
* // returns 0.9189385332046728
*/
// MAIN //
/**
* Natural logarithm of the square root of `2π`.
*
* ```tex
* \ln \sqrt{2\pi}
* ```
*
* @constant
* @type {number}
* @default 0.9189385332046728
*/
var LN_SQRT_TWO_PI = 9.18938533204672741780329736405617639861397473637783412817151540482765695927260397694743298635954197622005646625e-01; // eslint-disable-line max-len
// EXPORTS //
module.exports = LN_SQRT_TWO_PI;
},{}],249:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* The maximum biased base 2 exponent for a subnormal double-precision floating-point number.
*
* @module @stdlib/constants/float64/max-base2-exponent-subnormal
* @type {integer32}
*
* @example
* var FLOAT64_MAX_BASE2_EXPONENT_SUBNORMAL = require( '@stdlib/constants/float64/max-base2-exponent-subnormal' );
* // returns -1023
*/
// MAIN //
/**
* The maximum biased base 2 exponent for a subnormal double-precision floating-point number.
*
* ```text
* 00000000000 => 0 - BIAS = -1023
* ```
*
* where `BIAS = 1023`.
*
* @constant
* @type {integer32}
* @default -1023
* @see [IEEE 754]{@link https://en.wikipedia.org/wiki/IEEE_754-1985}
*/
var FLOAT64_MAX_BASE2_EXPONENT_SUBNORMAL = -1023|0; // asm type annotation
// EXPORTS //
module.exports = FLOAT64_MAX_BASE2_EXPONENT_SUBNORMAL;
},{}],250:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* The maximum biased base 2 exponent for a double-precision floating-point number.
*
* @module @stdlib/constants/float64/max-base2-exponent
* @type {integer32}
*
* @example
* var FLOAT64_MAX_BASE2_EXPONENT = require( '@stdlib/constants/float64/max-base2-exponent' );
* // returns 1023
*/
// MAIN //
/**
* The maximum biased base 2 exponent for a double-precision floating-point number.
*
* ```text
* 11111111110 => 2046 - BIAS = 1023
* ```
*
* where `BIAS = 1023`.
*
* @constant
* @type {integer32}
* @default 1023
* @see [IEEE 754]{@link https://en.wikipedia.org/wiki/IEEE_754-1985}
*/
var FLOAT64_MAX_BASE2_EXPONENT = 1023|0; // asm type annotation
// EXPORTS //
module.exports = FLOAT64_MAX_BASE2_EXPONENT;
},{}],251:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Maximum safe double-precision floating-point integer.
*
* @module @stdlib/constants/float64/max-safe-integer
* @type {number}
*
* @example
* var FLOAT64_MAX_SAFE_INTEGER = require( '@stdlib/constants/float64/max-safe-integer' );
* // returns 9007199254740991
*/
// MAIN //
/**
* Maximum safe double-precision floating-point integer.
*
* ## Notes
*
* The integer has the value
*
* ```tex
* 2^{53} - 1
* ```
*
* @constant
* @type {number}
* @default 9007199254740991
* @see [Safe Integers]{@link http://www.2ality.com/2013/10/safe-integers.html}
* @see [IEEE 754]{@link https://en.wikipedia.org/wiki/IEEE_754-1985}
*/
var FLOAT64_MAX_SAFE_INTEGER = 9007199254740991;
// EXPORTS //
module.exports = FLOAT64_MAX_SAFE_INTEGER;
},{}],252:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* The minimum biased base 2 exponent for a subnormal double-precision floating-point number.
*
* @module @stdlib/constants/float64/min-base2-exponent-subnormal
* @type {integer32}
*
* @example
* var FLOAT64_MIN_BASE2_EXPONENT_SUBNORMAL = require( '@stdlib/constants/float64/min-base2-exponent-subnormal' );
* // returns -1074
*/
// MAIN //
/**
* The minimum biased base 2 exponent for a subnormal double-precision floating-point number.
*
* ```text
* -(BIAS+(52-1)) = -(1023+51) = -1074
* ```
*
* where `BIAS = 1023` and `52` is the number of digits in the significand.
*
* @constant
* @type {integer32}
* @default -1074
* @see [IEEE 754]{@link https://en.wikipedia.org/wiki/IEEE_754-1985}
*/
var FLOAT64_MIN_BASE2_EXPONENT_SUBNORMAL = -1074|0; // asm type annotation
// EXPORTS //
module.exports = FLOAT64_MIN_BASE2_EXPONENT_SUBNORMAL;
},{}],253:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Double-precision floating-point negative infinity.
*
* @module @stdlib/constants/float64/ninf
* @type {number}
*
* @example
* var FLOAT64_NINF = require( '@stdlib/constants/float64/ninf' );
* // returns -Infinity
*/
// MODULES //
var Number = require( '@stdlib/number/ctor' );
// MAIN //
/**
* Double-precision floating-point negative infinity.
*
* ## Notes
*
* Double-precision floating-point negative infinity has the bit sequence
*
* ```binarystring
* 1 11111111111 00000000000000000000 00000000000000000000000000000000
* ```
*
* @constant
* @type {number}
* @default Number.NEGATIVE_INFINITY
* @see [IEEE 754]{@link https://en.wikipedia.org/wiki/IEEE_754-1985}
*/
var FLOAT64_NINF = Number.NEGATIVE_INFINITY;
// EXPORTS //
module.exports = FLOAT64_NINF;
},{"@stdlib/number/ctor":341}],254:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* The mathematical constant `π`.
*
* @module @stdlib/constants/float64/pi
* @type {number}
*
* @example
* var PI = require( '@stdlib/constants/float64/pi' );
* // returns 3.141592653589793
*/
// MAIN //
/**
* The mathematical constant `π`.
*
* @constant
* @type {number}
* @default 3.141592653589793
* @see [Wikipedia]{@link https://en.wikipedia.org/wiki/Pi}
*/
var PI = 3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679; // eslint-disable-line max-len
// EXPORTS //
module.exports = PI;
},{}],255:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Double-precision floating-point positive infinity.
*
* @module @stdlib/constants/float64/pinf
* @type {number}
*
* @example
* var FLOAT64_PINF = require( '@stdlib/constants/float64/pinf' );
* // returns Infinity
*/
// MAIN //
/**
* Double-precision floating-point positive infinity.
*
* ## Notes
*
* Double-precision floating-point positive infinity has the bit sequence
*
* ```binarystring
* 0 11111111111 00000000000000000000 00000000000000000000000000000000
* ```
*
* @constant
* @type {number}
* @default Number.POSITIVE_INFINITY
* @see [IEEE 754]{@link https://en.wikipedia.org/wiki/IEEE_754-1985}
*/
var FLOAT64_PINF = Number.POSITIVE_INFINITY; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = FLOAT64_PINF;
},{}],256:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Smallest positive double-precision floating-point normal number.
*
* @module @stdlib/constants/float64/smallest-normal
* @type {number}
*
* @example
* var FLOAT64_SMALLEST_NORMAL = require( '@stdlib/constants/float64/smallest-normal' );
* // returns 2.2250738585072014e-308
*/
// MAIN //
/**
* The smallest positive double-precision floating-point normal number.
*
* ## Notes
*
* The number has the value
*
* ```tex
* \frac{1}{2^{1023-1}}
* ```
*
* which corresponds to the bit sequence
*
* ```binarystring
* 0 00000000001 00000000000000000000 00000000000000000000000000000000
* ```
*
* @constant
* @type {number}
* @default 2.2250738585072014e-308
* @see [IEEE 754]{@link https://en.wikipedia.org/wiki/IEEE_754-1985}
*/
var FLOAT64_SMALLEST_NORMAL = 2.2250738585072014e-308;
// EXPORTS //
module.exports = FLOAT64_SMALLEST_NORMAL;
},{}],257:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Maximum signed 16-bit integer.
*
* @module @stdlib/constants/int16/max
* @type {integer32}
*
* @example
* var INT16_MAX = require( '@stdlib/constants/int16/max' );
* // returns 32767
*/
// MAIN //
/**
* Maximum signed 16-bit integer.
*
* ## Notes
*
* The number has the value
*
* ```tex
* 2^{15} - 1
* ```
*
* which corresponds to the bit sequence
*
* ```binarystring
* 0111111111111111
* ```
*
* @constant
* @type {integer32}
* @default 32767
*/
var INT16_MAX = 32767|0; // asm type annotation
// EXPORTS //
module.exports = INT16_MAX;
},{}],258:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Minimum signed 16-bit integer.
*
* @module @stdlib/constants/int16/min
* @type {integer32}
*
* @example
* var INT16_MIN = require( '@stdlib/constants/int16/min' );
* // returns -32768
*/
// MAIN //
/**
* Minimum signed 16-bit integer.
*
* ## Notes
*
* The number has the value
*
* ```tex
* -(2^{15})
* ```
*
* which corresponds to the two's complement bit sequence
*
* ```binarystring
* 1000000000000000
* ```
*
* @constant
* @type {integer32}
* @default -32768
*/
var INT16_MIN = -32768|0; // asm type annotation
// EXPORTS //
module.exports = INT16_MIN;
},{}],259:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Maximum signed 32-bit integer.
*
* @module @stdlib/constants/int32/max
* @type {integer32}
*
* @example
* var INT32_MAX = require( '@stdlib/constants/int32/max' );
* // returns 2147483647
*/
// MAIN //
/**
* Maximum signed 32-bit integer.
*
* ## Notes
*
* The number has the value
*
* ```tex
* 2^{31} - 1
* ```
*
* which corresponds to the bit sequence
*
* ```binarystring
* 01111111111111111111111111111111
* ```
*
* @constant
* @type {integer32}
* @default 2147483647
*/
var INT32_MAX = 2147483647|0; // asm type annotation
// EXPORTS //
module.exports = INT32_MAX;
},{}],260:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Minimum signed 32-bit integer.
*
* @module @stdlib/constants/int32/min
* @type {integer32}
*
* @example
* var INT32_MIN = require( '@stdlib/constants/int32/min' );
* // returns -2147483648
*/
// MAIN //
/**
* Minimum signed 32-bit integer.
*
* ## Notes
*
* The number has the value
*
* ```tex
* -(2^{31})
* ```
*
* which corresponds to the two's complement bit sequence
*
* ```binarystring
* 10000000000000000000000000000000
* ```
*
* @constant
* @type {integer32}
* @default -2147483648
*/
var INT32_MIN = -2147483648|0; // asm type annotation
// EXPORTS //
module.exports = INT32_MIN;
},{}],261:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Maximum signed 8-bit integer.
*
* @module @stdlib/constants/int8/max
* @type {integer32}
*
* @example
* var INT8_MAX = require( '@stdlib/constants/int8/max' );
* // returns 127
*/
// MAIN //
/**
* Maximum signed 8-bit integer.
*
* ## Notes
*
* The number is given by
*
* ```tex
* 2^{7} - 1
* ```
*
* which corresponds to the bit sequence
*
* ```binarystring
* 01111111
* ```
*
* @constant
* @type {integer32}
* @default 127
*/
var INT8_MAX = 127|0; // asm type annotation
// EXPORTS //
module.exports = INT8_MAX;
},{}],262:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Minimum signed 8-bit integer.
*
* @module @stdlib/constants/int8/min
* @type {integer32}
*
* @example
* var INT8_MIN = require( '@stdlib/constants/int8/min' );
* // returns -128
*/
// MAIN //
/**
* Minimum signed 8-bit integer.
*
* ## Notes
*
* The number is given by
*
* ```tex
* -(2^{7})
* ```
*
* which corresponds to the two's complement bit sequence
*
* ```binarystring
* 10000000
* ```
*
* @constant
* @type {integer32}
* @default -128
*/
var INT8_MIN = -128|0; // asm type annotation
// EXPORTS //
module.exports = INT8_MIN;
},{}],263:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Maximum unsigned 16-bit integer.
*
* @module @stdlib/constants/uint16/max
* @type {integer32}
*
* @example
* var UINT16_MAX = require( '@stdlib/constants/uint16/max' );
* // returns 65535
*/
// MAIN //
/**
* Maximum unsigned 16-bit integer.
*
* ## Notes
*
* The number has the value
*
* ```tex
* 2^{16} - 1
* ```
*
* which corresponds to the bit sequence
*
* ```binarystring
* 1111111111111111
* ```
*
* @constant
* @type {integer32}
* @default 65535
*/
var UINT16_MAX = 65535|0; // asm type annotation
// EXPORTS //
module.exports = UINT16_MAX;
},{}],264:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Maximum unsigned 32-bit integer.
*
* @module @stdlib/constants/uint32/max
* @type {uinteger32}
*
* @example
* var UINT32_MAX = require( '@stdlib/constants/uint32/max' );
* // returns 4294967295
*/
// MAIN //
/**
* Maximum unsigned 32-bit integer.
*
* ## Notes
*
* The number has the value
*
* ```tex
* 2^{32} - 1
* ```
*
* which corresponds to the bit sequence
*
* ```binarystring
* 11111111111111111111111111111111
* ```
*
* @constant
* @type {uinteger32}
* @default 4294967295
*/
var UINT32_MAX = 4294967295;
// EXPORTS //
module.exports = UINT32_MAX;
},{}],265:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Maximum unsigned 8-bit integer.
*
* @module @stdlib/constants/uint8/max
* @type {integer32}
*
* @example
* var UINT8_MAX = require( '@stdlib/constants/uint8/max' );
* // returns 255
*/
// MAIN //
/**
* Maximum unsigned 8-bit integer.
*
* ## Notes
*
* The number has the value
*
* ```tex
* 2^{8} - 1
* ```
*
* which corresponds to the bit sequence
*
* ```binarystring
* 11111111
* ```
*
* @constant
* @type {integer32}
* @default 255
*/
var UINT8_MAX = 255|0; // asm type annotation
// EXPORTS //
module.exports = UINT8_MAX;
},{}],266:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Maximum Unicode code point in the Basic Multilingual Plane (BMP).
*
* @module @stdlib/constants/unicode/max-bmp
* @type {integer32}
*
* @example
* var UNICODE_MAX_BMP = require( '@stdlib/constants/unicode/max-bmp' );
* // returns 65535
*/
// MAIN //
/**
* Maximum Unicode code point in the Basic Multilingual Plane (BMP).
*
* @constant
* @type {integer32}
* @default 65535
* @see [Unicode]{@link https://en.wikipedia.org/wiki/Unicode}
*/
var UNICODE_MAX_BMP = 0xFFFF|0; // asm type annotation
// EXPORTS //
module.exports = UNICODE_MAX_BMP;
},{}],267:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Maximum Unicode code point.
*
* @module @stdlib/constants/unicode/max
* @type {integer32}
*
* @example
* var UNICODE_MAX = require( '@stdlib/constants/unicode/max' );
* // returns 1114111
*/
// MAIN //
/**
* Maximum Unicode code point.
*
* @constant
* @type {integer32}
* @default 1114111
* @see [Unicode]{@link https://en.wikipedia.org/wiki/Unicode}
*/
var UNICODE_MAX = 0x10FFFF|0; // asm type annotation
// EXPORTS //
module.exports = UNICODE_MAX;
},{}],268:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a double-precision floating-point numeric value is infinite.
*
* @module @stdlib/math/base/assert/is-infinite
*
* @example
* var isInfinite = require( '@stdlib/math/base/assert/is-infinite' );
*
* var bool = isInfinite( Infinity );
* // returns true
*
* bool = isInfinite( -Infinity );
* // returns true
*
* bool = isInfinite( 5.0 );
* // returns false
*
* bool = isInfinite( NaN );
* // returns false
*/
// MODULES //
var isInfinite = require( './main.js' );
// EXPORTS //
module.exports = isInfinite;
},{"./main.js":269}],269:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var PINF = require( '@stdlib/constants/float64/pinf' );
var NINF = require( '@stdlib/constants/float64/ninf' );
// MAIN //
/**
* Tests if a double-precision floating-point numeric value is infinite.
*
* @param {number} x - value to test
* @returns {boolean} boolean indicating whether the value is infinite
*
* @example
* var bool = isInfinite( Infinity );
* // returns true
*
* @example
* var bool = isInfinite( -Infinity );
* // returns true
*
* @example
* var bool = isInfinite( 5.0 );
* // returns false
*
* @example
* var bool = isInfinite( NaN );
* // returns false
*/
function isInfinite( x ) {
return (x === PINF || x === NINF);
}
// EXPORTS //
module.exports = isInfinite;
},{"@stdlib/constants/float64/ninf":253,"@stdlib/constants/float64/pinf":255}],270:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a finite double-precision floating-point number is an integer.
*
* @module @stdlib/math/base/assert/is-integer
*
* @example
* var isInteger = require( '@stdlib/math/base/assert/is-integer' );
*
* var bool = isInteger( 1.0 );
* // returns true
*
* bool = isInteger( 3.14 );
* // returns false
*/
// MODULES //
var isInteger = require( './is_integer.js' );
// EXPORTS //
module.exports = isInteger;
},{"./is_integer.js":271}],271:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var floor = require( '@stdlib/math/base/special/floor' );
// MAIN //
/**
* Tests if a finite double-precision floating-point number is an integer.
*
* @param {number} x - value to test
* @returns {boolean} boolean indicating whether the value is an integer
*
* @example
* var bool = isInteger( 1.0 );
* // returns true
*
* @example
* var bool = isInteger( 3.14 );
* // returns false
*/
function isInteger( x ) {
return (floor(x) === x);
}
// EXPORTS //
module.exports = isInteger;
},{"@stdlib/math/base/special/floor":292}],272:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a double-precision floating-point numeric value is `NaN`.
*
* @module @stdlib/math/base/assert/is-nan
*
* @example
* var isnan = require( '@stdlib/math/base/assert/is-nan' );
*
* var bool = isnan( NaN );
* // returns true
*
* bool = isnan( 7.0 );
* // returns false
*/
// MODULES //
var isnan = require( './main.js' );
// EXPORTS //
module.exports = isnan;
},{"./main.js":273}],273:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Tests if a double-precision floating-point numeric value is `NaN`.
*
* @param {number} x - value to test
* @returns {boolean} boolean indicating whether the value is `NaN`
*
* @example
* var bool = isnan( NaN );
* // returns true
*
* @example
* var bool = isnan( 7.0 );
* // returns false
*/
function isnan( x ) {
return ( x !== x );
}
// EXPORTS //
module.exports = isnan;
},{}],274:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a finite double-precision floating-point number is a negative integer.
*
* @module @stdlib/math/base/assert/is-negative-integer
*
* @example
* var isNegativeInteger = require( '@stdlib/math/base/assert/is-negative-integer' );
*
* var bool = isNegativeInteger( -1.0 );
* // returns true
*
* bool = isNegativeInteger( 0.0 );
* // returns false
*
* bool = isNegativeInteger( 10.0 );
* // returns false
*/
// MODULES //
var isNegativeInteger = require( './is_negative_integer.js' );
// EXPORTS //
module.exports = isNegativeInteger;
},{"./is_negative_integer.js":275}],275:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var floor = require( '@stdlib/math/base/special/floor' );
// MAIN //
/**
* Tests if a finite double-precision floating-point number is a negative integer.
*
* @param {number} x - value to test
* @returns {boolean} boolean indicating whether the value is a negative integer
*
* @example
* var bool = isNegativeInteger( -1.0 );
* // returns true
*
* @example
* var bool = isNegativeInteger( 0.0 );
* // returns false
*
* @example
* var bool = isNegativeInteger( 10.0 );
* // returns false
*/
function isNegativeInteger( x ) {
return (floor(x) === x && x < 0.0);
}
// EXPORTS //
module.exports = isNegativeInteger;
},{"@stdlib/math/base/special/floor":292}],276:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Test if a double-precision floating-point numeric value is positive zero.
*
* @module @stdlib/math/base/assert/is-positive-zero
*
* @example
* var isPositiveZero = require( '@stdlib/math/base/assert/is-positive-zero' );
*
* var bool = isPositiveZero( 0.0 );
* // returns true
*
* bool = isPositiveZero( -0.0 );
* // returns false
*/
// MODULES //
var isPositiveZero = require( './main.js' );
// EXPORTS //
module.exports = isPositiveZero;
},{"./main.js":277}],277:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var PINF = require( '@stdlib/constants/float64/pinf' );
// MAIN //
/**
* Tests if a double-precision floating-point numeric value is positive zero.
*
* @param {number} x - value to test
* @returns {boolean} boolean indicating whether the value is positive zero
*
* @example
* var bool = isPositiveZero( 0.0 );
* // returns true
*
* @example
* var bool = isPositiveZero( -0.0 );
* // returns false
*/
function isPositiveZero( x ) {
return (x === 0.0 && 1.0/x === PINF);
}
// EXPORTS //
module.exports = isPositiveZero;
},{"@stdlib/constants/float64/pinf":255}],278:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Compute an absolute value of a double-precision floating-point number.
*
* @module @stdlib/math/base/special/abs
*
* @example
* var abs = require( '@stdlib/math/base/special/abs' );
*
* var v = abs( -1.0 );
* // returns 1.0
*
* v = abs( 2.0 );
* // returns 2.0
*
* v = abs( 0.0 );
* // returns 0.0
*
* v = abs( -0.0 );
* // returns 0.0
*
* v = abs( NaN );
* // returns NaN
*/
// MODULES //
var abs = require( './main.js' );
// EXPORTS //
module.exports = abs;
},{"./main.js":279}],279:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Computes the absolute value of a double-precision floating-point number `x`.
*
* @param {number} x - input value
* @returns {number} absolute value
*
* @example
* var v = abs( -1.0 );
* // returns 1.0
*
* @example
* var v = abs( 2.0 );
* // returns 2.0
*
* @example
* var v = abs( 0.0 );
* // returns 0.0
*
* @example
* var v = abs( -0.0 );
* // returns 0.0
*
* @example
* var v = abs( NaN );
* // returns NaN
*/
function abs( x ) {
return Math.abs( x ); // eslint-disable-line stdlib/no-builtin-math
}
// EXPORTS //
module.exports = abs;
},{}],280:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Round a double-precision floating-point number toward positive infinity.
*
* @module @stdlib/math/base/special/ceil
*
* @example
* var ceil = require( '@stdlib/math/base/special/ceil' );
*
* var v = ceil( -4.2 );
* // returns -4.0
*
* v = ceil( 9.99999 );
* // returns 10.0
*
* v = ceil( 0.0 );
* // returns 0.0
*
* v = ceil( NaN );
* // returns NaN
*/
// MODULES //
var ceil = require( './main.js' );
// EXPORTS //
module.exports = ceil;
},{"./main.js":281}],281:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// TODO: implementation (?)
/**
* Rounds a double-precision floating-point number toward positive infinity.
*
* @param {number} x - input value
* @returns {number} rounded value
*
* @example
* var v = ceil( -4.2 );
* // returns -4.0
*
* @example
* var v = ceil( 9.99999 );
* // returns 10.0
*
* @example
* var v = ceil( 0.0 );
* // returns 0.0
*
* @example
* var v = ceil( NaN );
* // returns NaN
*/
var ceil = Math.ceil; // eslint-disable-line stdlib/no-builtin-math
// EXPORTS //
module.exports = ceil;
},{}],282:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var toWords = require( '@stdlib/number/float64/base/to-words' );
var getHighWord = require( '@stdlib/number/float64/base/get-high-word' );
var fromWords = require( '@stdlib/number/float64/base/from-words' );
// VARIABLES //
// 10000000000000000000000000000000 => 2147483648 => 0x80000000
var SIGN_MASK = 0x80000000>>>0; // asm type annotation
// 01111111111111111111111111111111 => 2147483647 => 0x7fffffff
var MAGNITUDE_MASK = 0x7fffffff|0; // asm type annotation
// High/low words workspace:
var WORDS = [ 0, 0 ]; // WARNING: not thread safe
// MAIN //
/**
* Returns a double-precision floating-point number with the magnitude of `x` and the sign of `y`.
*
* @param {number} x - number from which to derive a magnitude
* @param {number} y - number from which to derive a sign
* @returns {number} a double-precision floating-point number
*
* @example
* var z = copysign( -3.14, 10.0 );
* // returns 3.14
*
* @example
* var z = copysign( 3.14, -1.0 );
* // returns -3.14
*
* @example
* var z = copysign( 1.0, -0.0 );
* // returns -1.0
*
* @example
* var z = copysign( -3.14, -0.0 );
* // returns -3.14
*
* @example
* var z = copysign( -0.0, 1.0 );
* // returns 0.0
*/
function copysign( x, y ) {
var hx;
var hy;
// Split `x` into higher and lower order words:
toWords( WORDS, x );
hx = WORDS[ 0 ];
// Turn off the sign bit of `x`:
hx &= MAGNITUDE_MASK;
// Extract the higher order word from `y`:
hy = getHighWord( y );
// Leave only the sign bit of `y` turned on:
hy &= SIGN_MASK;
// Copy the sign bit of `y` to `x`:
hx |= hy;
// Return a new value having the same magnitude as `x`, but with the sign of `y`:
return fromWords( hx, WORDS[ 1 ] );
}
// EXPORTS //
module.exports = copysign;
},{"@stdlib/number/float64/base/from-words":345,"@stdlib/number/float64/base/get-high-word":349,"@stdlib/number/float64/base/to-words":360}],283:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Return a double-precision floating-point number with the magnitude of `x` and the sign of `y`.
*
* @module @stdlib/math/base/special/copysign
*
* @example
* var copysign = require( '@stdlib/math/base/special/copysign' );
*
* var z = copysign( -3.14, 10.0 );
* // returns 3.14
*
* z = copysign( 3.14, -1.0 );
* // returns -3.14
*
* z = copysign( 1.0, -0.0 );
* // returns -1.0
*
* z = copysign( -3.14, -0.0 );
* // returns -3.14
*
* z = copysign( -0.0, 1.0 );
* // returns 0.0
*/
// MODULES //
var copysign = require( './copysign.js' );
// EXPORTS //
module.exports = copysign;
},{"./copysign.js":282}],284:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*
*
* ## Notice
*
* The following copyright, license, and long comment were part of the original implementation available as part of [FreeBSD]{@link https://svnweb.freebsd.org/base/release/9.3.0/lib/msun/src/s_cos.c}. The implementation follows the original, but has been modified for JavaScript.
*
* ```text
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunPro, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ```
*/
'use strict';
// MODULES //
var getHighWord = require( '@stdlib/number/float64/base/get-high-word' );
var kernelCos = require( '@stdlib/math/base/special/kernel-cos' );
var kernelSin = require( '@stdlib/math/base/special/kernel-sin' );
var rempio2 = require( '@stdlib/math/base/special/rempio2' );
// VARIABLES //
// Scratch array for storing temporary values:
var buffer = [ 0.0, 0.0 ]; // WARNING: not thread safe
// High word absolute value mask: 0x7fffffff => 01111111111111111111111111111111
var HIGH_WORD_ABS_MASK = 0x7fffffff|0; // asm type annotation
// High word of π/4: 0x3fe921fb => 00111111111010010010000111111011
var HIGH_WORD_PIO4 = 0x3fe921fb|0; // asm type annotation
// High word of 2^-27: 0x3e400000 => 00111110010000000000000000000000
var HIGH_WORD_TWO_NEG_27 = 0x3e400000|0; // asm type annotation
// High word exponent mask: 0x7ff00000 => 01111111111100000000000000000000
var HIGH_WORD_EXPONENT_MASK = 0x7ff00000|0; // asm type annotation
// MAIN //
/**
* Computes the cosine of a number.
*
* @param {number} x - input value (in radians)
* @returns {number} cosine
*
* @example
* var v = cos( 0.0 );
* // returns 1.0
*
* @example
* var v = cos( 3.141592653589793/4.0 );
* // returns ~0.707
*
* @example
* var v = cos( -3.141592653589793/6.0 );
* // returns ~0.866
*
* @example
* var v = cos( NaN );
* // returns NaN
*/
function cos( x ) {
var ix;
var n;
ix = getHighWord( x );
ix &= HIGH_WORD_ABS_MASK;
// Case: |x| ~< pi/4
if ( ix <= HIGH_WORD_PIO4 ) {
// Case: x < 2**-27
if ( ix < HIGH_WORD_TWO_NEG_27 ) {
return 1.0;
}
return kernelCos( x, 0.0 );
}
// Case: cos(Inf or NaN) is NaN */
if ( ix >= HIGH_WORD_EXPONENT_MASK ) {
return NaN;
}
// Case: Argument reduction needed...
n = rempio2( x, buffer );
switch ( n & 3 ) {
case 0:
return kernelCos( buffer[ 0 ], buffer[ 1 ] );
case 1:
return -kernelSin( buffer[ 0 ], buffer[ 1 ] );
case 2:
return -kernelCos( buffer[ 0 ], buffer[ 1 ] );
default:
return kernelSin( buffer[ 0 ], buffer[ 1 ] );
}
}
// EXPORTS //
module.exports = cos;
},{"@stdlib/math/base/special/kernel-cos":306,"@stdlib/math/base/special/kernel-sin":310,"@stdlib/math/base/special/rempio2":323,"@stdlib/number/float64/base/get-high-word":349}],285:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Compute the cosine of a number.
*
* @module @stdlib/math/base/special/cos
*
* @example
* var cos = require( '@stdlib/math/base/special/cos' );
*
* var v = cos( 0.0 );
* // returns 1.0
*
* v = cos( 3.141592653589793/4.0 );
* // returns ~0.707
*
* v = cos( -3.141592653589793/6.0 );
* // returns ~0.866
*/
// MODULES //
var cos = require( './cos.js' );
// EXPORTS //
module.exports = cos;
},{"./cos.js":284}],286:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*
*
* ## Notice
*
* The following copyright, license, and long comment were part of the original implementation available as part of [FreeBSD]{@link https://svnweb.freebsd.org/base/release/9.3.0/lib/msun/src/e_exp.c}. The implementation follows the original, but has been modified for JavaScript.
*
* ```text
* Copyright (C) 2004 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunPro, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ```
*/
'use strict';
// MODULES //
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var trunc = require( '@stdlib/math/base/special/trunc' );
var NINF = require( '@stdlib/constants/float64/ninf' );
var PINF = require( '@stdlib/constants/float64/pinf' );
var expmulti = require( './expmulti.js' );
// VARIABLES //
var LN2_HI = 6.93147180369123816490e-01;
var LN2_LO = 1.90821492927058770002e-10;
var LOG2_E = 1.44269504088896338700e+00;
var OVERFLOW = 7.09782712893383973096e+02;
var UNDERFLOW = -7.45133219101941108420e+02;
var NEARZERO = 1.0 / (1 << 28); // 2^-28;
var NEG_NEARZERO = -NEARZERO;
// MAIN //
/**
* Evaluates the natural exponential function.
*
* ## Method
*
* 1. We reduce \\( x \\) to an \\( r \\) so that \\( |r| \leq 0.5 \cdot \ln(2) \approx 0.34658 \\). Given \\( x \\), we find an \\( r \\) and integer \\( k \\) such that
*
* ```tex
* \begin{align*}
* x &= k \cdot \ln(2) + r \\
* |r| &\leq 0.5 \cdot \ln(2)
* \end{align*}
* ```
*
* <!-- <note> -->
*
* \\( r \\) can be represented as \\( r = \mathrm{hi} - \mathrm{lo} \\) for better accuracy.
*
* <!-- </note> -->
*
* 2. We approximate of \\( e^{r} \\) by a special rational function on the interval \\(\[0,0.34658]\\):
*
* ```tex
* \begin{align*}
* R\left(r^2\right) &= r \cdot \frac{ e^{r}+1 }{ e^{r}-1 } \\
* &= 2 + \frac{r^2}{6} - \frac{r^4}{360} + \ldots
* \end{align*}
* ```
*
* We use a special Remes algorithm on \\(\[0,0.34658]\\) to generate a polynomial of degree \\(5\\) to approximate \\(R\\). The maximum error of this polynomial approximation is bounded by \\(2^{-59}\\). In other words,
*
* ```tex
* R(z) \sim 2 + P_1 z + P_2 z^2 + P_3 z^3 + P_4 z^4 + P_5 z^5
* ```
*
* where \\( z = r^2 \\) and
*
* ```tex
* \left| 2 + P_1 z + \ldots + P_5 z^5 - R(z) \right| \leq 2^{-59}
* ```
*
* <!-- <note> -->
*
* The values of \\( P_1 \\) to \\( P_5 \\) are listed in the source code.
*
* <!-- </note> -->
*
* The computation of \\( e^{r} \\) thus becomes
*
* ```tex
* \begin{align*}
* e^{r} &= 1 + \frac{2r}{R-r} \\
* &= 1 + r + \frac{r \cdot R_1(r)}{2 - R_1(r)}\ \text{for better accuracy}
* \end{align*}
* ```
*
* where
*
* ```tex
* R_1(r) = r - P_1\ r^2 + P_2\ r^4 + \ldots + P_5\ r^{10}
* ```
*
* 3. We scale back to obtain \\( e^{x} \\). From step 1, we have
*
* ```tex
* e^{x} = 2^k e^{r}
* ```
*
*
* ## Special Cases
*
* ```tex
* \begin{align*}
* e^\infty &= \infty \\
* e^{-\infty} &= 0 \\
* e^{\mathrm{NaN}} &= \mathrm{NaN} \\
* e^0 &= 1\ \mathrm{is\ exact\ for\ finite\ argument\ only}
* \end{align*}
* ```
*
* ## Notes
*
* - According to an error analysis, the error is always less than \\(1\\) ulp (unit in the last place).
*
* - For an IEEE double,
*
* - if \\(x > 7.09782712893383973096\mbox{e+}02\\), then \\(e^{x}\\) overflows
* - if \\(x < -7.45133219101941108420\mbox{e+}02\\), then \\(e^{x}\\) underflows
*
* - The hexadecimal values included in the source code are the intended ones for the used constants. Decimal values may be used, provided that the compiler will convert from decimal to binary accurately enough to produce the intended hexadecimal values.
*
*
* @param {number} x - input value
* @returns {number} function value
*
* @example
* var v = exp( 4.0 );
* // returns ~54.5982
*
* @example
* var v = exp( -9.0 );
* // returns ~1.234e-4
*
* @example
* var v = exp( 0.0 );
* // returns 1.0
*
* @example
* var v = exp( NaN );
* // returns NaN
*/
function exp( x ) {
var hi;
var lo;
var k;
if ( isnan( x ) || x === PINF ) {
return x;
}
if ( x === NINF ) {
return 0.0;
}
if ( x > OVERFLOW ) {
return PINF;
}
if ( x < UNDERFLOW ) {
return 0.0;
}
if (
x > NEG_NEARZERO &&
x < NEARZERO
) {
return 1.0 + x;
}
// Reduce and compute `r = hi - lo` for extra precision.
if ( x < 0.0 ) {
k = trunc( (LOG2_E*x) - 0.5 );
} else {
k = trunc( (LOG2_E*x) + 0.5 );
}
hi = x - (k*LN2_HI);
lo = k * LN2_LO;
return expmulti( hi, lo, k );
}
// EXPORTS //
module.exports = exp;
},{"./expmulti.js":287,"@stdlib/constants/float64/ninf":253,"@stdlib/constants/float64/pinf":255,"@stdlib/math/base/assert/is-nan":272,"@stdlib/math/base/special/trunc":337}],287:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*
*
* ## Notice
*
* The following copyright, license, and long comment were part of the original implementation available as part of [FreeBSD]{@link https://svnweb.freebsd.org/base/release/9.3.0/lib/msun/src/e_exp.c}. The implementation follows the original, but has been modified for JavaScript.
*
* ```text
* Copyright (C) 2004 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunPro, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ```
*/
'use strict';
// MODULES //
var ldexp = require( '@stdlib/math/base/special/ldexp' );
var polyvalP = require( './polyval_p.js' );
// MAIN //
/**
* Computes \\(e^{r} 2^k\\) where \\(r = \mathrm{hi} - \mathrm{lo}\\) and \\(|r| \leq \ln(2)/2\\).
*
* @private
* @param {number} hi - upper bound
* @param {number} lo - lower bound
* @param {integer} k - power of 2
* @returns {number} function value
*/
function expmulti( hi, lo, k ) {
var r;
var t;
var c;
var y;
r = hi - lo;
t = r * r;
c = r - ( t*polyvalP( t ) );
y = 1.0 - ( lo - ( (r*c)/(2.0-c) ) - hi);
return ldexp( y, k );
}
// EXPORTS //
module.exports = expmulti;
},{"./polyval_p.js":289,"@stdlib/math/base/special/ldexp":312}],288:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Evaluate the natural exponential function.
*
* @module @stdlib/math/base/special/exp
*
* @example
* var exp = require( '@stdlib/math/base/special/exp' );
*
* var v = exp( 4.0 );
* // returns ~54.5982
*
* v = exp( -9.0 );
* // returns ~1.234e-4
*
* v = exp( 0.0 );
* // returns 1.0
*
* v = exp( NaN );
* // returns NaN
*/
// MODULES //
var exp = require( './exp.js' );
// EXPORTS //
module.exports = exp;
},{"./exp.js":286}],289:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
/* This is a generated file. Do not edit directly. */
'use strict';
// MAIN //
/**
* Evaluates a polynomial.
*
* ## Notes
*
* - The implementation uses [Horner's rule][horners-method] for efficient computation.
*
* [horners-method]: https://en.wikipedia.org/wiki/Horner%27s_method
*
*
* @private
* @param {number} x - value at which to evaluate the polynomial
* @returns {number} evaluated polynomial
*/
function evalpoly( x ) {
if ( x === 0.0 ) {
return 0.16666666666666602;
}
return 0.16666666666666602 + (x * (-0.0027777777777015593 + (x * (0.00006613756321437934 + (x * (-0.0000016533902205465252 + (x * 4.1381367970572385e-8))))))); // eslint-disable-line max-len
}
// EXPORTS //
module.exports = evalpoly;
},{}],290:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isNegativeInteger = require( '@stdlib/math/base/assert/is-negative-integer' );
var gammaln = require( '@stdlib/math/base/special/gammaln' );
// MAIN //
/**
* Evaluates the natural logarithm of the factorial of `x`.
*
* @param {number} x - input value
* @returns {number} natural logarithm of factorial of `x`
*
* @example
* var v = factorialln( 3.0 );
* // returns ~1.792
*
* @example
* var v = factorialln( 2.4 );
* // returns ~1.092
*
* @example
* var v = factorialln( -1.0 );
* // returns NaN
*
* @example
* var v = factorialln( -1.5 );
* // returns ~1.266
*
* @example
* var v = factorialln( NaN );
* // returns NaN
*/
function factorialln( x ) {
if ( isNegativeInteger( x ) ) {
return NaN;
}
return gammaln( x + 1.0 );
}
// EXPORTS //
module.exports = factorialln;
},{"@stdlib/math/base/assert/is-negative-integer":274,"@stdlib/math/base/special/gammaln":295}],291:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Evaluate the natural logarithm of the factorial function.
*
* @module @stdlib/math/base/special/factorialln
*
* @example
* var factorialln = require( '@stdlib/math/base/special/factorialln' );
*
* var v = factorialln( 3.0 );
* // returns ~1.792
*
* v = factorialln( 2.4 );
* // returns ~1.092
*
* v = factorialln( -1.0 );
* // returns NaN
*
* v = factorialln( -1.5 );
* // returns ~1.266
*
* v = factorialln( NaN );
* // returns NaN
*/
// MODULES //
var factorialln = require( './factorialln.js' );
// EXPORTS //
module.exports = factorialln;
},{"./factorialln.js":290}],292:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Round a double-precision floating-point number toward negative infinity.
*
* @module @stdlib/math/base/special/floor
*
* @example
* var floor = require( '@stdlib/math/base/special/floor' );
*
* var v = floor( -4.2 );
* // returns -5.0
*
* v = floor( 9.99999 );
* // returns 9.0
*
* v = floor( 0.0 );
* // returns 0.0
*
* v = floor( NaN );
* // returns NaN
*/
// MODULES //
var floor = require( './main.js' );
// EXPORTS //
module.exports = floor;
},{"./main.js":293}],293:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// TODO: implementation (?)
/**
* Rounds a double-precision floating-point number toward negative infinity.
*
* @param {number} x - input value
* @returns {number} rounded value
*
* @example
* var v = floor( -4.2 );
* // returns -5.0
*
* @example
* var v = floor( 9.99999 );
* // returns 9.0
*
* @example
* var v = floor( 0.0 );
* // returns 0.0
*
* @example
* var v = floor( NaN );
* // returns NaN
*/
var floor = Math.floor; // eslint-disable-line stdlib/no-builtin-math
// EXPORTS //
module.exports = floor;
},{}],294:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*
*
* ## Notice
*
* The following copyright, license, and long comment were part of the original implementation available as part of [FreeBSD]{@link https://svnweb.freebsd.org/base/release/9.3.0/lib/msun/src/e_lgamma_r.c}. The implementation follows the original, but has been modified for JavaScript.
*
* ```text
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunPro, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ```
*/
'use strict';
// MODULES //
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var isInfinite = require( '@stdlib/math/base/assert/is-infinite' );
var abs = require( '@stdlib/math/base/special/abs' );
var ln = require( '@stdlib/math/base/special/ln' );
var trunc = require( '@stdlib/math/base/special/trunc' );
var sinpi = require( '@stdlib/math/base/special/sinpi' );
var PI = require( '@stdlib/constants/float64/pi' );
var PINF = require( '@stdlib/constants/float64/pinf' );
var polyvalA1 = require( './polyval_a1.js' );
var polyvalA2 = require( './polyval_a2.js' );
var polyvalR = require( './polyval_r.js' );
var polyvalS = require( './polyval_s.js' );
var polyvalT1 = require( './polyval_t1.js' );
var polyvalT2 = require( './polyval_t2.js' );
var polyvalT3 = require( './polyval_t3.js' );
var polyvalU = require( './polyval_u.js' );
var polyvalV = require( './polyval_v.js' );
var polyvalW = require( './polyval_w.js' );
// VARIABLES //
var A1C = 7.72156649015328655494e-02; // 0x3FB3C467E37DB0C8
var A2C = 3.22467033424113591611e-01; // 0x3FD4A34CC4A60FAD
var RC = 1.0;
var SC = -7.72156649015328655494e-02; // 0xBFB3C467E37DB0C8
var T1C = 4.83836122723810047042e-01; // 0x3FDEF72BC8EE38A2
var T2C = -1.47587722994593911752e-01; // 0xBFC2E4278DC6C509
var T3C = 6.46249402391333854778e-02; // 0x3FB08B4294D5419B
var UC = -7.72156649015328655494e-02; // 0xBFB3C467E37DB0C8
var VC = 1.0;
var WC = 4.18938533204672725052e-01; // 0x3FDACFE390C97D69
var YMIN = 1.461632144968362245;
var TWO52 = 4503599627370496; // 2**52
var TWO58 = 288230376151711744; // 2**58
var TINY = 8.470329472543003e-22;
var TC = 1.46163214496836224576e+00; // 0x3FF762D86356BE3F
var TF = -1.21486290535849611461e-01; // 0xBFBF19B9BCC38A42
var TT = -3.63867699703950536541e-18; // 0xBC50C7CAA48A971F => TT = -(tail of TF)
// MAIN //
/**
* Evaluates the natural logarithm of the gamma function.
*
* ## Method
*
* 1. Argument reduction for \\(0 < x \leq 8\\). Since \\(\Gamma(1+s) = s \Gamma(s)\\), for \\(x \in \[0,8]\\), we may reduce \\(x\\) to a number in \\(\[1.5,2.5]\\) by
*
* ```tex
* \operatorname{lgamma}(1+s) = \ln(s) + \operatorname{lgamma}(s)
* ```
*
* For example,
*
* ```tex
* \begin{align*}
* \operatorname{lgamma}(7.3) &= \ln(6.3) + \operatorname{lgamma}(6.3) \\
* &= \ln(6.3 \cdot 5.3) + \operatorname{lgamma}(5.3) \\
* &= \ln(6.3 \cdot 5.3 \cdot 4.3 \cdot 3.3 \cdot2.3) + \operatorname{lgamma}(2.3)
* \end{align*}
* ```
*
* 2. Compute a polynomial approximation of \\(\mathrm{lgamma}\\) around its minimum (\\(\mathrm{ymin} = 1.461632144968362245\\)) to maintain monotonicity. On the interval \\(\[\mathrm{ymin} - 0.23, \mathrm{ymin} + 0.27]\\) (i.e., \\(\[1.23164,1.73163]\\)), we let \\(z = x - \mathrm{ymin}\\) and use
*
* ```tex
* \operatorname{lgamma}(x) = -1.214862905358496078218 + z^2 \cdot \operatorname{poly}(z)
* ```
*
* where \\(\operatorname{poly}(z)\\) is a \\(14\\) degree polynomial.
*
* 3. Compute a rational approximation in the primary interval \\(\[2,3]\\). Let \\( s = x - 2.0 \\). We can thus use the approximation
*
* ```tex
* \operatorname{lgamma}(x) = \frac{s}{2} + s\frac{\operatorname{P}(s)}{\operatorname{Q}(s)}
* ```
*
* with accuracy
*
* ```tex
* \biggl|\frac{\mathrm{P}}{\mathrm{Q}} - \biggr(\operatorname{lgamma}(x)-\frac{s}{2}\biggl)\biggl| < 2^{-61.71}
* ```
*
* The algorithms are based on the observation
*
* ```tex
* \operatorname{lgamma}(2+s) = s(1 - \gamma) + \frac{\zeta(2) - 1}{2} s^2 - \frac{\zeta(3) - 1}{3} s^3 + \ldots
* ```
*
* where \\(\zeta\\) is the zeta function and \\(\gamma = 0.5772156649...\\) is the Euler-Mascheroni constant, which is very close to \\(0.5\\).
*
* 4. For \\(x \geq 8\\),
*
* ```tex
* \operatorname{lgamma}(x) \approx \biggl(x-\frac{1}{2}\biggr) \ln(x) - x + \frac{\ln(2\pi)}{2} + \frac{1}{12x} - \frac{1}{360x^3} + \ldots
* ```
*
* which can be expressed
*
* ```tex
* \operatorname{lgamma}(x) \approx \biggl(x-\frac{1}{2}\biggr)(\ln(x)-1)-\frac{\ln(2\pi)-1}{2} + \ldots
* ```
*
* Let \\(z = \frac{1}{x}\\). We can then use the approximation
*
* ```tex
* f(z) = \operatorname{lgamma}(x) - \biggl(x-\frac{1}{2}\biggr)(\ln(x)-1)
* ```
*
* by
*
* ```tex
* w = w_0 + w_1 z + w_2 z^3 + w_3 z^5 + \ldots + w_6 z^{11}
* ```
*
* where
*
* ```tex
* |w - f(z)| < 2^{-58.74}
* ```
*
* 5. For negative \\(x\\), since
*
* ```tex
* -x \Gamma(-x) \Gamma(x) = \frac{\pi}{\sin(\pi x)}
* ```
*
* where \\(\Gamma\\) is the gamma function, we have
*
* ```tex
* \Gamma(x) = \frac{\pi}{\sin(\pi x)(-x)\Gamma(-x)}
* ```
*
* Since \\(\Gamma(-x)\\) is positive,
*
* ```tex
* \operatorname{sign}(\Gamma(x)) = \operatorname{sign}(\sin(\pi x))
* ```
*
* for \\(x < 0\\). Hence, for \\(x < 0\\),
*
* ```tex
* \mathrm{signgam} = \operatorname{sign}(\sin(\pi x))
* ```
*
* and
*
* ```tex
* \begin{align*}
* \operatorname{lgamma}(x) &= \ln(|\Gamma(x)|) \\
* &= \ln\biggl(\frac{\pi}{|x \sin(\pi x)|}\biggr) - \operatorname{lgamma}(-x)
* \end{align*}
* ```
*
* <!-- <note> -->
*
* Note that one should avoid computing \\(\pi (-x)\\) directly in the computation of \\(\sin(\pi (-x))\\).
*
* <!-- </note> -->
*
*
* ## Special Cases
*
* ```tex
* \begin{align*}
* \operatorname{lgamma}(2+s) &\approx s (1-\gamma) & \mathrm{for\ tiny\ s} \\
* \operatorname{lgamma}(x) &\approx -\ln(x) & \mathrm{for\ tiny\ x} \\
* \operatorname{lgamma}(1) &= 0 & \\
* \operatorname{lgamma}(2) &= 0 & \\
* \operatorname{lgamma}(0) &= \infty & \\
* \operatorname{lgamma}(\infty) &= \infty & \\
* \operatorname{lgamma}(-\mathrm{integer}) &= \pm \infty
* \end{align*}
* ```
*
*
* @param {number} x - input value
* @returns {number} function value
*
* @example
* var v = gammaln( 1.0 );
* // returns 0.0
*
* @example
* var v = gammaln( 2.0 );
* // returns 0.0
*
* @example
* var v = gammaln( 4.0 );
* // returns ~1.792
*
* @example
* var v = gammaln( -0.5 );
* // returns ~1.266
*
* @example
* var v = gammaln( 0.5 );
* // returns ~0.572
*
* @example
* var v = gammaln( 0.0 );
* // returns Infinity
*
* @example
* var v = gammaln( NaN );
* // returns NaN
*/
function gammaln( x ) {
var isNegative;
var nadj;
var flg;
var p3;
var p2;
var p1;
var p;
var q;
var t;
var w;
var y;
var z;
var r;
// Special cases: NaN, +-infinity
if ( isnan( x ) || isInfinite( x ) ) {
return x;
}
// Special case: 0
if ( x === 0.0 ) {
return PINF;
}
if ( x < 0.0 ) {
isNegative = true;
x = -x;
} else {
isNegative = false;
}
// If |x| < 2**-70, return -ln(|x|)
if ( x < TINY ) {
return -ln( x );
}
if ( isNegative ) {
// If |x| >= 2**52, must be -integer
if ( x >= TWO52 ) {
return PINF;
}
t = sinpi( x );
if ( t === 0.0 ) {
return PINF;
}
nadj = ln( PI / abs( t*x ) );
}
// If x equals 1 or 2, return 0
if ( x === 1.0 || x === 2.0 ) {
return 0.0;
}
// If x < 2, use lgamma(x) = lgamma(x+1) - log(x)
if ( x < 2.0 ) {
if ( x <= 0.9 ) {
r = -ln( x );
// 0.7316 <= x <= 0.9
if ( x >= ( YMIN - 1.0 + 0.27 ) ) {
y = 1.0 - x;
flg = 0;
}
// 0.2316 <= x < 0.7316
else if ( x >= (YMIN - 1.0 - 0.27) ) {
y = x - (TC - 1.0);
flg = 1;
}
// 0 < x < 0.2316
else {
y = x;
flg = 2;
}
} else {
r = 0.0;
// 1.7316 <= x < 2
if ( x >= (YMIN + 0.27) ) {
y = 2.0 - x;
flg = 0;
}
// 1.2316 <= x < 1.7316
else if ( x >= (YMIN - 0.27) ) {
y = x - TC;
flg = 1;
}
// 0.9 < x < 1.2316
else {
y = x - 1.0;
flg = 2;
}
}
switch ( flg ) { // eslint-disable-line default-case
case 0:
z = y * y;
p1 = A1C + (z*polyvalA1( z ));
p2 = z * (A2C + (z*polyvalA2( z )));
p = (y*p1) + p2;
r += ( p - (0.5*y) );
break;
case 1:
z = y * y;
w = z * y;
p1 = T1C + (w*polyvalT1( w ));
p2 = T2C + (w*polyvalT2( w ));
p3 = T3C + (w*polyvalT3( w ));
p = (z*p1) - (TT - (w*(p2+(y*p3))));
r += ( TF + p );
break;
case 2:
p1 = y * (UC + (y*polyvalU( y )));
p2 = VC + (y*polyvalV( y ));
r += (-0.5*y) + (p1/p2);
break;
}
}
// 2 <= x < 8
else if ( x < 8.0 ) {
flg = trunc( x );
y = x - flg;
p = y * (SC + (y*polyvalS( y )));
q = RC + (y*polyvalR( y ));
r = (0.5*y) + (p/q);
z = 1.0; // gammaln(1+s) = ln(s) + gammaln(s)
switch ( flg ) { // eslint-disable-line default-case
case 7:
z *= y + 6.0;
/* falls through */
case 6:
z *= y + 5.0;
/* falls through */
case 5:
z *= y + 4.0;
/* falls through */
case 4:
z *= y + 3.0;
/* falls through */
case 3:
z *= y + 2.0;
r += ln( z );
}
}
// 8 <= x < 2**58
else if ( x < TWO58 ) {
t = ln( x );
z = 1.0 / x;
y = z * z;
w = WC + (z*polyvalW( y ));
r = ((x-0.5)*(t-1.0)) + w;
}
// 2**58 <= x <= Inf
else {
r = x * ( ln(x)-1.0 );
}
if ( isNegative ) {
r = nadj - r;
}
return r;
}
// EXPORTS //
module.exports = gammaln;
},{"./polyval_a1.js":296,"./polyval_a2.js":297,"./polyval_r.js":298,"./polyval_s.js":299,"./polyval_t1.js":300,"./polyval_t2.js":301,"./polyval_t3.js":302,"./polyval_u.js":303,"./polyval_v.js":304,"./polyval_w.js":305,"@stdlib/constants/float64/pi":254,"@stdlib/constants/float64/pinf":255,"@stdlib/math/base/assert/is-infinite":268,"@stdlib/math/base/assert/is-nan":272,"@stdlib/math/base/special/abs":278,"@stdlib/math/base/special/ln":314,"@stdlib/math/base/special/sinpi":333,"@stdlib/math/base/special/trunc":337}],295:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Evaluate the natural logarithm of the gamma function.
*
* @module @stdlib/math/base/special/gammaln
*
* @example
* var gammaln = require( '@stdlib/math/base/special/gammaln' );
*
* var v = gammaln( 1.0 );
* // returns 0.0
*
* v = gammaln( 2.0 );
* // returns 0.0
*
* v = gammaln( 4.0 );
* // returns ~1.792
*
* v = gammaln( -0.5 );
* // returns ~1.266
*
* v = gammaln( 0.5 );
* // returns ~0.572
*
* v = gammaln( 0.0 );
* // returns Infinity
*
* v = gammaln( NaN );
* // returns NaN
*/
// MODULES //
var gammaln = require( './gammaln.js' );
// EXPORTS //
module.exports = gammaln;
},{"./gammaln.js":294}],296:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
/* This is a generated file. Do not edit directly. */
'use strict';
// MAIN //
/**
* Evaluates a polynomial.
*
* ## Notes
*
* - The implementation uses [Horner's rule][horners-method] for efficient computation.
*
* [horners-method]: https://en.wikipedia.org/wiki/Horner%27s_method
*
*
* @private
* @param {number} x - value at which to evaluate the polynomial
* @returns {number} evaluated polynomial
*/
function evalpoly( x ) {
if ( x === 0.0 ) {
return 0.06735230105312927;
}
return 0.06735230105312927 + (x * (0.007385550860814029 + (x * (0.0011927076318336207 + (x * (0.00022086279071390839 + (x * 0.000025214456545125733))))))); // eslint-disable-line max-len
}
// EXPORTS //
module.exports = evalpoly;
},{}],297:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
/* This is a generated file. Do not edit directly. */
'use strict';
// MAIN //
/**
* Evaluates a polynomial.
*
* ## Notes
*
* - The implementation uses [Horner's rule][horners-method] for efficient computation.
*
* [horners-method]: https://en.wikipedia.org/wiki/Horner%27s_method
*
*
* @private
* @param {number} x - value at which to evaluate the polynomial
* @returns {number} evaluated polynomial
*/
function evalpoly( x ) {
if ( x === 0.0 ) {
return 0.020580808432516733;
}
return 0.020580808432516733 + (x * (0.0028905138367341563 + (x * (0.0005100697921535113 + (x * (0.00010801156724758394 + (x * 0.000044864094961891516))))))); // eslint-disable-line max-len
}
// EXPORTS //
module.exports = evalpoly;
},{}],298:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
/* This is a generated file. Do not edit directly. */
'use strict';
// MAIN //
/**
* Evaluates a polynomial.
*
* ## Notes
*
* - The implementation uses [Horner's rule][horners-method] for efficient computation.
*
* [horners-method]: https://en.wikipedia.org/wiki/Horner%27s_method
*
*
* @private
* @param {number} x - value at which to evaluate the polynomial
* @returns {number} evaluated polynomial
*/
function evalpoly( x ) {
if ( x === 0.0 ) {
return 1.3920053346762105;
}
return 1.3920053346762105 + (x * (0.7219355475671381 + (x * (0.17193386563280308 + (x * (0.01864591917156529 + (x * (0.0007779424963818936 + (x * 0.000007326684307446256))))))))); // eslint-disable-line max-len
}
// EXPORTS //
module.exports = evalpoly;
},{}],299:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
/* This is a generated file. Do not edit directly. */
'use strict';
// MAIN //
/**
* Evaluates a polynomial.
*
* ## Notes
*
* - The implementation uses [Horner's rule][horners-method] for efficient computation.
*
* [horners-method]: https://en.wikipedia.org/wiki/Horner%27s_method
*
*
* @private
* @param {number} x - value at which to evaluate the polynomial
* @returns {number} evaluated polynomial
*/
function evalpoly( x ) {
if ( x === 0.0 ) {
return 0.21498241596060885;
}
return 0.21498241596060885 + (x * (0.325778796408931 + (x * (0.14635047265246445 + (x * (0.02664227030336386 + (x * (0.0018402845140733772 + (x * 0.00003194753265841009))))))))); // eslint-disable-line max-len
}
// EXPORTS //
module.exports = evalpoly;
},{}],300:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
/* This is a generated file. Do not edit directly. */
'use strict';
// MAIN //
/**
* Evaluates a polynomial.
*
* ## Notes
*
* - The implementation uses [Horner's rule][horners-method] for efficient computation.
*
* [horners-method]: https://en.wikipedia.org/wiki/Horner%27s_method
*
*
* @private
* @param {number} x - value at which to evaluate the polynomial
* @returns {number} evaluated polynomial
*/
function evalpoly( x ) {
if ( x === 0.0 ) {
return -0.032788541075985965;
}
return -0.032788541075985965 + (x * (0.006100538702462913 + (x * (-0.0014034646998923284 + (x * 0.00031563207090362595))))); // eslint-disable-line max-len
}
// EXPORTS //
module.exports = evalpoly;
},{}],301:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
/* This is a generated file. Do not edit directly. */
'use strict';
// MAIN //
/**
* Evaluates a polynomial.
*
* ## Notes
*
* - The implementation uses [Horner's rule][horners-method] for efficient computation.
*
* [horners-method]: https://en.wikipedia.org/wiki/Horner%27s_method
*
*
* @private
* @param {number} x - value at which to evaluate the polynomial
* @returns {number} evaluated polynomial
*/
function evalpoly( x ) {
if ( x === 0.0 ) {
return 0.01797067508118204;
}
return 0.01797067508118204 + (x * (-0.0036845201678113826 + (x * (0.000881081882437654 + (x * -0.00031275416837512086))))); // eslint-disable-line max-len
}
// EXPORTS //
module.exports = evalpoly;
},{}],302:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
/* This is a generated file. Do not edit directly. */
'use strict';
// MAIN //
/**
* Evaluates a polynomial.
*
* ## Notes
*
* - The implementation uses [Horner's rule][horners-method] for efficient computation.
*
* [horners-method]: https://en.wikipedia.org/wiki/Horner%27s_method
*
*
* @private
* @param {number} x - value at which to evaluate the polynomial
* @returns {number} evaluated polynomial
*/
function evalpoly( x ) {
if ( x === 0.0 ) {
return -0.010314224129834144;
}
return -0.010314224129834144 + (x * (0.0022596478090061247 + (x * (-0.0005385953053567405 + (x * 0.0003355291926355191))))); // eslint-disable-line max-len
}
// EXPORTS //
module.exports = evalpoly;
},{}],303:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
/* This is a generated file. Do not edit directly. */
'use strict';
// MAIN //
/**
* Evaluates a polynomial.
*
* ## Notes
*
* - The implementation uses [Horner's rule][horners-method] for efficient computation.
*
* [horners-method]: https://en.wikipedia.org/wiki/Horner%27s_method
*
*
* @private
* @param {number} x - value at which to evaluate the polynomial
* @returns {number} evaluated polynomial
*/
function evalpoly( x ) {
if ( x === 0.0 ) {
return 0.6328270640250934;
}
return 0.6328270640250934 + (x * (1.4549225013723477 + (x * (0.9777175279633727 + (x * (0.22896372806469245 + (x * 0.013381091853678766))))))); // eslint-disable-line max-len
}
// EXPORTS //
module.exports = evalpoly;
},{}],304:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
/* This is a generated file. Do not edit directly. */
'use strict';
// MAIN //
/**
* Evaluates a polynomial.
*
* ## Notes
*
* - The implementation uses [Horner's rule][horners-method] for efficient computation.
*
* [horners-method]: https://en.wikipedia.org/wiki/Horner%27s_method
*
*
* @private
* @param {number} x - value at which to evaluate the polynomial
* @returns {number} evaluated polynomial
*/
function evalpoly( x ) {
if ( x === 0.0 ) {
return 2.4559779371304113;
}
return 2.4559779371304113 + (x * (2.128489763798934 + (x * (0.7692851504566728 + (x * (0.10422264559336913 + (x * 0.003217092422824239))))))); // eslint-disable-line max-len
}
// EXPORTS //
module.exports = evalpoly;
},{}],305:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
/* This is a generated file. Do not edit directly. */
'use strict';
// MAIN //
/**
* Evaluates a polynomial.
*
* ## Notes
*
* - The implementation uses [Horner's rule][horners-method] for efficient computation.
*
* [horners-method]: https://en.wikipedia.org/wiki/Horner%27s_method
*
*
* @private
* @param {number} x - value at which to evaluate the polynomial
* @returns {number} evaluated polynomial
*/
function evalpoly( x ) {
if ( x === 0.0 ) {
return 0.08333333333333297;
}
return 0.08333333333333297 + (x * (-0.0027777777772877554 + (x * (0.0007936505586430196 + (x * (-0.00059518755745034 + (x * (0.0008363399189962821 + (x * -0.0016309293409657527))))))))); // eslint-disable-line max-len
}
// EXPORTS //
module.exports = evalpoly;
},{}],306:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Compute the cosine of a number on `[-π/4, π/4]`.
*
* @module @stdlib/math/base/special/kernel-cos
*
* @example
* var kernelCos = require( '@stdlib/math/base/special/kernel-cos' );
*
* var v = kernelCos( 0.0, 0.0 );
* // returns ~1.0
*
* v = kernelCos( 3.141592653589793/6.0, 0.0 );
* // returns ~0.866
*
* v = kernelCos( 0.785, -1.144e-17 );
* // returns ~0.707
*
* v = kernelCos( NaN, 0.0 );
* // returns NaN
*/
// MODULES //
var kernelCos = require( './kernel_cos.js' );
// EXPORTS //
module.exports = kernelCos;
},{"./kernel_cos.js":307}],307:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*
*
* ## Notice
*
* The following copyright, license, and long comment were part of the original implementation available as part of [FreeBSD]{@link https://svnweb.freebsd.org/base/release/9.3.0/lib/msun/src/k_cos.c}. The implementation follows the original, but has been modified for JavaScript.
*
* ```text
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunPro, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ```
*/
'use strict';
// MODULES //
var polyval13 = require( './polyval_c13.js' );
var polyval46 = require( './polyval_c46.js' );
// MAIN //
/**
* Computes the cosine on \\( \[-\pi/4, \pi/4] \\), where \\( \pi/4 \approx 0.785398164 \\).
*
* ## Method
*
* - Since \\( \cos(-x) = \cos(x) \\), we need only to consider positive \\(x\\).
*
* - If \\( x < 2^{-27} \\), return \\(1\\) which is inexact if \\( x \ne 0 \\).
*
* - \\( cos(x) \\) is approximated by a polynomial of degree \\(14\\) on \\( \[0,\pi/4] \\).
*
* ```tex
* \cos(x) \approx 1 - \frac{x \cdot x}{2} + C_1 \cdot x^4 + \ldots + C_6 \cdot x^{14}
* ```
*
* where the Remez error is
*
* ```tex
* \left| \cos(x) - \left( 1 - \frac{x^2}{2} + C_1x^4 + C_2x^6 + C_3x^8 + C_4x^{10} + C_5x^{12} + C_6x^{15} \right) \right| \le 2^{-58}
* ```
*
* - Let \\( C_1x^4 + C_2x^6 + C_3x^8 + C_4x^{10} + C_5x^{12} + C_6x^{14} \\), then
*
* ```tex
* \cos(x) \approx 1 - \frac{x \cdot x}{2} + r
* ```
*
* Since
*
* ```tex
* \cos(x+y) \approx \cos(x) - \sin(x) \cdot y \approx \cos(x) - x \cdot y
* ```
*
* a correction term is necessary in \\( \cos(x) \\). Hence,
*
* ```tex
* \cos(x+y) = 1 - \left( \frac{x \cdot x}{2} - (r - x \cdot y) \right)
* ```
*
* For better accuracy, rearrange to
*
* ```tex
* \cos(x+y) \approx w + \left( t + ( r - x \cdot y ) \right)
* ```
*
* where \\( w = 1 - \frac{x \cdot x}{2} \\) and \\( t \\) is a tiny correction term (\\( 1 - \frac{x \cdot x}{2} = w + t \\) exactly in infinite precision). The exactness of \\(w + t\\) in infinite precision depends on \\(w\\) and \\(t\\) having the same precision as \\(x\\).
*
*
* @param {number} x - input value (in radians, assumed to be bounded by ~pi/4 in magnitude)
* @param {number} y - tail of `x`
* @returns {number} cosine
*
* @example
* var v = kernelCos( 0.0, 0.0 );
* // returns ~1.0
*
* @example
* var v = kernelCos( 3.141592653589793/6.0, 0.0 );
* // returns ~0.866
*
* @example
* var v = kernelCos( 0.785, -1.144e-17 );
* // returns ~0.707
*
* @example
* var v = kernelCos( NaN, 0.0 );
* // returns NaN
*/
function kernelCos( x, y ) {
var hz;
var r;
var w;
var z;
z = x * x;
w = z * z;
r = z * polyval13( z );
r += w * w * polyval46( z );
hz = 0.5 * z;
w = 1.0 - hz;
return w + ( ((1.0-w) - hz) + ((z*r) - (x*y)) );
}
// EXPORTS //
module.exports = kernelCos;
},{"./polyval_c13.js":308,"./polyval_c46.js":309}],308:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
/* This is a generated file. Do not edit directly. */
'use strict';
// MAIN //
/**
* Evaluates a polynomial.
*
* ## Notes
*
* - The implementation uses [Horner's rule][horners-method] for efficient computation.
*
* [horners-method]: https://en.wikipedia.org/wiki/Horner%27s_method
*
*
* @private
* @param {number} x - value at which to evaluate the polynomial
* @returns {number} evaluated polynomial
*/
function evalpoly( x ) {
if ( x === 0.0 ) {
return 0.0416666666666666;
}
return 0.0416666666666666 + (x * (-0.001388888888887411 + (x * 0.00002480158728947673))); // eslint-disable-line max-len
}
// EXPORTS //
module.exports = evalpoly;
},{}],309:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
/* This is a generated file. Do not edit directly. */
'use strict';
// MAIN //
/**
* Evaluates a polynomial.
*
* ## Notes
*
* - The implementation uses [Horner's rule][horners-method] for efficient computation.
*
* [horners-method]: https://en.wikipedia.org/wiki/Horner%27s_method
*
*
* @private
* @param {number} x - value at which to evaluate the polynomial
* @returns {number} evaluated polynomial
*/
function evalpoly( x ) {
if ( x === 0.0 ) {
return -2.7557314351390663e-7;
}
return -2.7557314351390663e-7 + (x * (2.087572321298175e-9 + (x * -1.1359647557788195e-11))); // eslint-disable-line max-len
}
// EXPORTS //
module.exports = evalpoly;
},{}],310:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Compute the sine of a number on `[-π/4, π/4]`.
*
* @module @stdlib/math/base/special/kernel-sin
*
* @example
* var kernelSin = require( '@stdlib/math/base/special/kernel-sin' );
*
* var v = kernelSin( 0.0, 0.0 );
* // returns ~0.0
*
* v = kernelSin( 3.141592653589793/6.0, 0.0 );
* // returns ~0.5
*
* v = kernelSin( 0.619, 9.279e-18 );
* // returns ~0.581
*
* v = kernelSin( NaN, 0.0 );
* // returns NaN
*
* v = kernelSin( 3.0, NaN );
* // returns NaN
*
* v = kernelSin( NaN, NaN );
* // returns NaN
*/
// MODULES //
var kernelSin = require( './kernel_sin.js' );
// EXPORTS //
module.exports = kernelSin;
},{"./kernel_sin.js":311}],311:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*
*
* ## Notice
*
* The following copyright, license, and long comment were part of the original implementation available as part of [FreeBSD]{@link https://svnweb.freebsd.org/base/release/9.3.0/lib/msun/src/k_sin.c}. The implementation follows the original, but has been modified for JavaScript.
*
* ```text
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunPro, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ```
*/
'use strict';
// VARIABLES //
var S1 = -1.66666666666666324348e-01; // 0xBFC55555, 0x55555549
var S2 = 8.33333333332248946124e-03; // 0x3F811111, 0x1110F8A6
var S3 = -1.98412698298579493134e-04; // 0xBF2A01A0, 0x19C161D5
var S4 = 2.75573137070700676789e-06; // 0x3EC71DE3, 0x57B1FE7D
var S5 = -2.50507602534068634195e-08; // 0xBE5AE5E6, 0x8A2B9CEB
var S6 = 1.58969099521155010221e-10; // 0x3DE5D93A, 0x5ACFD57C
// MAIN //
/**
* Computes the sine on \\( \approx \[-\pi/4, \pi/4] \\) (except on \\(-0\\)), where \\( \pi/4 \approx 0.7854 \\).
*
* ## Method
*
* - Since \\( \sin(-x) = -\sin(x) \\), we need only to consider positive \\(x\\).
*
* - Callers must return \\( \sin(-0) = -0 \\) without calling here since our odd polynomial is not evaluated in a way that preserves \\(-0\\). Callers may do the optimization \\( \sin(x) \approx x \\) for tiny \\(x\\).
*
* - \\( \sin(x) \\) is approximated by a polynomial of degree \\(13\\) on \\( \left\[0,\tfrac{pi}{4}\right] \\)
*
* ```tex
* \sin(x) \approx x + S_1 \cdot x^3 + \ldots + S_6 \cdot x^{13}
* ```
*
* where
*
* ```tex
* \left| \frac{\sin(x)}{x} \left( 1 + S_1 \cdot x + S_2 \cdot x + S_3 \cdot x + S_4 \cdot x + S_5 \cdot x + S_6 \cdot x \right) \right| \le 2^{-58}
* ```
*
* - We have
*
* ```tex
* \sin(x+y) = \sin(x) + \sin'(x') \cdot y \approx \sin(x) + (1-x*x/2) \cdot y
* ```
*
* For better accuracy, let
*
* ```tex
* r = x^3 * \left( S_2 + x^2 \cdot \left( S_3 + x^2 * \left( S_4 + x^2 \cdot ( S_5+x^2 \cdot S_6 ) \right) \right) \right)
* ```
*
* then
*
* ```tex
* \sin(x) = x + \left( S_1 \cdot x + ( x \cdot (r-y/2) + y ) \right)
* ```
*
*
* @param {number} x - input value (in radians, assumed to be bounded by `~pi/4` in magnitude)
* @param {number} y - tail of `x`
* @returns {number} sine
*
* @example
* var v = kernelSin( 0.0, 0.0 );
* // returns ~0.0
*
* @example
* var v = kernelSin( 3.141592653589793/6.0, 0.0 );
* // returns ~0.5
*
* @example
* var v = kernelSin( 0.619, 9.279e-18 );
* // returns ~0.58
*
* @example
* var v = kernelSin( NaN, 0.0 );
* // returns NaN
*
* @example
* var v = kernelSin( 3.0, NaN );
* // returns NaN
*
* @example
* var v = kernelSin( NaN, NaN );
* // returns NaN
*/
function kernelSin( x, y ) {
var r;
var v;
var w;
var z;
z = x * x;
w = z * z;
r = S2 + (z * (S3 + (z*S4))) + (z * w * (S5 + (z*S6)));
v = z * x;
if ( y === 0.0 ) {
return x + (v * (S1 + (z*r)));
}
return x - (((z*((0.5*y) - (v*r))) - y) - (v*S1));
}
// EXPORTS //
module.exports = kernelSin;
},{}],312:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Multiply a double-precision floating-point number by an integer power of two.
*
* @module @stdlib/math/base/special/ldexp
*
* @example
* var ldexp = require( '@stdlib/math/base/special/ldexp' );
*
* var x = ldexp( 0.5, 3 ); // => 0.5 * 2^3 = 0.5 * 8
* // returns 4.0
*
* x = ldexp( 4.0, -2 ); // => 4 * 2^(-2) = 4 * (1/4)
* // returns 1.0
*
* x = ldexp( 0.0, 20 );
* // returns 0.0
*
* x = ldexp( -0.0, 39 );
* // returns -0.0
*
* x = ldexp( NaN, -101 );
* // returns NaN
*
* x = ldexp( Infinity, 11 );
* // returns Infinity
*
* x = ldexp( -Infinity, -118 );
* // returns -Infinity
*/
// MODULES //
var ldexp = require( './ldexp.js' );
// EXPORTS //
module.exports = ldexp;
},{"./ldexp.js":313}],313:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// NOTES //
/*
* => ldexp: load exponent (see [The Open Group]{@link http://pubs.opengroup.org/onlinepubs/9699919799/functions/ldexp.html} and [cppreference]{@link http://en.cppreference.com/w/c/numeric/math/ldexp}).
*/
// MODULES //
var PINF = require( '@stdlib/constants/float64/pinf' );
var NINF = require( '@stdlib/constants/float64/ninf' );
var BIAS = require( '@stdlib/constants/float64/exponent-bias' );
var MAX_EXPONENT = require( '@stdlib/constants/float64/max-base2-exponent' );
var MAX_SUBNORMAL_EXPONENT = require( '@stdlib/constants/float64/max-base2-exponent-subnormal' );
var MIN_SUBNORMAL_EXPONENT = require( '@stdlib/constants/float64/min-base2-exponent-subnormal' );
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var isInfinite = require( '@stdlib/math/base/assert/is-infinite' );
var copysign = require( '@stdlib/math/base/special/copysign' );
var normalize = require( '@stdlib/number/float64/base/normalize' );
var floatExp = require( '@stdlib/number/float64/base/exponent' );
var toWords = require( '@stdlib/number/float64/base/to-words' );
var fromWords = require( '@stdlib/number/float64/base/from-words' );
// VARIABLES //
// 1/(1<<52) = 1/(2**52) = 1/4503599627370496
var TWO52_INV = 2.220446049250313e-16;
// Exponent all 0s: 1 00000000000 11111111111111111111 => 2148532223
var CLEAR_EXP_MASK = 0x800fffff>>>0; // asm type annotation
// Normalization workspace:
var FRAC = [ 0.0, 0.0 ]; // WARNING: not thread safe
// High/low words workspace:
var WORDS = [ 0, 0 ]; // WARNING: not thread safe
// MAIN //
/**
* Multiplies a double-precision floating-point number by an integer power of two.
*
* @param {number} frac - fraction
* @param {integer} exp - exponent
* @returns {number} double-precision floating-point number
*
* @example
* var x = ldexp( 0.5, 3 ); // => 0.5 * 2^3 = 0.5 * 8
* // returns 4.0
*
* @example
* var x = ldexp( 4.0, -2 ); // => 4 * 2^(-2) = 4 * (1/4)
* // returns 1.0
*
* @example
* var x = ldexp( 0.0, 20 );
* // returns 0.0
*
* @example
* var x = ldexp( -0.0, 39 );
* // returns -0.0
*
* @example
* var x = ldexp( NaN, -101 );
* // returns NaN
*
* @example
* var x = ldexp( Infinity, 11 );
* // returns Infinity
*
* @example
* var x = ldexp( -Infinity, -118 );
* // returns -Infinity
*/
function ldexp( frac, exp ) {
var high;
var m;
if (
frac === 0.0 || // handles +-0
isnan( frac ) ||
isInfinite( frac )
) {
return frac;
}
// Normalize the input fraction:
normalize( FRAC, frac );
frac = FRAC[ 0 ];
exp += FRAC[ 1 ];
// Extract the exponent from `frac` and add it to `exp`:
exp += floatExp( frac );
// Check for underflow/overflow...
if ( exp < MIN_SUBNORMAL_EXPONENT ) {
return copysign( 0.0, frac );
}
if ( exp > MAX_EXPONENT ) {
if ( frac < 0.0 ) {
return NINF;
}
return PINF;
}
// Check for a subnormal and scale accordingly to retain precision...
if ( exp <= MAX_SUBNORMAL_EXPONENT ) {
exp += 52;
m = TWO52_INV;
} else {
m = 1.0;
}
// Split the fraction into higher and lower order words:
toWords( WORDS, frac );
high = WORDS[ 0 ];
// Clear the exponent bits within the higher order word:
high &= CLEAR_EXP_MASK;
// Set the exponent bits to the new exponent:
high |= ((exp+BIAS) << 20);
// Create a new floating-point number:
return m * fromWords( high, WORDS[ 1 ] );
}
// EXPORTS //
module.exports = ldexp;
},{"@stdlib/constants/float64/exponent-bias":245,"@stdlib/constants/float64/max-base2-exponent":250,"@stdlib/constants/float64/max-base2-exponent-subnormal":249,"@stdlib/constants/float64/min-base2-exponent-subnormal":252,"@stdlib/constants/float64/ninf":253,"@stdlib/constants/float64/pinf":255,"@stdlib/math/base/assert/is-infinite":268,"@stdlib/math/base/assert/is-nan":272,"@stdlib/math/base/special/copysign":283,"@stdlib/number/float64/base/exponent":343,"@stdlib/number/float64/base/from-words":345,"@stdlib/number/float64/base/normalize":354,"@stdlib/number/float64/base/to-words":360}],314:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Evaluate the natural logarithm.
*
* @module @stdlib/math/base/special/ln
*
* @example
* var ln = require( '@stdlib/math/base/special/ln' );
*
* var v = ln( 4.0 );
* // returns ~1.386
*
* v = ln( 0.0 );
* // returns -Infinity
*
* v = ln( Infinity );
* // returns Infinity
*
* v = ln( NaN );
* // returns NaN
*
* v = ln( -4.0 );
* // returns NaN
*/
// MODULES //
var ln = require( './ln.js' );
// EXPORTS //
module.exports = ln;
},{"./ln.js":315}],315:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*
*
* ## Notice
*
* The following copyright and license were part of the original implementation available as part of [FreeBSD]{@link https://svnweb.freebsd.org/base/release/9.3.0/lib/msun/src/e_log.c}. The implementation follows the original, but has been modified for JavaScript.
*
* ```text
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunPro, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ```
*/
'use strict';
// MODULES //
var getHighWord = require( '@stdlib/number/float64/base/get-high-word' );
var setHighWord = require( '@stdlib/number/float64/base/set-high-word' );
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var BIAS = require( '@stdlib/constants/float64/exponent-bias' );
var NINF = require( '@stdlib/constants/float64/ninf' );
var polyvalP = require( './polyval_p.js' );
var polyvalQ = require( './polyval_q.js' );
// VARIABLES //
var LN2_HI = 6.93147180369123816490e-01; // 3FE62E42 FEE00000
var LN2_LO = 1.90821492927058770002e-10; // 3DEA39EF 35793C76
var TWO54 = 1.80143985094819840000e+16; // 0x43500000, 0x00000000
var ONE_THIRD = 0.33333333333333333;
// 0x000fffff = 1048575 => 0 00000000000 11111111111111111111
var HIGH_SIGNIFICAND_MASK = 0x000fffff|0; // asm type annotation
// 0x7ff00000 = 2146435072 => 0 11111111111 00000000000000000000 => biased exponent: 2047 = 1023+1023 => 2^1023
var HIGH_MAX_NORMAL_EXP = 0x7ff00000|0; // asm type annotation
// 0x00100000 = 1048576 => 0 00000000001 00000000000000000000 => biased exponent: 1 = -1022+1023 => 2^-1022
var HIGH_MIN_NORMAL_EXP = 0x00100000|0; // asm type annotation
// 0x3ff00000 = 1072693248 => 0 01111111111 00000000000000000000 => biased exponent: 1023 = 0+1023 => 2^0 = 1
var HIGH_BIASED_EXP_0 = 0x3ff00000|0; // asm type annotation
// MAIN //
/**
* Evaluates the natural logarithm.
*
* @param {NonNegativeNumber} x - input value
* @returns {number} function value
*
* @example
* var v = ln( 4.0 );
* // returns ~1.386
*
* @example
* var v = ln( 0.0 );
* // returns -Infinity
*
* @example
* var v = ln( Infinity );
* // returns Infinity
*
* @example
* var v = ln( NaN );
* // returns NaN
*
* @example
* var v = ln( -4.0 );
* // returns NaN
*/
function ln( x ) {
var hfsq;
var hx;
var t2;
var t1;
var k;
var R;
var f;
var i;
var j;
var s;
var w;
var z;
if ( x === 0.0 ) {
return NINF;
}
if ( isnan( x ) || x < 0.0 ) {
return NaN;
}
hx = getHighWord( x );
k = 0|0; // asm type annotation
if ( hx < HIGH_MIN_NORMAL_EXP ) {
// Case: 0 < x < 2**-1022
k -= 54|0; // asm type annotation
// Subnormal number, scale up `x`:
x *= TWO54;
hx = getHighWord( x );
}
if ( hx >= HIGH_MAX_NORMAL_EXP ) {
return x + x;
}
k += ( ( hx>>20 ) - BIAS )|0; // asm type annotation
hx &= HIGH_SIGNIFICAND_MASK;
i = ( (hx+0x95f64) & 0x100000 )|0; // asm type annotation
// Normalize `x` or `x/2`...
x = setHighWord( x, hx|(i^HIGH_BIASED_EXP_0) );
k += ( i>>20 )|0; // asm type annotation
f = x - 1.0;
if ( (HIGH_SIGNIFICAND_MASK&(2+hx)) < 3 ) {
// Case: -2**-20 <= f < 2**-20
if ( f === 0.0 ) {
if ( k === 0 ) {
return 0.0;
}
return (k * LN2_HI) + (k * LN2_LO);
}
R = f * f * ( 0.5 - (ONE_THIRD*f) );
if ( k === 0 ) {
return f - R;
}
return (k * LN2_HI) - ( (R-(k*LN2_LO)) - f );
}
s = f / (2.0 + f);
z = s * s;
i = ( hx - 0x6147a )|0; // asm type annotation
w = z * z;
j = ( 0x6b851 - hx )|0; // asm type annotation
t1 = w * polyvalP( w );
t2 = z * polyvalQ( w );
i |= j;
R = t2 + t1;
if ( i > 0 ) {
hfsq = 0.5 * f * f;
if ( k === 0 ) {
return f - ( hfsq - (s * (hfsq+R)) );
}
return (k * LN2_HI) - ( hfsq - ((s*(hfsq+R))+(k*LN2_LO)) - f );
}
if ( k === 0 ) {
return f - (s*(f-R));
}
return (k * LN2_HI) - ( ( (s*(f-R)) - (k*LN2_LO) ) - f );
}
// EXPORTS //
module.exports = ln;
},{"./polyval_p.js":316,"./polyval_q.js":317,"@stdlib/constants/float64/exponent-bias":245,"@stdlib/constants/float64/ninf":253,"@stdlib/math/base/assert/is-nan":272,"@stdlib/number/float64/base/get-high-word":349,"@stdlib/number/float64/base/set-high-word":358}],316:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
/* This is a generated file. Do not edit directly. */
'use strict';
// MAIN //
/**
* Evaluates a polynomial.
*
* ## Notes
*
* - The implementation uses [Horner's rule][horners-method] for efficient computation.
*
* [horners-method]: https://en.wikipedia.org/wiki/Horner%27s_method
*
*
* @private
* @param {number} x - value at which to evaluate the polynomial
* @returns {number} evaluated polynomial
*/
function evalpoly( x ) {
if ( x === 0.0 ) {
return 0.3999999999940942;
}
return 0.3999999999940942 + (x * (0.22222198432149784 + (x * 0.15313837699209373))); // eslint-disable-line max-len
}
// EXPORTS //
module.exports = evalpoly;
},{}],317:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
/* This is a generated file. Do not edit directly. */
'use strict';
// MAIN //
/**
* Evaluates a polynomial.
*
* ## Notes
*
* - The implementation uses [Horner's rule][horners-method] for efficient computation.
*
* [horners-method]: https://en.wikipedia.org/wiki/Horner%27s_method
*
*
* @private
* @param {number} x - value at which to evaluate the polynomial
* @returns {number} evaluated polynomial
*/
function evalpoly( x ) {
if ( x === 0.0 ) {
return 0.6666666666666735;
}
return 0.6666666666666735 + (x * (0.2857142874366239 + (x * (0.1818357216161805 + (x * 0.14798198605116586))))); // eslint-disable-line max-len
}
// EXPORTS //
module.exports = evalpoly;
},{}],318:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Return the maximum value.
*
* @module @stdlib/math/base/special/max
*
* @example
* var max = require( '@stdlib/math/base/special/max' );
*
* var v = max( 3.14, 4.2 );
* // returns 4.2
*
* v = max( 5.9, 3.14, 4.2 );
* // returns 5.9
*
* v = max( 3.14, NaN );
* // returns NaN
*
* v = max( +0.0, -0.0 );
* // returns +0.0
*/
// MODULES //
var max = require( './max.js' );
// EXPORTS //
module.exports = max;
},{"./max.js":319}],319:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isPositiveZero = require( '@stdlib/math/base/assert/is-positive-zero' );
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var NINF = require( '@stdlib/constants/float64/ninf' );
var PINF = require( '@stdlib/constants/float64/pinf' );
// MAIN //
/**
* Returns the maximum value.
*
* @param {number} [x] - first number
* @param {number} [y] - second number
* @param {...number} [args] - numbers
* @returns {number} maximum value
*
* @example
* var v = max( 3.14, 4.2 );
* // returns 4.2
*
* @example
* var v = max( 5.9, 3.14, 4.2 );
* // returns 5.9
*
* @example
* var v = max( 3.14, NaN );
* // returns NaN
*
* @example
* var v = max( +0.0, -0.0 );
* // returns +0.0
*/
function max( x, y ) {
var len;
var m;
var v;
var i;
len = arguments.length;
if ( len === 2 ) {
if ( isnan( x ) || isnan( y ) ) {
return NaN;
}
if ( x === PINF || y === PINF ) {
return PINF;
}
if ( x === y && x === 0.0 ) {
if ( isPositiveZero( x ) ) {
return x;
}
return y;
}
if ( x > y ) {
return x;
}
return y;
}
m = NINF;
for ( i = 0; i < len; i++ ) {
v = arguments[ i ];
if ( isnan( v ) || v === PINF ) {
return v;
}
if ( v > m ) {
m = v;
} else if (
v === m &&
v === 0.0 &&
isPositiveZero( v )
) {
m = v;
}
}
return m;
}
// EXPORTS //
module.exports = max;
},{"@stdlib/constants/float64/ninf":253,"@stdlib/constants/float64/pinf":255,"@stdlib/math/base/assert/is-nan":272,"@stdlib/math/base/assert/is-positive-zero":276}],320:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Decompose a double-precision floating-point number into integral and fractional parts.
*
* @module @stdlib/math/base/special/modf
*
* @example
* var modf = require( '@stdlib/math/base/special/modf' );
*
* var parts = modf( 3.14 );
* // returns [ 3.0, 0.14000000000000012 ]
*
* @example
* var Float64Array = require( '@stdlib/array/float64' );
* var modf = require( '@stdlib/math/base/special/modf' );
*
* var out = new Float64Array( 2 );
*
* var parts = modf( out, 3.14 );
* // returns [ 3.0, 0.14000000000000012 ]
*
* var bool = ( parts === out );
* // returns true
*/
// MODULES //
var modf = require( './main.js' );
// EXPORTS //
module.exports = modf;
},{"./main.js":321}],321:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var fcn = require( './modf.js' );
// MAIN //
/**
* Decomposes a double-precision floating-point number into integral and fractional parts, each having the same type and sign as the input value.
*
* @param {(Array|TypedArray|Object)} [out] - output array
* @param {number} x - input value
* @returns {(Array|TypedArray|Object)} output array
*
* @example
* var parts = modf( 3.14 );
* // returns [ 3.0, 0.14000000000000012 ]
*
* @example
* var Float64Array = require( '@stdlib/array/float64' );
*
* var out = new Float64Array( 2 );
*
* var parts = modf( out, 3.14 );
* // returns <Float64Array>[ 3.0, 0.14000000000000012 ]
*
* var bool = ( parts === out );
* // returns true
*/
function modf( out, x ) {
if ( arguments.length === 1 ) {
return fcn( [ 0.0, 0.0 ], out );
}
return fcn( out, x );
}
// EXPORTS //
module.exports = modf;
},{"./modf.js":322}],322:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var toWords = require( '@stdlib/number/float64/base/to-words' );
var fromWords = require( '@stdlib/number/float64/base/from-words' );
var PINF = require( '@stdlib/constants/float64/pinf' );
var FLOAT64_EXPONENT_BIAS = require( '@stdlib/constants/float64/exponent-bias' );
var FLOAT64_HIGH_WORD_EXPONENT_MASK = require( '@stdlib/constants/float64/high-word-exponent-mask' ); // eslint-disable-line id-length
var FLOAT64_HIGH_WORD_SIGNIFICAND_MASK = require( '@stdlib/constants/float64/high-word-significand-mask' ); // eslint-disable-line id-length
// VARIABLES //
// 4294967295 => 0xffffffff => 11111111111111111111111111111111
var ALL_ONES = 4294967295>>>0; // asm type annotation
// High/low words workspace:
var WORDS = [ 0|0, 0|0 ]; // WARNING: not thread safe
// MAIN //
/**
* Decomposes a double-precision floating-point number into integral and fractional parts, each having the same type and sign as the input value.
*
* @private
* @param {(Array|TypedArray|Object)} out - output array
* @param {number} x - input value
* @returns {(Array|TypedArray|Object)} output array
*
* @example
* var parts = modf( [ 0.0, 0.0 ], 3.14 );
* // returns [ 3.0, 0.14000000000000012 ]
*/
function modf( out, x ) {
var high;
var low;
var exp;
var i;
// Special cases...
if ( x < 1.0 ) {
if ( x < 0.0 ) {
modf( out, -x );
out[ 0 ] *= -1.0;
out[ 1 ] *= -1.0;
return out;
}
if ( x === 0.0 ) { // [ +-0, +-0 ]
out[ 0 ] = x;
out[ 1 ] = x;
return out;
}
out[ 0 ] = 0.0;
out[ 1 ] = x;
return out;
}
if ( isnan( x ) ) {
out[ 0 ] = NaN;
out[ 1 ] = NaN;
return out;
}
if ( x === PINF ) {
out[ 0 ] = PINF;
out[ 1 ] = 0.0;
return out;
}
// Decompose |x|...
// Extract the high and low words:
toWords( WORDS, x );
high = WORDS[ 0 ];
low = WORDS[ 1 ];
// Extract the unbiased exponent from the high word:
exp = ((high & FLOAT64_HIGH_WORD_EXPONENT_MASK) >> 20)|0; // asm type annotation
exp -= FLOAT64_EXPONENT_BIAS|0; // asm type annotation
// Handle smaller values (x < 2**20 = 1048576)...
if ( exp < 20 ) {
i = (FLOAT64_HIGH_WORD_SIGNIFICAND_MASK >> exp)|0; // asm type annotation
// Determine if `x` is integral by checking for significand bits which cannot be exponentiated away...
if ( ((high&i)|low) === 0 ) {
out[ 0 ] = x;
out[ 1 ] = 0.0;
return out;
}
// Turn off all the bits which cannot be exponentiated away:
high &= (~i);
// Generate the integral part:
i = fromWords( high, 0 );
// The fractional part is whatever is leftover:
out[ 0 ] = i;
out[ 1 ] = x - i;
return out;
}
// Check if `x` can even have a fractional part...
if ( exp > 51 ) {
// `x` is integral:
out[ 0 ] = x;
out[ 1 ] = 0.0;
return out;
}
i = ALL_ONES >>> (exp-20);
// Determine if `x` is integral by checking for less significant significand bits which cannot be exponentiated away...
if ( (low&i) === 0 ) {
out[ 0 ] = x;
out[ 1 ] = 0.0;
return out;
}
// Turn off all the bits which cannot be exponentiated away:
low &= (~i);
// Generate the integral part:
i = fromWords( high, low );
// The fractional part is whatever is leftover:
out[ 0 ] = i;
out[ 1 ] = x - i;
return out;
}
// EXPORTS //
module.exports = modf;
},{"@stdlib/constants/float64/exponent-bias":245,"@stdlib/constants/float64/high-word-exponent-mask":246,"@stdlib/constants/float64/high-word-significand-mask":247,"@stdlib/constants/float64/pinf":255,"@stdlib/math/base/assert/is-nan":272,"@stdlib/number/float64/base/from-words":345,"@stdlib/number/float64/base/to-words":360}],323:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Compute `x - nπ/2 = r`.
*
* @module @stdlib/math/base/special/rempio2
*
* @example
* var rempio2 = require( '@stdlib/math/base/special/rempio2' );
*
* var y = [ 0.0, 0.0 ];
* var n = rempio2( 128.0, y );
* // returns 81
*
* var y1 = y[ 0 ];
* // returns ~0.765
*
* var y2 = y[ 1 ];
* // returns ~3.618e-17
*/
// MODULES //
var rempio2 = require( './rempio2.js' );
// EXPORTS //
module.exports = rempio2;
},{"./rempio2.js":325}],324:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*
*
* ## Notice
*
* The following copyright and license were part of the original implementation available as part of [FreeBSD]{@link https://svnweb.freebsd.org/base/release/9.3.0/lib/msun/src/k_rem_pio2.c}. The implementation follows the original, but has been modified for JavaScript.
*
* ```text
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunPro, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ```
*/
/* eslint-disable array-element-newline */
'use strict';
// MODULES //
var floor = require( '@stdlib/math/base/special/floor' );
var ldexp = require( '@stdlib/math/base/special/ldexp' );
// VARIABLES //
/*
* Table of constants for `2/π` (`396` hex digits, `476` decimal).
*
* Integer array which contains the (`24*i`)-th to (`24*i+23`)-th bit of `2/π` after binary point. The corresponding floating value is
*
* ```tex
* \operatorname{ipio2}[i] \cdot 2^{-24(i+1)}
* ```
*
* This table must have at least `(e0-3)/24 + jk` terms. For quad precision (`e0 <= 16360`, `jk = 6`), this is `686`.
*/
var IPIO2 = [
0xA2F983, 0x6E4E44, 0x1529FC, 0x2757D1, 0xF534DD, 0xC0DB62,
0x95993C, 0x439041, 0xFE5163, 0xABDEBB, 0xC561B7, 0x246E3A,
0x424DD2, 0xE00649, 0x2EEA09, 0xD1921C, 0xFE1DEB, 0x1CB129,
0xA73EE8, 0x8235F5, 0x2EBB44, 0x84E99C, 0x7026B4, 0x5F7E41,
0x3991D6, 0x398353, 0x39F49C, 0x845F8B, 0xBDF928, 0x3B1FF8,
0x97FFDE, 0x05980F, 0xEF2F11, 0x8B5A0A, 0x6D1F6D, 0x367ECF,
0x27CB09, 0xB74F46, 0x3F669E, 0x5FEA2D, 0x7527BA, 0xC7EBE5,
0xF17B3D, 0x0739F7, 0x8A5292, 0xEA6BFB, 0x5FB11F, 0x8D5D08,
0x560330, 0x46FC7B, 0x6BABF0, 0xCFBC20, 0x9AF436, 0x1DA9E3,
0x91615E, 0xE61B08, 0x659985, 0x5F14A0, 0x68408D, 0xFFD880,
0x4D7327, 0x310606, 0x1556CA, 0x73A8C9, 0x60E27B, 0xC08C6B
];
// Double precision array, obtained by cutting `π/2` into `24` bits chunks...
var PIO2 = [
1.57079625129699707031e+00, // 0x3FF921FB, 0x40000000
7.54978941586159635335e-08, // 0x3E74442D, 0x00000000
5.39030252995776476554e-15, // 0x3CF84698, 0x80000000
3.28200341580791294123e-22, // 0x3B78CC51, 0x60000000
1.27065575308067607349e-29, // 0x39F01B83, 0x80000000
1.22933308981111328932e-36, // 0x387A2520, 0x40000000
2.73370053816464559624e-44, // 0x36E38222, 0x80000000
2.16741683877804819444e-51 // 0x3569F31D, 0x00000000
];
var TWO24 = 1.67772160000000000000e+07; // 0x41700000, 0x00000000
var TWON24 = 5.96046447753906250000e-08; // 0x3E700000, 0x00000000
// Arrays for storing temporary values (note that, in C, this is not thread safe):
var F = zeros( 20 );
var Q = zeros( 20 );
var FQ = zeros( 20 );
var IQ = zeros( 20 );
// FUNCTIONS //
/**
* Returns an array of zeros.
*
* @private
* @param {NonNegativeInteger} len - array length
* @returns {NonNegativeIntegerArray} output array
*/
function zeros( len ) {
var out;
var i;
out = [];
for ( i = 0; i < len; i++ ) {
out.push( 0.0 );
}
return out;
}
/**
* Performs the computation for `kernelRempio2()`.
*
* @private
* @param {PositiveNumber} x - input value
* @param {(Array|TypedArray|Object)} y - output object for storing double precision numbers
* @param {integer} jz - number of terms of `ipio2[]` used
* @param {Array<integer>} q - array with integral values, representing the 24-bits chunk of the product of `x` and `2/π`
* @param {integer} q0 - the corresponding exponent of `q[0]` (the exponent for `q[i]` would be `q0-24*i`)
* @param {integer} jk - `jk+1` is the initial number of terms of `IPIO2[]` needed in the computation
* @param {integer} jv - index for pointing to the suitable `ipio2[]` for the computation
* @param {integer} jx - `nx - 1`
* @param {Array<number>} f - `IPIO2[]` in floating point
* @returns {number} last three binary digits of `N`
*/
function compute( x, y, jz, q, q0, jk, jv, jx, f ) {
var carry;
var fw;
var ih;
var jp;
var i;
var k;
var n;
var j;
var z;
// `jp+1` is the number of terms in `PIO2[]` needed:
jp = jk;
// Distill `q[]` into `IQ[]` in reverse order...
z = q[ jz ];
j = jz;
for ( i = 0; j > 0; i++ ) {
fw = ( TWON24 * z )|0;
IQ[ i ] = ( z - (TWO24*fw) )|0;
z = q[ j-1 ] + fw;
j -= 1;
}
// Compute `n`...
z = ldexp( z, q0 );
z -= 8.0 * floor( z*0.125 ); // Trim off integer >= 8
n = z|0;
z -= n;
ih = 0;
if ( q0 > 0 ) {
// Need `IQ[jz-1]` to determine `n`...
i = ( IQ[ jz-1 ] >> (24-q0) );
n += i;
IQ[ jz-1 ] -= ( i << (24-q0) );
ih = ( IQ[ jz-1 ] >> (23-q0) );
}
else if ( q0 === 0 ) {
ih = ( IQ[ jz-1 ] >> 23 );
}
else if ( z >= 0.5 ) {
ih = 2;
}
// Case: q > 0.5
if ( ih > 0 ) {
n += 1;
carry = 0;
// Compute `1-q`:
for ( i = 0; i < jz; i++ ) {
j = IQ[ i ];
if ( carry === 0 ) {
if ( j !== 0 ) {
carry = 1;
IQ[ i ] = 0x1000000 - j;
}
} else {
IQ[ i ] = 0xffffff - j;
}
}
if ( q0 > 0 ) {
// Rare case: chance is 1 in 12...
switch ( q0 ) { // eslint-disable-line default-case
case 1:
IQ[ jz-1 ] &= 0x7fffff;
break;
case 2:
IQ[ jz-1 ] &= 0x3fffff;
break;
}
}
if ( ih === 2 ) {
z = 1.0 - z;
if ( carry !== 0 ) {
z -= ldexp( 1.0, q0 );
}
}
}
// Check if re-computation is needed...
if ( z === 0.0 ) {
j = 0;
for ( i = jz-1; i >= jk; i-- ) {
j |= IQ[ i ];
}
if ( j === 0 ) {
// Need re-computation...
for ( k = 1; IQ[ jk-k ] === 0; k++ ) {
// `k` is the number of terms needed...
}
for ( i = jz+1; i <= jz+k; i++ ) {
// Add `q[jz+1]` to `q[jz+k]`...
f[ jx+i ] = IPIO2[ jv+i ];
fw = 0.0;
for ( j = 0; j <= jx; j++ ) {
fw += x[ j ] * f[ jx + (i-j) ];
}
q[ i ] = fw;
}
jz += k;
return compute( x, y, jz, q, q0, jk, jv, jx, f );
}
}
// Chop off zero terms...
if ( z === 0.0 ) {
jz -= 1;
q0 -= 24;
while ( IQ[ jz ] === 0 ) {
jz -= 1;
q0 -= 24;
}
} else {
// Break `z` into 24-bit if necessary...
z = ldexp( z, -q0 );
if ( z >= TWO24 ) {
fw = (TWON24*z)|0;
IQ[ jz ] = ( z - (TWO24*fw) )|0;
jz += 1;
q0 += 24;
IQ[ jz ] = fw;
} else {
IQ[ jz ] = z|0;
}
}
// Convert integer "bit" chunk to floating-point value...
fw = ldexp( 1.0, q0 );
for ( i = jz; i >= 0; i-- ) {
q[ i ] = fw * IQ[i];
fw *= TWON24;
}
// Compute `PIO2[0,...,jp]*q[jz,...,0]`...
for ( i = jz; i >= 0; i-- ) {
fw = 0.0;
for ( k = 0; k <= jp && k <= jz-i; k++ ) {
fw += PIO2[ k ] * q[ i+k ];
}
FQ[ jz-i ] = fw;
}
// Compress `FQ[]` into `y[]`...
fw = 0.0;
for ( i = jz; i >= 0; i-- ) {
fw += FQ[ i ];
}
if ( ih === 0 ) {
y[ 0 ] = fw;
} else {
y[ 0 ] = -fw;
}
fw = FQ[ 0 ] - fw;
for ( i = 1; i <= jz; i++ ) {
fw += FQ[i];
}
if ( ih === 0 ) {
y[ 1 ] = fw;
} else {
y[ 1 ] = -fw;
}
return ( n & 7 );
}
// MAIN //
/**
* Returns the last three binary digits of `N` with `y = x - Nπ/2` so that `|y| < π/2`.
*
* ## Method
*
* - The method is to compute the integer (`mod 8`) and fraction parts of `2x/π` without doing the full multiplication. In general, we skip the part of the product that is known to be a huge integer (more accurately, equals `0 mod 8` ). Thus, the number of operations is independent of the exponent of the input.
*
* @private
* @param {PositiveNumber} x - input value
* @param {(Array|TypedArray|Object)} y - remainder elements
* @param {PositiveInteger} e0 - the exponent of `x[0]` (must be <= 16360)
* @param {PositiveInteger} nx - dimension of `x[]`
* @returns {number} last three binary digits of `N`
*/
function kernelRempio2( x, y, e0, nx ) {
var fw;
var jk;
var jv;
var jx;
var jz;
var q0;
var i;
var j;
var m;
// Initialize `jk` for double-precision floating-point numbers:
jk = 4;
// Determine `jx`, `jv`, `q0` (note that `q0 < 3`):
jx = nx - 1;
jv = ( (e0 - 3) / 24 )|0;
if ( jv < 0 ) {
jv = 0;
}
q0 = e0 - (24 * (jv + 1));
// Set up `F[0]` to `F[jx+jk]` where `F[jx+jk] = IPIO2[jv+jk]`:
j = jv - jx;
m = jx + jk;
for ( i = 0; i <= m; i++ ) {
if ( j < 0 ) {
F[ i ] = 0.0;
} else {
F[ i ] = IPIO2[ j ];
}
j += 1;
}
// Compute `Q[0],Q[1],...,Q[jk]`:
for ( i = 0; i <= jk; i++ ) {
fw = 0.0;
for ( j = 0; j <= jx; j++ ) {
fw += x[ j ] * F[ jx + (i-j) ];
}
Q[ i ] = fw;
}
jz = jk;
return compute( x, y, jz, Q, q0, jk, jv, jx, F );
}
// EXPORTS //
module.exports = kernelRempio2;
},{"@stdlib/math/base/special/floor":292,"@stdlib/math/base/special/ldexp":312}],325:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*
*
* ## Notice
*
* The following copyright and license were part of the original implementation available as part of [FreeBSD]{@link https://svnweb.freebsd.org/base/release/9.3.0/lib/msun/src/e_rem_pio2.c}. The implementation follows the original, but has been modified for JavaScript.
*
* ```text
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunPro, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
*
* Optimized by Bruce D. Evans.
* ```
*/
'use strict';
// MODULES //
var getHighWord = require( '@stdlib/number/float64/base/get-high-word' );
var getLowWord = require( '@stdlib/number/float64/base/get-low-word' );
var fromWords = require( '@stdlib/number/float64/base/from-words' );
var rempio2Kernel = require( './kernel_rempio2.js' );
var rempio2Medium = require( './rempio2_medium.js' );
// VARIABLES //
var ZERO = 0.00000000000000000000e+00; // 0x00000000, 0x00000000
var TWO24 = 1.67772160000000000000e+07; // 0x41700000, 0x00000000
// 33 bits of π/2:
var PIO2_1 = 1.57079632673412561417e+00; // 0x3FF921FB, 0x54400000
// PIO2_1T = π/2 - PIO2_1:
var PIO2_1T = 6.07710050650619224932e-11; // 0x3DD0B461, 0x1A626331
var TWO_PIO2_1T = 2.0 * PIO2_1T;
var THREE_PIO2_1T = 3.0 * PIO2_1T;
var FOUR_PIO2_1T = 4.0 * PIO2_1T;
// Absolute value mask: 0x7fffffff = 2147483647 => 01111111111111111111111111111111
var ABS_MASK = 0x7fffffff|0; // asm type annotation
// Exponent mask: 0x7ff00000 = 2146435072 => 01111111111100000000000000000000
var EXPONENT_MASK = 0x7ff00000|0; // asm type annotation
// High word significand mask: 0xfffff = 1048575 => 00000000000011111111111111111111
var SIGNIFICAND_MASK = 0xfffff|0; // asm type annotation
// High word significand for π and π/2: 0x921fb = 598523 => 00000000000010010010000111111011
var PI_HIGH_WORD_SIGNIFICAND = 0x921fb|0; // asm type annotation
// High word for π/4: 0x3fe921fb = 1072243195 => 00111111111010010010000111111011
var PIO4_HIGH_WORD = 0x3fe921fb|0; // asm type annotation
// High word for 3π/4: 0x4002d97c = 1073928572 => 01000000000000101101100101111100
var THREE_PIO4_HIGH_WORD = 0x4002d97c|0; // asm type annotation
// High word for 5π/4: 0x400f6a7a = 1074752122 => 01000000000011110110101001111010
var FIVE_PIO4_HIGH_WORD = 0x400f6a7a|0; // asm type annotation
// High word for 6π/4: 0x4012d97c = 1074977148 => 01000000000100101101100101111100
var THREE_PIO2_HIGH_WORD = 0x4012d97c|0; // asm type annotation
// High word for 7π/4: 0x4015fdbc = 1075183036 => 01000000000101011111110110111100
var SEVEN_PIO4_HIGH_WORD = 0x4015fdbc|0; // asm type annotation
// High word for 8π/4: 0x401921fb = 1075388923 => 01000000000110010010000111111011
var TWO_PI_HIGH_WORD = 0x401921fb|0; // asm type annotation
// High word for 9π/4: 0x401c463b = 1075594811 => 01000000000111000100011000111011
var NINE_PIO4_HIGH_WORD = 0x401c463b|0; // asm type annotation
// 2^20*π/2 = 1647099.3291652855 => 0100000100111001001000011111101101010100010001000010110100011000 => high word => 0x413921fb = 1094263291 => 01000001001110010010000111111011
var MEDIUM = 0x413921fb|0; // asm type annotation
// Arrays for storing temporary values:
var TX = [ 0.0, 0.0, 0.0 ]; // WARNING: not thread safe
var TY = [ 0.0, 0.0 ]; // WARNING: not thread safe
// MAIN //
/**
* Computes `x - nπ/2 = r`.
*
* ## Notes
*
* - Returns `n` and stores the remainder `r` as two numbers `y[0]` and `y[1]`, such that `y[0]+y[1] = r`.
*
*
* @param {number} x - input value
* @param {(Array|TypedArray|Object)} y - remainder elements
* @returns {integer} factor of `π/2`
*
* @example
* var y = [ 0.0, 0.0 ];
* var n = rempio2( 128.0, y );
* // returns 81
*
* var y1 = y[ 0 ];
* // returns ~0.765
*
* var y2 = y[ 1 ];
* // returns ~3.618e-17
*
* @example
* var y = [ 0.0, 0.0 ];
* var n = rempio2( NaN, y );
* // returns 0
*
* var y1 = y[ 0 ];
* // returns NaN
*
* var y2 = y[ 1 ];
* // returns NaN
*/
function rempio2( x, y ) {
var low;
var e0;
var hx;
var ix;
var nx;
var i;
var n;
var z;
hx = getHighWord( x );
ix = (hx & ABS_MASK)|0; // asm type annotation
// Case: |x| ~<= π/4 (no need for reduction)
if ( ix <= PIO4_HIGH_WORD ) {
y[ 0 ] = x;
y[ 1 ] = 0.0;
return 0;
}
// Case: |x| ~<= 5π/4
if ( ix <= FIVE_PIO4_HIGH_WORD ) {
// Case: |x| ~= π/2 or π
if ( (ix & SIGNIFICAND_MASK) === PI_HIGH_WORD_SIGNIFICAND ) {
// Cancellation => use medium case
return rempio2Medium( x, ix, y );
}
// Case: |x| ~<= 3π/4
if ( ix <= THREE_PIO4_HIGH_WORD ) {
if ( x > 0.0 ) {
z = x - PIO2_1;
y[ 0 ] = z - PIO2_1T;
y[ 1 ] = (z - y[0]) - PIO2_1T;
return 1;
}
z = x + PIO2_1;
y[ 0 ] = z + PIO2_1T;
y[ 1 ] = (z - y[0]) + PIO2_1T;
return -1;
}
if ( x > 0.0 ) {
z = x - ( 2.0*PIO2_1 );
y[ 0 ] = z - TWO_PIO2_1T;
y[ 1 ] = (z - y[0]) - TWO_PIO2_1T;
return 2;
}
z = x + ( 2.0*PIO2_1 );
y[ 0 ] = z + TWO_PIO2_1T;
y[ 1 ] = (z - y[0]) + TWO_PIO2_1T;
return -2;
}
// Case: |x| ~<= 9π/4
if ( ix <= NINE_PIO4_HIGH_WORD ) {
// Case: |x| ~<= 7π/4
if ( ix <= SEVEN_PIO4_HIGH_WORD ) {
// Case: |x| ~= 3π/2
if ( ix === THREE_PIO2_HIGH_WORD ) {
return rempio2Medium( x, ix, y );
}
if ( x > 0.0 ) {
z = x - ( 3.0*PIO2_1 );
y[ 0 ] = z - THREE_PIO2_1T;
y[ 1 ] = (z - y[0]) - THREE_PIO2_1T;
return 3;
}
z = x + ( 3.0*PIO2_1 );
y[ 0 ] = z + THREE_PIO2_1T;
y[ 1 ] = (z - y[0]) + THREE_PIO2_1T;
return -3;
}
// Case: |x| ~= 4π/2
if ( ix === TWO_PI_HIGH_WORD ) {
return rempio2Medium( x, ix, y );
}
if ( x > 0.0 ) {
z = x - ( 4.0*PIO2_1 );
y[ 0 ] = z - FOUR_PIO2_1T;
y[ 1 ] = (z - y[0]) - FOUR_PIO2_1T;
return 4;
}
z = x + ( 4.0*PIO2_1 );
y[ 0 ] = z + FOUR_PIO2_1T;
y[ 1 ] = (z - y[0]) + FOUR_PIO2_1T;
return -4;
}
// Case: |x| ~< 2^20*π/2 (medium size)
if ( ix < MEDIUM ) {
return rempio2Medium( x, ix, y );
}
// Case: x is NaN or infinity
if ( ix >= EXPONENT_MASK ) {
y[ 0 ] = NaN;
y[ 1 ] = NaN;
return 0.0;
}
// Set z = scalbn(|x|, ilogb(x)-23)...
low = getLowWord( x );
e0 = (ix >> 20) - 1046; // `e0 = ilogb(z) - 23` => unbiased exponent minus 23
z = fromWords( ix - ((e0 << 20)|0), low );
for ( i = 0; i < 2; i++ ) {
TX[ i ] = z|0;
z = (z - TX[i]) * TWO24;
}
TX[ 2 ] = z;
nx = 3;
while ( TX[ nx-1 ] === ZERO ) {
// Skip zero term...
nx -= 1;
}
n = rempio2Kernel( TX, TY, e0, nx, 1 );
if ( x < 0.0 ) {
y[ 0 ] = -TY[ 0 ];
y[ 1 ] = -TY[ 1 ];
return -n;
}
y[ 0 ] = TY[ 0 ];
y[ 1 ] = TY[ 1 ];
return n;
}
// EXPORTS //
module.exports = rempio2;
},{"./kernel_rempio2.js":324,"./rempio2_medium.js":326,"@stdlib/number/float64/base/from-words":345,"@stdlib/number/float64/base/get-high-word":349,"@stdlib/number/float64/base/get-low-word":351}],326:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*
*
* ## Notice
*
* The following copyright and license were part of the original implementation available as part of [FreeBSD]{@link https://svnweb.freebsd.org/base/release/9.3.0/lib/msun/src/k_rem_pio2.c}. The implementation follows the original, but has been modified for JavaScript.
*
* ```text
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunPro, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ```
*/
'use strict';
// MODULES //
var round = require( '@stdlib/math/base/special/round' );
var getHighWord = require( '@stdlib/number/float64/base/get-high-word' );
// VARIABLES //
// 53 bits of 2/π:
var INVPIO2 = 6.36619772367581382433e-01; // 0x3FE45F30, 0x6DC9C883
// First 33 bits of π/2:
var PIO2_1 = 1.57079632673412561417e+00; // 0x3FF921FB, 0x54400000
// PIO2_1T = π/2 - PIO2_1:
var PIO2_1T = 6.07710050650619224932e-11; // 0x3DD0B461, 0x1A626331
// Another 33 bits of π/2:
var PIO2_2 = 6.07710050630396597660e-11; // 0x3DD0B461, 0x1A600000
// PIO2_2T = π/2 - ( PIO2_1 + PIO2_2 ):
var PIO2_2T = 2.02226624879595063154e-21; // 0x3BA3198A, 0x2E037073
// Another 33 bits of π/2:
var PIO2_3 = 2.02226624871116645580e-21; // 0x3BA3198A, 0x2E000000
// PIO2_3T = π/2 - ( PIO2_1 + PIO2_2 + PIO2_3 ):
var PIO2_3T = 8.47842766036889956997e-32; // 0x397B839A, 0x252049C1
// Exponent mask (2047 => 0x7ff):
var EXPONENT_MASK = 0x7ff|0; // asm type annotation
// MAIN //
/**
* Computes `x - nπ/2 = r` for medium-sized inputs.
*
* @private
* @param {number} x - input value
* @param {uint32} ix - high word of `x`
* @param {(Array|TypedArray|Object)} y - remainder elements
* @returns {integer} factor of `π/2`
*/
function rempio2Medium( x, ix, y ) {
var high;
var n;
var t;
var r;
var w;
var i;
var j;
n = round( x * INVPIO2 );
r = x - ( n * PIO2_1 );
w = n * PIO2_1T;
// First rounding (good to 85 bits)...
j = (ix >> 20)|0; // asm type annotation
y[ 0 ] = r - w;
high = getHighWord( y[0] );
i = j - ( (high >> 20) & EXPONENT_MASK );
// Check if a second iteration is needed (good to 118 bits)...
if ( i > 16 ) {
t = r;
w = n * PIO2_2;
r = t - w;
w = (n * PIO2_2T) - ((t-r) - w);
y[ 0 ] = r - w;
high = getHighWord( y[0] );
i = j - ( (high >> 20) & EXPONENT_MASK );
// Check if a third iteration is needed (151 bits accumulated)...
if ( i > 49 ) {
t = r;
w = n * PIO2_3;
r = t - w;
w = (n * PIO2_3T) - ((t-r) - w);
y[ 0 ] = r - w;
}
}
y[ 1 ] = (r - y[0]) - w;
return n;
}
// EXPORTS //
module.exports = rempio2Medium;
},{"@stdlib/math/base/special/round":327,"@stdlib/number/float64/base/get-high-word":349}],327:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// TODO: implementation
/**
* Round a numeric value to the nearest integer.
*
* @module @stdlib/math/base/special/round
*
* @example
* var round = require( '@stdlib/math/base/special/round' );
*
* var v = round( -4.2 );
* // returns -4.0
*
* v = round( -4.5 );
* // returns -4.0
*
* v = round( -4.6 );
* // returns -5.0
*
* v = round( 9.99999 );
* // returns 10.0
*
* v = round( 9.5 );
* // returns 10.0
*
* v = round( 9.2 );
* // returns 9.0
*
* v = round( 0.0 );
* // returns 0.0
*
* v = round( -0.0 );
* // returns -0.0
*
* v = round( Infinity );
* // returns Infinity
*
* v = round( -Infinity );
* // returns -Infinity
*
* v = round( NaN );
* // returns NaN
*/
// MODULES //
var round = require( './round.js' );
// EXPORTS //
module.exports = round;
},{"./round.js":328}],328:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// TODO: implementation
/**
* Rounds a numeric value to the nearest integer.
*
* @param {number} x - input value
* @returns {number} function value
*
* @example
* var v = round( -4.2 );
* // returns -4.0
*
* @example
* var v = round( -4.5 );
* // returns -4.0
*
* @example
* var v = round( -4.6 );
* // returns -5.0
*
* @example
* var v = round( 9.99999 );
* // returns 10.0
*
* @example
* var v = round( 9.5 );
* // returns 10.0
*
* @example
* var v = round( 9.2 );
* // returns 9.0
*
* @example
* var v = round( 0.0 );
* // returns 0.0
*
* @example
* var v = round( -0.0 );
* // returns -0.0
*
* @example
* var v = round( Infinity );
* // returns Infinity
*
* @example
* var v = round( -Infinity );
* // returns -Infinity
*
* @example
* var v = round( NaN );
* // returns NaN
*/
var round = Math.round; // eslint-disable-line stdlib/no-builtin-math
// EXPORTS //
module.exports = round;
},{}],329:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Evaluate the signum function for a double-precision floating-point number.
*
* @module @stdlib/math/base/special/signum
*
* @example
* var signum = require( '@stdlib/math/base/special/signum' );
*
* var sign = signum( -5.0 );
* // returns -1.0
*
* sign = signum( 5.0 );
* // returns 1.0
*
* sign = signum( -0.0 );
* // returns -0.0
*
* sign = signum( 0.0 );
* // returns 0.0
*
* sign = signum( NaN );
* // returns NaN
*/
// MODULES //
var signum = require( './main.js' );
// EXPORTS //
module.exports = signum;
},{"./main.js":330}],330:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isnan = require( '@stdlib/math/base/assert/is-nan' );
// MAIN //
/**
* Evaluates the signum function for a double-precision floating-point number.
*
* @param {number} x - input value
* @returns {number} function value
*
* @example
* var sign = signum( -5.0 );
* // returns -1.0
*
* @example
* var sign = signum( 5.0 );
* // returns 1.0
*
* @example
* var sign = signum( -0.0 );
* // returns -0.0
*
* @example
* var sign = signum( 0.0 );
* // returns 0.0
*
* @example
* var sign = signum( NaN );
* // returns NaN
*/
function signum( x ) {
if ( x === 0.0 || isnan( x ) ) {
return x; // addresses both +-0
}
return ( x < 0.0 ) ? -1.0 : 1.0;
}
// EXPORTS //
module.exports = signum;
},{"@stdlib/math/base/assert/is-nan":272}],331:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Compute the sine of a number.
*
* @module @stdlib/math/base/special/sin
*
* @example
* var sin = require( '@stdlib/math/base/special/sin' );
*
* var v = sin( 0.0 );
* // returns ~0.0
*
* v = sin( 3.141592653589793/2.0 );
* // returns ~1.0
*
* v = sin( -3.141592653589793/6.0 );
* // returns ~-0.5
*
* v = sin( NaN );
* // returns NaN
*/
// MODULES //
var sin = require( './sin.js' );
// EXPORTS //
module.exports = sin;
},{"./sin.js":332}],332:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*
*
* ## Notice
*
* The following copyright, license, and long comment were part of the original implementation available as part of [FreeBSD]{@link https://svnweb.freebsd.org/base/release/9.3.0/lib/msun/src/s_sin.c}. The implementation follows the original, but has been modified for JavaScript.
*
* ```text
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunPro, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ```
*/
'use strict';
// MODULES //
var getHighWord = require( '@stdlib/number/float64/base/get-high-word' );
var kernelCos = require( '@stdlib/math/base/special/kernel-cos' );
var kernelSin = require( '@stdlib/math/base/special/kernel-sin' );
var rempio2 = require( '@stdlib/math/base/special/rempio2' );
// VARIABLES //
// Absolute value mask: 0x7fffffff = 2147483647 => 01111111111111111111111111111111
var ABS_MASK = 0x7fffffff|0; // asm type annotation
// Exponent mask: 0x7ff00000 = 2146435072 => 01111111111100000000000000000000
var EXPONENT_MASK = 0x7ff00000|0; // asm type annotation
// High word for PI/4: 0x3fe921fb = 1072243195 => 00111111111010010010000111111011
var PIO4_HIGH_WORD = 0x3fe921fb|0; // asm type annotation
// 2^-26 = 1.4901161193847656e-8 => 0011111001010000000000000000000000000000000000000000000000000000 => high word => 00111110010100000000000000000000 => 0x3e500000 = 1045430272
var SMALL_HIGH_WORD = 0x3e500000|0; // asm type annotation
// Array for storing remainder elements:
var Y = [ 0.0, 0.0 ]; // WARNING: not thread safe
// MAIN //
/**
* Computes the sine of a number.
*
* ## Method
*
* - Let \\(S\\), \\(C\\), and \\(T\\) denote the \\(\sin\\), \\(\cos\\), and \\(\tan\\), respectively, on \\(\[-\pi/4, +\pi/4\]\\).
*
* - Reduce the argument \\(x\\) to \\(y1+y2 = x-k\pi/2\\) in \\(\[-\pi/4, +\pi/4\]\\), and let \\(n = k \mod 4\\).
*
* - We have
*
* | n | sin(x) | cos(x) | tan(x) |
* | - | ------ | ------ | ------ |
* | 0 | S | C | T |
* | 1 | C | -S | -1/T |
* | 2 | -S | -C | T |
* | 3 | -C | S | -1/T |
*
*
* @param {number} x - input value (in radians)
* @returns {number} sine
*
* @example
* var v = sin( 0.0 );
* // returns ~0.0
*
* @example
* var v = sin( 3.141592653589793/2.0 );
* // returns ~1.0
*
* @example
* var v = sin( -3.141592653589793/6.0 );
* // returns ~-0.5
*
* @example
* var v = sin( NaN );
* // returns NaN
*/
function sin( x ) {
var ix;
var n;
ix = getHighWord( x );
ix &= ABS_MASK;
// Case: |x| ~< π/4
if ( ix <= PIO4_HIGH_WORD ) {
// Case: |x| ~< 2^-26
if ( ix < SMALL_HIGH_WORD ) {
return x;
}
return kernelSin( x, 0.0 );
}
// Case: x is NaN or infinity
if ( ix >= EXPONENT_MASK ) {
return NaN;
}
// Argument reduction...
n = rempio2( x, Y );
switch ( n & 3 ) {
case 0:
return kernelSin( Y[ 0 ], Y[ 1 ] );
case 1:
return kernelCos( Y[ 0 ], Y[ 1 ] );
case 2:
return -kernelSin( Y[ 0 ], Y[ 1 ] );
default:
return -kernelCos( Y[ 0 ], Y[ 1 ] );
}
}
// EXPORTS //
module.exports = sin;
},{"@stdlib/math/base/special/kernel-cos":306,"@stdlib/math/base/special/kernel-sin":310,"@stdlib/math/base/special/rempio2":323,"@stdlib/number/float64/base/get-high-word":349}],333:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Compute the value of `sin(πx)`.
*
* @module @stdlib/math/base/special/sinpi
*
* @example
* var sinpi = require( '@stdlib/math/base/special/sinpi' );
*
* var y = sinpi( 0.0 );
* // returns 0.0
*
* y = sinpi( 0.5 );
* // returns 1.0
*
* y = sinpi( 0.9 );
* // returns ~0.309
*
* y = sinpi( NaN );
* // returns NaN
*/
// MODULES //
var sinpi = require( './sinpi.js' );
// EXPORTS //
module.exports = sinpi;
},{"./sinpi.js":334}],334:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/*
* Notes:
* => sin(-x) = -sin(x)
* => sin(+n) = +0, where `n` is a positive integer
* => sin(-n) = -sin(+n) = -0, where `n` is a positive integer
* => cos(-x) = cos(x)
*/
// MODULES //
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var isInfinite = require( '@stdlib/math/base/assert/is-infinite' );
var cos = require( '@stdlib/math/base/special/cos' );
var sin = require( '@stdlib/math/base/special/sin' );
var abs = require( '@stdlib/math/base/special/abs' );
var copysign = require( '@stdlib/math/base/special/copysign' );
var PI = require( '@stdlib/constants/float64/pi' );
// MAIN //
/**
* Computes the value of `sin(πx)`.
*
* @param {number} x - input value
* @returns {number} function value
*
* @example
* var y = sinpi( 0.0 );
* // returns 0.0
*
* @example
* var y = sinpi( 0.5 );
* // returns 1.0
*
* @example
* var y = sinpi( 0.9 );
* // returns ~0.309
*
* @example
* var y = sinpi( NaN );
* // returns NaN
*/
function sinpi( x ) {
var ar;
var r;
if ( isnan( x ) ) {
return NaN;
}
if ( isInfinite( x ) ) {
return NaN;
}
// Argument reduction (reduce to [0,2))...
r = x % 2.0; // sign preserving
ar = abs( r );
// If `x` is an integer, the mod is an integer...
if ( ar === 0.0 || ar === 1.0 ) {
return copysign( 0.0, r );
}
if ( ar < 0.25 ) {
return sin( PI*r );
}
// In each of the following, we further reduce to [-π/4,π/4)...
if ( ar < 0.75 ) {
ar = 0.5 - ar;
return copysign( cos( PI*ar ), r );
}
if ( ar < 1.25 ) {
r = copysign( 1.0, r ) - r;
return sin( PI*r );
}
if ( ar < 1.75 ) {
ar -= 1.5;
return -copysign( cos( PI*ar ), r );
}
r -= copysign( 2.0, r );
return sin( PI*r );
}
// EXPORTS //
module.exports = sinpi;
},{"@stdlib/constants/float64/pi":254,"@stdlib/math/base/assert/is-infinite":268,"@stdlib/math/base/assert/is-nan":272,"@stdlib/math/base/special/abs":278,"@stdlib/math/base/special/copysign":283,"@stdlib/math/base/special/cos":285,"@stdlib/math/base/special/sin":331}],335:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Compute the principal square root of a double-precision floating-point number.
*
* @module @stdlib/math/base/special/sqrt
*
* @example
* var sqrt = require( '@stdlib/math/base/special/sqrt' );
*
* var v = sqrt( 4.0 );
* // returns 2.0
*
* v = sqrt( 9.0 );
* // returns 3.0
*
* v = sqrt( 0.0 );
* // returns 0.0
*
* v = sqrt( -4.0 );
* // returns NaN
*
* v = sqrt( NaN );
* // returns NaN
*/
// MODULES //
var sqrt = require( './main.js' );
// EXPORTS //
module.exports = sqrt;
},{"./main.js":336}],336:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Compute the principal square root of a double-precision floating-point number.
*
* @type {Function}
* @param {number} x - input value
* @returns {number} principal square root
*
* @example
* var v = sqrt( 4.0 );
* // returns 2.0
*
* v = sqrt( 9.0 );
* // returns 3.0
*
* v = sqrt( 0.0 );
* // returns 0.0
*
* v = sqrt( -4.0 );
* // returns NaN
*
* v = sqrt( NaN );
* // returns NaN
*/
var sqrt = Math.sqrt; // eslint-disable-line stdlib/no-builtin-math
// EXPORTS //
module.exports = sqrt;
},{}],337:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Round a double-precision floating-point number toward zero.
*
* @module @stdlib/math/base/special/trunc
*
* @example
* var trunc = require( '@stdlib/math/base/special/trunc' );
*
* var v = trunc( -4.2 );
* // returns -4.0
*
* v = trunc( 9.99999 );
* // returns 9.0
*
* v = trunc( 0.0 );
* // returns 0.0
*
* v = trunc( -0.0 );
* // returns -0.0
*
* v = trunc( NaN );
* // returns NaN
*
* v = trunc( Infinity );
* // returns Infinity
*
* v = trunc( -Infinity );
* // returns -Infinity
*/
// MODULES //
var trunc = require( './main.js' );
// EXPORTS //
module.exports = trunc;
},{"./main.js":338}],338:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var floor = require( '@stdlib/math/base/special/floor' );
var ceil = require( '@stdlib/math/base/special/ceil' );
// MAIN //
/**
* Rounds a double-precision floating-point number toward zero.
*
* @param {number} x - input value
* @returns {number} rounded value
*
* @example
* var v = trunc( -4.2 );
* // returns -4.0
*
* @example
* var v = trunc( 9.99999 );
* // returns 9.0
*
* @example
* var v = trunc( 0.0 );
* // returns 0.0
*
* @example
* var v = trunc( -0.0 );
* // returns -0.0
*
* @example
* var v = trunc( NaN );
* // returns NaN
*
* @example
* var v = trunc( Infinity );
* // returns Infinity
*
* @example
* var v = trunc( -Infinity );
* // returns -Infinity
*/
function trunc( x ) {
if ( x < 0.0 ) {
return ceil( x );
}
return floor( x );
}
// EXPORTS //
module.exports = trunc;
},{"@stdlib/math/base/special/ceil":280,"@stdlib/math/base/special/floor":292}],339:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Perform C-like multiplication of two unsigned 32-bit integers.
*
* @module @stdlib/math/base/special/uimul
*
* @example
* var uimul = require( '@stdlib/math/base/special/uimul' );
*
* var v = uimul( 10>>>0, 4>>>0 );
* // returns 40
*/
// MODULES //
var uimul = require( './main.js' );
// EXPORTS //
module.exports = uimul;
},{"./main.js":340}],340:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// VARIABLES //
// Define a mask for the least significant 16 bits (low word): 65535 => 0x0000ffff => 00000000000000001111111111111111
var LOW_WORD_MASK = 0x0000ffff>>>0; // asm type annotation
// MAIN //
/**
* Performs C-like multiplication of two unsigned 32-bit integers.
*
* ## Method
*
* - To emulate C-like multiplication without the aid of 64-bit integers, we recognize that a 32-bit integer can be split into two 16-bit words
*
* ```tex
* a = w_h*2^{16} + w_l
* ```
*
* where \\( w_h \\) is the most significant 16 bits and \\( w_l \\) is the least significant 16 bits. For example, consider the maximum unsigned 32-bit integer \\( 2^{32}-1 \\)
*
* ```binarystring
* 11111111111111111111111111111111
* ```
*
* The 16-bit high word is then
*
* ```binarystring
* 1111111111111111
* ```
*
* and the 16-bit low word
*
* ```binarystring
* 1111111111111111
* ```
*
* If we cast the high word to 32-bit precision and multiply by \\( 2^{16} \\) (equivalent to a 16-bit left shift), then the bit sequence is
*
* ```binarystring
* 11111111111111110000000000000000
* ```
*
* Similarly, upon casting the low word to 32-bit precision, the bit sequence is
*
* ```binarystring
* 00000000000000001111111111111111
* ```
*
* From the rules of binary addition, we recognize that adding the two 32-bit values for the high and low words will return our original value \\( 2^{32}-1 \\).
*
* - Accordingly, the multiplication of two 32-bit integers can be expressed
*
* ```tex
* \begin{align*}
* a \cdot b &= ( a_h \cdot 2^{16} + a_l) \cdot ( b_h \cdot 2^{16} + b_l) \\
* &= a_l \cdot b_l + a_h \cdot b_l \cdot 2^{16} + a_l \cdot b_h \cdot 2^{16} + (a_h \cdot b_h) \cdot 2^{32} \\
* &= a_l \cdot b_l + (a_h \cdot b_l + a_l \cdot b_h) \cdot 2^{16} + (a_h \cdot b_h) \cdot 2^{32}
* \end{align*}
* ```
*
* - We note that multiplying (dividing) an integer by \\( 2^n \\) is equivalent to performing a left (right) shift of \\( n \\) bits.
*
* - Further, as we want to return an integer of the same precision, for a 32-bit integer, the return value will be modulo \\( 2^{32} \\). Stated another way, we only care about the low word of a 64-bit result.
*
* - Accordingly, the last term, being evenly divisible by \\( 2^{32} \\), drops from the equation leaving the remaining two terms as the remainder.
*
* ```tex
* a \cdot b = a_l \cdot b_l + (a_h \cdot b_l + a_l \cdot b_h) << 16
* ```
*
* - Lastly, the second term in the above equation contributes to the middle bits and may cause the product to "overflow". However, we can disregard (`>>>0`) overflow bits due modulo arithmetic, as discussed earlier with regard to the term involving the partial product of high words.
*
*
* @param {uinteger32} a - integer
* @param {uinteger32} b - integer
* @returns {uinteger32} product
*
* @example
* var v = uimul( 10>>>0, 4>>>0 );
* // returns 40
*/
function uimul( a, b ) {
var lbits;
var mbits;
var ha;
var hb;
var la;
var lb;
a >>>= 0; // asm type annotation
b >>>= 0; // asm type annotation
// Isolate the most significant 16-bits:
ha = ( a>>>16 )>>>0; // asm type annotation
hb = ( b>>>16 )>>>0; // asm type annotation
// Isolate the least significant 16-bits:
la = ( a&LOW_WORD_MASK )>>>0; // asm type annotation
lb = ( b&LOW_WORD_MASK )>>>0; // asm type annotation
// Compute partial sums:
lbits = ( la*lb )>>>0; // asm type annotation; no integer overflow possible
mbits = ( ((ha*lb) + (la*hb))<<16 )>>>0; // asm type annotation; possible integer overflow
// The final `>>>0` converts the intermediate sum to an unsigned integer (possible integer overflow during sum):
return ( lbits + mbits )>>>0; // asm type annotation
}
// EXPORTS //
module.exports = uimul;
},{}],341:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Constructor which returns a `Number` object.
*
* @module @stdlib/number/ctor
*
* @example
* var Number = require( '@stdlib/number/ctor' );
*
* var v = new Number( 10.0 );
* // returns <Number>
*/
// MODULES //
var Number = require( './number.js' );
// EXPORTS //
module.exports = Number;
},{"./number.js":342}],342:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// EXPORTS //
module.exports = Number; // eslint-disable-line stdlib/require-globals
},{}],343:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Return an integer corresponding to the unbiased exponent of a double-precision floating-point number.
*
* @module @stdlib/number/float64/base/exponent
*
* @example
* var exponent = require( '@stdlib/number/float64/base/exponent' );
*
* var exp = exponent( 3.14e-307 ); // => 2**-1019 ~ 1e-307
* // returns -1019
*
* exp = exponent( -3.14 );
* // returns 1
*
* exp = exponent( 0.0 );
* // returns -1023
*
* exp = exponent( NaN );
* // returns 1024
*/
// MODULES //
var exponent = require( './main.js' );
// EXPORTS //
module.exports = exponent;
},{"./main.js":344}],344:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var getHighWord = require( '@stdlib/number/float64/base/get-high-word' );
var EXP_MASK = require( '@stdlib/constants/float64/high-word-exponent-mask' );
var BIAS = require( '@stdlib/constants/float64/exponent-bias' );
// MAIN //
/**
* Returns an integer corresponding to the unbiased exponent of a double-precision floating-point number.
*
* @param {number} x - input value
* @returns {integer32} unbiased exponent
*
* @example
* var exp = exponent( 3.14e-307 ); // => 2**-1019 ~ 1e-307
* // returns -1019
*
* @example
* var exp = exponent( -3.14 );
* // returns 1
*
* @example
* var exp = exponent( 0.0 );
* // returns -1023
*
* @example
* var exp = exponent( NaN );
* // returns 1024
*/
function exponent( x ) {
// Extract from the input value a higher order word (unsigned 32-bit integer) which contains the exponent:
var high = getHighWord( x );
// Apply a mask to isolate only the exponent bits and then shift off all bits which are part of the fraction:
high = ( high & EXP_MASK ) >>> 20;
// Remove the bias and return:
return (high - BIAS)|0; // asm type annotation
}
// EXPORTS //
module.exports = exponent;
},{"@stdlib/constants/float64/exponent-bias":245,"@stdlib/constants/float64/high-word-exponent-mask":246,"@stdlib/number/float64/base/get-high-word":349}],345:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Create a double-precision floating-point number from a higher order word (unsigned 32-bit integer) and a lower order word (unsigned 32-bit integer).
*
* @module @stdlib/number/float64/base/from-words
*
* @example
* var fromWords = require( '@stdlib/number/float64/base/from-words' );
*
* var v = fromWords( 1774486211, 2479577218 );
* // returns 3.14e201
*
* v = fromWords( 3221823995, 1413754136 );
* // returns -3.141592653589793
*
* v = fromWords( 0, 0 );
* // returns 0.0
*
* v = fromWords( 2147483648, 0 );
* // returns -0.0
*
* v = fromWords( 2146959360, 0 );
* // returns NaN
*
* v = fromWords( 2146435072, 0 );
* // returns Infinity
*
* v = fromWords( 4293918720, 0 );
* // returns -Infinity
*/
// MODULES //
var fromWords = require( './main.js' );
// EXPORTS //
module.exports = fromWords;
},{"./main.js":347}],346:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isLittleEndian = require( '@stdlib/assert/is-little-endian' );
// MAIN //
var indices;
var HIGH;
var LOW;
if ( isLittleEndian === true ) {
HIGH = 1; // second index
LOW = 0; // first index
} else {
HIGH = 0; // first index
LOW = 1; // second index
}
indices = {
'HIGH': HIGH,
'LOW': LOW
};
// EXPORTS //
module.exports = indices;
},{"@stdlib/assert/is-little-endian":116}],347:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var Uint32Array = require( '@stdlib/array/uint32' );
var Float64Array = require( '@stdlib/array/float64' );
var indices = require( './indices.js' );
// VARIABLES //
var FLOAT64_VIEW = new Float64Array( 1 );
var UINT32_VIEW = new Uint32Array( FLOAT64_VIEW.buffer );
var HIGH = indices.HIGH;
var LOW = indices.LOW;
// MAIN //
/**
* Creates a double-precision floating-point number from a higher order word (unsigned 32-bit integer) and a lower order word (unsigned 32-bit integer).
*
* ## Notes
*
* ```text
* float64 (64 bits)
* f := fraction (significand/mantissa) (52 bits)
* e := exponent (11 bits)
* s := sign bit (1 bit)
*
* |-------- -------- -------- -------- -------- -------- -------- --------|
* | Float64 |
* |-------- -------- -------- -------- -------- -------- -------- --------|
* | Uint32 | Uint32 |
* |-------- -------- -------- -------- -------- -------- -------- --------|
* ```
*
* If little endian (more significant bits last):
*
* ```text
* <-- lower higher -->
* | f7 f6 f5 f4 f3 f2 e2 | f1 |s| e1 |
* ```
*
* If big endian (more significant bits first):
*
* ```text
* <-- higher lower -->
* |s| e1 e2 | f1 f2 f3 f4 f5 f6 f7 |
* ```
*
*
* In which Uint32 should we place the higher order bits? If little endian, the second; if big endian, the first.
*
*
* ## References
*
* - [Open Group][1]
*
* [1]: http://pubs.opengroup.org/onlinepubs/9629399/chap14.htm
*
* @param {uinteger32} high - higher order word (unsigned 32-bit integer)
* @param {uinteger32} low - lower order word (unsigned 32-bit integer)
* @returns {number} floating-point number
*
* @example
* var v = fromWords( 1774486211, 2479577218 );
* // returns 3.14e201
*
* @example
* var v = fromWords( 3221823995, 1413754136 );
* // returns -3.141592653589793
*
* @example
* var v = fromWords( 0, 0 );
* // returns 0.0
*
* @example
* var v = fromWords( 2147483648, 0 );
* // returns -0.0
*
* @example
* var v = fromWords( 2146959360, 0 );
* // returns NaN
*
* @example
* var v = fromWords( 2146435072, 0 );
* // returns Infinity
*
* @example
* var v = fromWords( 4293918720, 0 );
* // returns -Infinity
*/
function fromWords( high, low ) {
UINT32_VIEW[ HIGH ] = high;
UINT32_VIEW[ LOW ] = low;
return FLOAT64_VIEW[ 0 ];
}
// EXPORTS //
module.exports = fromWords;
},{"./indices.js":346,"@stdlib/array/float64":5,"@stdlib/array/uint32":23}],348:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isLittleEndian = require( '@stdlib/assert/is-little-endian' );
// MAIN //
var HIGH;
if ( isLittleEndian === true ) {
HIGH = 1; // second index
} else {
HIGH = 0; // first index
}
// EXPORTS //
module.exports = HIGH;
},{"@stdlib/assert/is-little-endian":116}],349:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Return an unsigned 32-bit integer corresponding to the more significant 32 bits of a double-precision floating-point number.
*
* @module @stdlib/number/float64/base/get-high-word
*
* @example
* var getHighWord = require( '@stdlib/number/float64/base/get-high-word' );
*
* var w = getHighWord( 3.14e201 ); // => 01101001110001001000001011000011
* // returns 1774486211
*/
// MODULES //
var getHighWord = require( './main.js' );
// EXPORTS //
module.exports = getHighWord;
},{"./main.js":350}],350:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var Uint32Array = require( '@stdlib/array/uint32' );
var Float64Array = require( '@stdlib/array/float64' );
var HIGH = require( './high.js' );
// VARIABLES //
var FLOAT64_VIEW = new Float64Array( 1 );
var UINT32_VIEW = new Uint32Array( FLOAT64_VIEW.buffer );
// MAIN //
/**
* Returns an unsigned 32-bit integer corresponding to the more significant 32 bits of a double-precision floating-point number.
*
* ## Notes
*
* ```text
* float64 (64 bits)
* f := fraction (significand/mantissa) (52 bits)
* e := exponent (11 bits)
* s := sign bit (1 bit)
*
* |-------- -------- -------- -------- -------- -------- -------- --------|
* | Float64 |
* |-------- -------- -------- -------- -------- -------- -------- --------|
* | Uint32 | Uint32 |
* |-------- -------- -------- -------- -------- -------- -------- --------|
* ```
*
* If little endian (more significant bits last):
*
* ```text
* <-- lower higher -->
* | f7 f6 f5 f4 f3 f2 e2 | f1 |s| e1 |
* ```
*
* If big endian (more significant bits first):
*
* ```text
* <-- higher lower -->
* |s| e1 e2 | f1 f2 f3 f4 f5 f6 f7 |
* ```
*
* In which Uint32 can we find the higher order bits? If little endian, the second; if big endian, the first.
*
*
* ## References
*
* - [Open Group][1]
*
* [1]: http://pubs.opengroup.org/onlinepubs/9629399/chap14.htm
*
* @param {number} x - input value
* @returns {uinteger32} higher order word
*
* @example
* var w = getHighWord( 3.14e201 ); // => 01101001110001001000001011000011
* // returns 1774486211
*/
function getHighWord( x ) {
FLOAT64_VIEW[ 0 ] = x;
return UINT32_VIEW[ HIGH ];
}
// EXPORTS //
module.exports = getHighWord;
},{"./high.js":348,"@stdlib/array/float64":5,"@stdlib/array/uint32":23}],351:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Return an unsigned 32-bit integer corresponding to the less significant 32 bits of a double-precision floating-point number.
*
* @module @stdlib/number/float64/base/get-low-word
*
* @example
* var getLowWord = require( '@stdlib/number/float64/base/get-low-word' );
*
* var w = getLowWord( 3.14e201 ); // => 10010011110010110101100010000010
* // returns 2479577218
*/
// MODULES //
var getLowWord = require( './main.js' );
// EXPORTS //
module.exports = getLowWord;
},{"./main.js":353}],352:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isLittleEndian = require( '@stdlib/assert/is-little-endian' );
// MAIN //
var LOW;
if ( isLittleEndian === true ) {
LOW = 0; // first index
} else {
LOW = 1; // second index
}
// EXPORTS //
module.exports = LOW;
},{"@stdlib/assert/is-little-endian":116}],353:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var Uint32Array = require( '@stdlib/array/uint32' );
var Float64Array = require( '@stdlib/array/float64' );
var LOW = require( './low.js' );
// VARIABLES //
var FLOAT64_VIEW = new Float64Array( 1 );
var UINT32_VIEW = new Uint32Array( FLOAT64_VIEW.buffer );
// MAIN //
/**
* Returns a 32-bit unsigned integer corresponding to the less significant 32 bits of a double-precision floating-point number.
*
* ## Notes
*
* ```text
* float64 (64 bits)
* f := fraction (significand/mantissa) (52 bits)
* e := exponent (11 bits)
* s := sign bit (1 bit)
*
* |-------- -------- -------- -------- -------- -------- -------- --------|
* | Float64 |
* |-------- -------- -------- -------- -------- -------- -------- --------|
* | Uint32 | Uint32 |
* |-------- -------- -------- -------- -------- -------- -------- --------|
* ```
*
* If little endian (more significant bits last):
*
* ```text
* <-- lower higher -->
* | f7 f6 f5 f4 f3 f2 e2 | f1 |s| e1 |
* ```
*
* If big endian (more significant bits first):
*
* ```text
* <-- higher lower -->
* |s| e1 e2 | f1 f2 f3 f4 f5 f6 f7 |
* ```
*
* In which Uint32 can we find the lower order bits? If little endian, the first; if big endian, the second.
*
*
* ## References
*
* - [Open Group][1]
*
* [1]: http://pubs.opengroup.org/onlinepubs/9629399/chap14.htm
*
* @param {number} x - input value
* @returns {uinteger32} lower order word
*
* @example
* var w = getLowWord( 3.14e201 ); // => 10010011110010110101100010000010
* // returns 2479577218
*/
function getLowWord( x ) {
FLOAT64_VIEW[ 0 ] = x;
return UINT32_VIEW[ LOW ];
}
// EXPORTS //
module.exports = getLowWord;
},{"./low.js":352,"@stdlib/array/float64":5,"@stdlib/array/uint32":23}],354:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Return a normal number `y` and exponent `exp` satisfying \\(x = y \cdot 2^\mathrm{exp}\\).
*
* @module @stdlib/number/float64/base/normalize
*
* @example
* var normalize = require( '@stdlib/number/float64/base/normalize' );
* var pow = require( '@stdlib/math/base/special/pow' );
*
* var out = normalize( 3.14e-319 );
* // returns [ 1.4141234400356668e-303, -52 ]
*
* var y = out[ 0 ];
* var exp = out[ 1 ];
*
* var bool = ( y*pow(2.0,exp) === 3.14e-319 );
* // returns true
*
* @example
* var Float64Array = require( '@stdlib/array/float64' );
* var normalize = require( '@stdlib/number/float64/base/normalize' );
*
* var out = new Float64Array( 2 );
*
* var v = normalize( out, 3.14e-319 );
* // returns <Float64Array>[ 1.4141234400356668e-303, -52 ]
*
* var bool = ( v === out );
* // returns true
*/
// MODULES //
var normalize = require( './main.js' );
// EXPORTS //
module.exports = normalize;
},{"./main.js":355}],355:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var fcn = require( './normalize.js' );
// MAIN //
/**
* Returns a normal number `y` and exponent `exp` satisfying \\(x = y \cdot 2^\mathrm{exp}\\).
*
* @param {(Array|TypedArray|Object)} [out] - output array
* @param {number} x - input value
* @returns {(Array|TypedArray|Object)} output array
*
* @example
* var pow = require( '@stdlib/math/base/special/pow' );
*
* var out = normalize( [ 0.0, 0 ], 3.14e-319 );
* // returns [ 1.4141234400356668e-303, -52 ]
*
* var y = out[ 0 ];
* var exp = out[ 1 ];
*
* var bool = ( y*pow(2.0,exp) === 3.14e-319 );
* // returns true
*
* @example
* var Float64Array = require( '@stdlib/array/float64' );
* var pow = require( '@stdlib/math/base/special/pow' );
*
* var out = new Float64Array( 2 );
*
* var v = normalize( out, 3.14e-319 );
* // returns <Float64Array>[ 1.4141234400356668e-303, -52 ]
*
* var bool = ( v === out );
* // returns true
*
* @example
* var out = normalize( [ 0.0, 0 ], 0.0 );
* // returns [ 0.0, 0 ]
*
* @example
* var out = normalize( [ 0.0, 0 ], Infinity );
* // returns [ Infinity, 0 ]
*
* @example
* var out = normalize( [ 0.0, 0 ], -Infinity );
* // returns [ -Infinity, 0 ]
*
* @example
* var out = normalize( [ 0.0, 0 ], NaN );
* // returns [ NaN, 0 ]
*/
function normalize( out, x ) {
if ( arguments.length === 1 ) {
return fcn( [ 0.0, 0 ], out );
}
return fcn( out, x );
}
// EXPORTS //
module.exports = normalize;
},{"./normalize.js":356}],356:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var FLOAT64_SMALLEST_NORMAL = require( '@stdlib/constants/float64/smallest-normal' );
var isInfinite = require( '@stdlib/math/base/assert/is-infinite' );
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var abs = require( '@stdlib/math/base/special/abs' );
// VARIABLES //
// (1<<52)
var SCALAR = 4503599627370496;
// MAIN //
/**
* Returns a normal number `y` and exponent `exp` satisfying \\(x = y \cdot 2^\mathrm{exp}\\).
*
* @private
* @param {(Array|TypedArray|Object)} out - output array
* @param {number} x - input value
* @returns {(Array|TypedArray|Object)} output array
*
* @example
* var pow = require( '@stdlib/math/base/special/pow' );
*
* var out = normalize( [ 0.0, 0 ], 3.14e-319 );
* // returns [ 1.4141234400356668e-303, -52 ]
*
* var y = out[ 0 ];
* var exp = out[ 1 ];
*
* var bool = ( y*pow(2.0,exp) === 3.14e-319 );
* // returns true
*
* @example
* var out = normalize( [ 0.0, 0 ], 0.0 );
* // returns [ 0.0, 0 ];
*
* @example
* var out = normalize( [ 0.0, 0 ], Infinity );
* // returns [ Infinity, 0 ]
*
* @example
* var out = normalize( [ 0.0, 0 ], -Infinity );
* // returns [ -Infinity, 0 ]
*
* @example
* var out = normalize( [ 0.0, 0 ], NaN );
* // returns [ NaN, 0 ]
*/
function normalize( out, x ) {
if ( isnan( x ) || isInfinite( x ) ) {
out[ 0 ] = x;
out[ 1 ] = 0;
return out;
}
if ( x !== 0.0 && abs( x ) < FLOAT64_SMALLEST_NORMAL ) {
out[ 0 ] = x * SCALAR;
out[ 1 ] = -52;
return out;
}
out[ 0 ] = x;
out[ 1 ] = 0;
return out;
}
// EXPORTS //
module.exports = normalize;
},{"@stdlib/constants/float64/smallest-normal":256,"@stdlib/math/base/assert/is-infinite":268,"@stdlib/math/base/assert/is-nan":272,"@stdlib/math/base/special/abs":278}],357:[function(require,module,exports){
arguments[4][348][0].apply(exports,arguments)
},{"@stdlib/assert/is-little-endian":116,"dup":348}],358:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Set the more significant 32 bits of a double-precision floating-point number.
*
* @module @stdlib/number/float64/base/set-high-word
*
* @example
* var setHighWord = require( '@stdlib/number/float64/base/set-high-word' );
*
* var high = 5 >>> 0; // => 0 00000000000 00000000000000000101
*
* var y = setHighWord( 3.14e201, high ); // => 0 00000000000 0000000000000000010110010011110010110101100010000010
* // returns 1.18350528745e-313
*
* @example
* var setHighWord = require( '@stdlib/number/float64/base/set-high-word' );
* var PINF = require( '@stdlib/constants/float64/pinf' ); // => 0 11111111111 00000000000000000000 00000000000000000000000000000000
*
* var high = 1072693248 >>> 0; // => 0 01111111111 00000000000000000000
*
* // Set the higher order bits of `+infinity` to return `1`:
* var y = setHighWord( PINF, high ); => 0 01111111111 0000000000000000000000000000000000000000000000000000
* // returns 1.0
*/
// MODULES //
var setHighWord = require( './main.js' );
// EXPORTS //
module.exports = setHighWord;
},{"./main.js":359}],359:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var Uint32Array = require( '@stdlib/array/uint32' );
var Float64Array = require( '@stdlib/array/float64' );
var HIGH = require( './high.js' );
// VARIABLES //
var FLOAT64_VIEW = new Float64Array( 1 );
var UINT32_VIEW = new Uint32Array( FLOAT64_VIEW.buffer );
// MAIN //
/**
* Sets the more significant 32 bits of a double-precision floating-point number.
*
* ## Notes
*
* ```text
* float64 (64 bits)
* f := fraction (significand/mantissa) (52 bits)
* e := exponent (11 bits)
* s := sign bit (1 bit)
*
* |-------- -------- -------- -------- -------- -------- -------- --------|
* | Float64 |
* |-------- -------- -------- -------- -------- -------- -------- --------|
* | Uint32 | Uint32 |
* |-------- -------- -------- -------- -------- -------- -------- --------|
* ```
*
* If little endian (more significant bits last):
*
* ```text
* <-- lower higher -->
* | f7 f6 f5 f4 f3 f2 e2 | f1 |s| e1 |
* ```
*
* If big endian (more significant bits first):
*
* ```text
* <-- higher lower -->
* |s| e1 e2 | f1 f2 f3 f4 f5 f6 f7 |
* ```
*
* In which Uint32 can we find the higher order bits? If little endian, the second; if big endian, the first.
*
*
* ## References
*
* - [Open Group][1]
*
* [1]: http://pubs.opengroup.org/onlinepubs/9629399/chap14.htm
*
* @param {number} x - double
* @param {uinteger32} high - unsigned 32-bit integer to replace the higher order word of `x`
* @returns {number} double having the same lower order word as `x`
*
* @example
* var high = 5 >>> 0; // => 0 00000000000 00000000000000000101
*
* var y = setHighWord( 3.14e201, high ); // => 0 00000000000 0000000000000000010110010011110010110101100010000010
* // returns 1.18350528745e-313
*
* @example
* var PINF = require( '@stdlib/constants/float64/pinf' ); // => 0 11111111111 00000000000000000000 00000000000000000000000000000000
*
* var high = 1072693248 >>> 0; // => 0 01111111111 00000000000000000000
*
* // Set the higher order bits of `+infinity` to return `1`:
* var y = setHighWord( PINF, high ); // => 0 01111111111 0000000000000000000000000000000000000000000000000000
* // returns 1.0
*/
function setHighWord( x, high ) {
FLOAT64_VIEW[ 0 ] = x;
UINT32_VIEW[ HIGH ] = ( high >>> 0 ); // identity bit shift to ensure integer
return FLOAT64_VIEW[ 0 ];
}
// EXPORTS //
module.exports = setHighWord;
},{"./high.js":357,"@stdlib/array/float64":5,"@stdlib/array/uint32":23}],360:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Split a double-precision floating-point number into a higher order word (unsigned 32-bit integer) and a lower order word (unsigned 32-bit integer).
*
* @module @stdlib/number/float64/base/to-words
*
* @example
* var toWords = require( '@stdlib/number/float64/base/to-words' );
*
* var w = toWords( 3.14e201 );
* // returns [ 1774486211, 2479577218 ]
*
* @example
* var Uint32Array = require( '@stdlib/array/uint32' );
* var toWords = require( '@stdlib/number/float64/base/to-words' );
*
* var out = new Uint32Array( 2 );
*
* var w = toWords( out, 3.14e201 );
* // returns <Uint32Array>[ 1774486211, 2479577218 ]
*
* var bool = ( w === out );
* // returns true
*/
// MODULES //
var toWords = require( './main.js' );
// EXPORTS //
module.exports = toWords;
},{"./main.js":362}],361:[function(require,module,exports){
arguments[4][346][0].apply(exports,arguments)
},{"@stdlib/assert/is-little-endian":116,"dup":346}],362:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var fcn = require( './to_words.js' );
// MAIN //
/**
* Splits a double-precision floating-point number into a higher order word (unsigned 32-bit integer) and a lower order word (unsigned 32-bit integer).
*
* @param {(Array|TypedArray|Object)} [out] - output array
* @param {number} x - input value
* @returns {(Array|TypedArray|Object)} output array
*
* @example
* var w = toWords( 3.14e201 );
* // returns [ 1774486211, 2479577218 ]
*
* @example
* var Uint32Array = require( '@stdlib/array/uint32' );
*
* var out = new Uint32Array( 2 );
*
* var w = toWords( out, 3.14e201 );
* // returns <Uint32Array>[ 1774486211, 2479577218 ]
*
* var bool = ( w === out );
* // returns true
*/
function toWords( out, x ) {
if ( arguments.length === 1 ) {
return fcn( [ 0, 0 ], out );
}
return fcn( out, x );
}
// EXPORTS //
module.exports = toWords;
},{"./to_words.js":363}],363:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var Uint32Array = require( '@stdlib/array/uint32' );
var Float64Array = require( '@stdlib/array/float64' );
var indices = require( './indices.js' );
// VARIABLES //
var FLOAT64_VIEW = new Float64Array( 1 );
var UINT32_VIEW = new Uint32Array( FLOAT64_VIEW.buffer );
var HIGH = indices.HIGH;
var LOW = indices.LOW;
// MAIN //
/**
* Splits a double-precision floating-point number into a higher order word (unsigned 32-bit integer) and a lower order word (unsigned 32-bit integer).
*
* ## Notes
*
* ```text
* float64 (64 bits)
* f := fraction (significand/mantissa) (52 bits)
* e := exponent (11 bits)
* s := sign bit (1 bit)
*
* |-------- -------- -------- -------- -------- -------- -------- --------|
* | Float64 |
* |-------- -------- -------- -------- -------- -------- -------- --------|
* | Uint32 | Uint32 |
* |-------- -------- -------- -------- -------- -------- -------- --------|
* ```
*
* If little endian (more significant bits last):
*
* ```text
* <-- lower higher -->
* | f7 f6 f5 f4 f3 f2 e2 | f1 |s| e1 |
* ```
*
* If big endian (more significant bits first):
*
* ```text
* <-- higher lower -->
* |s| e1 e2 | f1 f2 f3 f4 f5 f6 f7 |
* ```
*
* In which Uint32 can we find the higher order bits? If little endian, the second; if big endian, the first.
*
*
* ## References
*
* - [Open Group][1]
*
* [1]: http://pubs.opengroup.org/onlinepubs/9629399/chap14.htm
*
*
* @private
* @param {(Array|TypedArray|Object)} out - output array
* @param {number} x - input value
* @returns {(Array|TypedArray|Object)} output array
*
* @example
* var Uint32Array = require( '@stdlib/array/uint32' );
*
* var out = new Uint32Array( 2 );
*
* var w = toWords( out, 3.14e201 );
* // returns <Uint32Array>[ 1774486211, 2479577218 ]
*
* var bool = ( w === out );
* // returns true
*/
function toWords( out, x ) {
FLOAT64_VIEW[ 0 ] = x;
out[ 0 ] = UINT32_VIEW[ HIGH ];
out[ 1 ] = UINT32_VIEW[ LOW ];
return out;
}
// EXPORTS //
module.exports = toWords;
},{"./indices.js":361,"@stdlib/array/float64":5,"@stdlib/array/uint32":23}],364:[function(require,module,exports){
/* eslint-disable max-lines, max-len */
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*
*
* ## Notice
*
* The original C code and copyright notice are from the [source implementation]{@link http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/CODES/mt19937ar.c}. The implementation has been modified for JavaScript.
*
* ```text
* Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. The names of its contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* ```
*/
'use strict';
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var setReadOnlyAccessor = require( '@stdlib/utils/define-nonenumerable-read-only-accessor' );
var setReadWriteAccessor = require( '@stdlib/utils/define-nonenumerable-read-write-accessor' );
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var isObject = require( '@stdlib/assert/is-plain-object' );
var isCollection = require( '@stdlib/assert/is-collection' );
var isUint32Array = require( '@stdlib/assert/is-uint32array' );
var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive;
var isPositiveInteger = require( '@stdlib/assert/is-positive-integer' ).isPrimitive;
var FLOAT64_MAX_SAFE_INTEGER = require( '@stdlib/constants/float64/max-safe-integer' );
var UINT32_MAX = require( '@stdlib/constants/uint32/max' );
var Uint32Array = require( '@stdlib/array/uint32' );
var max = require( '@stdlib/math/base/special/max' );
var uimul = require( '@stdlib/math/base/special/uimul' );
var gcopy = require( '@stdlib/blas/base/gcopy' );
var typedarray2json = require( '@stdlib/array/to-json' );
var randuint32 = require( './rand_uint32.js' );
// VARIABLES //
// Define the size of the state array (see refs):
var N = 624;
// Define a (magic) constant used for indexing into the state array:
var M = 397;
// Define the maximum seed: 11111111111111111111111111111111
var MAX_SEED = UINT32_MAX >>> 0; // asm type annotation
// For seed arrays, define an initial state (magic) constant: 19650218 => 00000001001010111101011010101010
var SEED_ARRAY_INIT_STATE = 19650218 >>> 0; // asm type annotation
// Define a mask for the most significant `w-r` bits, where `w` is the word size (32 bits) and `r` is the separation point of one word (see refs): 2147483648 => 0x80000000 => 10000000000000000000000000000000
var UPPER_MASK = 0x80000000 >>> 0; // asm type annotation
// Define a mask for the least significant `r` bits (see refs): 2147483647 => 0x7fffffff => 01111111111111111111111111111111
var LOWER_MASK = 0x7fffffff >>> 0; // asm type annotation
// Define a multiplier (see Knuth TAOCP Vol2. 3rd Ed. P.106): 1812433253 => 01101100000001111000100101100101
var KNUTH_MULTIPLIER = 1812433253 >>> 0; // asm type annotation
// Define a (magic) multiplier: 1664525 => 00000000000110010110011000001101
var MAGIC_MULTIPLIER_1 = 1664525 >>> 0; // asm type annotation
// Define a (magic) multiplier: 1566083941 => 01011101010110001000101101100101
var MAGIC_MULTIPLIER_2 = 1566083941 >>> 0; // asm type annotation
// Define a tempering coefficient: 2636928640 => 0x9d2c5680 => 10011101001011000101011010000000
var TEMPERING_COEFFICIENT_1 = 0x9d2c5680 >>> 0; // asm type annotation
// Define a tempering coefficient: 4022730752 => 0xefc60000 => 11101111110001100000000000000000
var TEMPERING_COEFFICIENT_2 = 0xefc60000 >>> 0; // asm type annotation
// Define a constant vector `a` (see refs): 2567483615 => 0x9908b0df => 10011001000010001011000011011111
var MATRIX_A = 0x9908b0df >>> 0; // asm type annotation
// MAG01[x] = x * MATRIX_A; for x = {0,1}
var MAG01 = [ 0x0 >>> 0, MATRIX_A >>> 0 ]; // asm type annotation
// Define a normalization constant when generating double-precision floating-point numbers: 2^53 => 9007199254740992
var FLOAT64_NORMALIZATION_CONSTANT = 1.0 / ( FLOAT64_MAX_SAFE_INTEGER+1.0 ); // eslint-disable-line id-length
// 2^26: 67108864
var TWO_26 = 67108864 >>> 0; // asm type annotation
// 2^32: 2147483648 => 0x80000000 => 10000000000000000000000000000000
var TWO_32 = 0x80000000 >>> 0; // asm type annotation
// 1 (as a 32-bit unsigned integer): 1 => 0x1 => 00000000000000000000000000000001
var ONE = 0x1 >>> 0; // asm type annotation
// Define the maximum normalized pseudorandom double-precision floating-point number: ( (((2^32-1)>>>5)*2^26)+( (2^32-1)>>>6) ) / 2^53
var MAX_NORMALIZED = FLOAT64_MAX_SAFE_INTEGER * FLOAT64_NORMALIZATION_CONSTANT;
// Define the state array schema version:
var STATE_ARRAY_VERSION = 1; // NOTE: anytime the state array schema changes, this value should be incremented!!!
// Define the number of sections in the state array:
var NUM_STATE_SECTIONS = 3; // state, other, seed
// Define the index offset of the "state" section in the state array:
var STATE_SECTION_OFFSET = 2; // | version | num_sections | state_length | ...state | other_length | state_index | seed_length | ...seed |
// Define the index offset of the "other" section in the state array:
var OTHER_SECTION_OFFSET = N + 3; // | version | num_sections | state_length | ...state | other_length | state_index | seed_length | ...seed |
// Define the index offset of the seed section in the state array:
var SEED_SECTION_OFFSET = N + 5; // | version | num_sections | state_length | ...state | other_length | state_index | seed_length | ...seed |
// Define the length of the "fixed" length portion of the state array:
var STATE_FIXED_LENGTH = N + 6; // 1 (version) + 1 (num_sections) + 1 (state_length) + N (state) + 1 (other_length) + 1 (state_index) + 1 (seed_length)
// FUNCTIONS //
/**
* Verifies state array integrity.
*
* @private
* @param {Uint32Array} state - state array
* @param {boolean} FLG - flag indicating whether the state array was provided as an option (true) or an argument (false)
* @returns {(Error|null)} an error or `null`
*/
function verifyState( state, FLG ) {
var s1;
if ( FLG ) {
s1 = 'option';
} else {
s1 = 'argument';
}
// The state array must have a minimum length...
if ( state.length < STATE_FIXED_LENGTH+1 ) {
return new RangeError( 'invalid '+s1+'. `state` array has insufficient length.' );
}
// The first element of the state array must equal the supported state array schema version...
if ( state[ 0 ] !== STATE_ARRAY_VERSION ) {
return new RangeError( 'invalid '+s1+'. `state` array has an incompatible schema version. Expected: '+STATE_ARRAY_VERSION+'. Actual: '+state[ 0 ]+'.' );
}
// The second element of the state array must contain the number of sections...
if ( state[ 1 ] !== NUM_STATE_SECTIONS ) {
return new RangeError( 'invalid '+s1+'. `state` array has an incompatible number of sections. Expected: '+NUM_STATE_SECTIONS+'. Actual: '+state[ 1 ]+'.' );
}
// The length of the "state" section must equal `N`...
if ( state[ STATE_SECTION_OFFSET ] !== N ) {
return new RangeError( 'invalid '+s1+'. `state` array has an incompatible state length. Expected: '+N+'. Actual: '+state[ STATE_SECTION_OFFSET ]+'.' );
}
// The length of the "other" section must equal `1`...
if ( state[ OTHER_SECTION_OFFSET ] !== 1 ) {
return new RangeError( 'invalid '+s1+'. `state` array has an incompatible section length. Expected: '+(1).toString()+'. Actual: '+state[ OTHER_SECTION_OFFSET ]+'.' );
}
// The length of the "seed" section much match the empirical length...
if ( state[ SEED_SECTION_OFFSET ] !== state.length-STATE_FIXED_LENGTH ) {
return new RangeError( 'invalid '+s1+'. `state` array length is incompatible with seed section length. Expected: '+(state.length-STATE_FIXED_LENGTH)+'. Actual: '+state[ SEED_SECTION_OFFSET ]+'.' );
}
return null;
}
/**
* Returns an initial PRNG state.
*
* @private
* @param {Uint32Array} state - state array
* @param {PositiveInteger} N - state size
* @param {uinteger32} s - seed
* @returns {Uint32Array} state array
*/
function createState( state, N, s ) {
var i;
// Set the first element of the state array to the provided seed:
state[ 0 ] = s >>> 0; // equivalent to `s & 0xffffffffUL` in original C implementation
// Initialize the remaining state array elements:
for ( i = 1; i < N; i++ ) {
/*
* In the original C implementation (see `init_genrand()`),
*
* ```c
* mt[i] = (KNUTH_MULTIPLIER * (mt[i-1] ^ (mt[i-1] >> 30)) + i)
* ```
*
* In order to replicate this in JavaScript, we must emulate C-like multiplication of unsigned 32-bit integers.
*/
s = state[ i-1 ]>>>0; // asm type annotation
s = ( s^(s>>>30) )>>>0; // asm type annotation
state[ i ] = ( uimul( s, KNUTH_MULTIPLIER ) + i )>>>0; // asm type annotation
}
return state;
}
/**
* Initializes a PRNG state array according to a seed array.
*
* @private
* @param {Uint32Array} state - state array
* @param {NonNegativeInteger} N - state array length
* @param {Collection} seed - seed array
* @param {NonNegativeInteger} M - seed array length
* @returns {Uint32Array} state array
*/
function initState( state, N, seed, M ) {
var s;
var i;
var j;
var k;
i = 1;
j = 0;
for ( k = max( N, M ); k > 0; k-- ) {
/*
* In the original C implementation (see `init_by_array()`),
*
* ```c
* mt[i] = (mt[i]^((mt[i-1]^(mt[i-1]>>30))*1664525UL)) + seed[j] + j;
* ```
*
* In order to replicate this in JavaScript, we must emulate C-like multiplication of unsigned 32-bit integers.
*/
s = state[ i-1 ]>>>0; // asm type annotation
s = ( s^(s>>>30) )>>>0; // asm type annotation
s = ( uimul( s, MAGIC_MULTIPLIER_1 ) )>>>0; // asm type annotation
state[ i ] = ( ((state[i]>>>0)^s) + seed[j] + j )>>>0; /* non-linear */ // asm type annotation
i += 1;
j += 1;
if ( i >= N ) {
state[ 0 ] = state[ N-1 ];
i = 1;
}
if ( j >= M ) {
j = 0;
}
}
for ( k = N-1; k > 0; k-- ) {
/*
* In the original C implementation (see `init_by_array()`),
*
* ```c
* mt[i] = (mt[i]^((mt[i-1]^(mt[i-1]>>30))*1566083941UL)) - i;
* ```
*
* In order to replicate this in JavaScript, we must emulate C-like multiplication of unsigned 32-bit integers.
*/
s = state[ i-1 ]>>>0; // asm type annotation
s = ( s^(s>>>30) )>>>0; // asm type annotation
s = ( uimul( s, MAGIC_MULTIPLIER_2 ) )>>>0; // asm type annotation
state[ i ] = ( ((state[i]>>>0)^s) - i )>>>0; /* non-linear */ // asm type annotation
i += 1;
if ( i >= N ) {
state[ 0 ] = state[ N-1 ];
i = 1;
}
}
// Ensure a non-zero initial state array:
state[ 0 ] = TWO_32; // MSB (most significant bit) is 1
return state;
}
/**
* Updates a PRNG's internal state by generating the next `N` words.
*
* @private
* @param {Uint32Array} state - state array
* @returns {Uint32Array} state array
*/
function twist( state ) {
var w;
var i;
var j;
var k;
k = N - M;
for ( i = 0; i < k; i++ ) {
w = ( state[i]&UPPER_MASK ) | ( state[i+1]&LOWER_MASK );
state[ i ] = state[ i+M ] ^ ( w>>>1 ) ^ MAG01[ w&ONE ];
}
j = N - 1;
for ( ; i < j; i++ ) {
w = ( state[i]&UPPER_MASK ) | ( state[i+1]&LOWER_MASK );
state[ i ] = state[ i-k ] ^ ( w>>>1 ) ^ MAG01[ w&ONE ];
}
w = ( state[j]&UPPER_MASK ) | ( state[0]&LOWER_MASK );
state[ j ] = state[ M-1 ] ^ ( w>>>1 ) ^ MAG01[ w&ONE ];
return state;
}
// MAIN //
/**
* Returns a 32-bit Mersenne Twister pseudorandom number generator.
*
* ## Notes
*
* - In contrast to the original C implementation, array seeds of length `1` are considered integer seeds. This ensures that the seed `[ 1234 ]` generates the same output as the seed `1234`. In the original C implementation, the two seeds would yield different output, which is **not** obvious from a user perspective.
*
* @param {Options} [options] - options
* @param {PRNGSeedMT19937} [options.seed] - pseudorandom number generator seed
* @param {PRNGStateMT19937} [options.state] - pseudorandom number generator state
* @param {boolean} [options.copy=true] - boolean indicating whether to copy a provided pseudorandom number generator state
* @throws {TypeError} options argument must be an object
* @throws {TypeError} a seed must be either a positive integer less than or equal to the maximum unsigned 32-bit integer or an array-like object containing integers less than or equal to the maximum unsigned 32-bit integer
* @throws {RangeError} a numeric seed must be a positive integer less than or equal to the maximum unsigned 32-bit integer
* @throws {TypeError} state must be a `Uint32Array`
* @throws {Error} must provide a valid state
* @throws {TypeError} `copy` option must be a boolean
* @returns {PRNG} Mersenne Twister PRNG
*
* @example
* var mt19937 = factory();
*
* var v = mt19937();
* // returns <number>
*
* @example
* // Return a seeded Mersenne Twister PRNG:
* var mt19937 = factory({
* 'seed': 1234
* });
*
* var v = mt19937();
* // returns 822569775
*/
function factory( options ) {
var STATE;
var state;
var opts;
var seed;
var slen;
var err;
opts = {};
if ( arguments.length ) {
if ( !isObject( options ) ) {
throw new TypeError( 'invalid argument. Options argument must be an object. Value: `' + options + '`.' );
}
if ( hasOwnProp( options, 'copy' ) ) {
opts.copy = options.copy;
if ( !isBoolean( options.copy ) ) {
throw new TypeError( 'invalid option. `copy` option must be a boolean. Option: `' + options.copy + '`.' );
}
}
if ( hasOwnProp( options, 'state' ) ) {
state = options.state;
opts.state = true;
if ( !isUint32Array( state ) ) {
throw new TypeError( 'invalid option. `state` option must be a Uint32Array. Option: `' + state + '`.' );
}
err = verifyState( state, true );
if ( err ) {
throw err;
}
if ( opts.copy === false ) {
STATE = state;
} else {
STATE = new Uint32Array( state.length );
gcopy( state.length, state, 1, STATE, 1 );
}
// Create a state "view":
state = new Uint32Array( STATE.buffer, STATE.byteOffset+((STATE_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), N );
// Create a seed "view":
seed = new Uint32Array( STATE.buffer, STATE.byteOffset+((SEED_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), state[ SEED_SECTION_OFFSET ] );
}
// If provided a PRNG state, we ignore the `seed` option...
if ( seed === void 0 ) {
if ( hasOwnProp( options, 'seed' ) ) {
seed = options.seed;
opts.seed = true;
if ( isPositiveInteger( seed ) ) {
if ( seed > MAX_SEED ) {
throw new RangeError( 'invalid option. `seed` option must be a positive integer less than or equal to the maximum unsigned 32-bit integer. Option: `' + seed + '`.' );
}
seed >>>= 0; // asm type annotation
} else if ( isCollection( seed ) === false || seed.length < 1 ) {
throw new TypeError( 'invalid option. `seed` option must be either a positive integer less than or equal to the maximum unsigned 32-bit integer or an array-like object containing integer values less than or equal to the maximum unsigned 32-bit integer. Option: `' + seed + '`.' );
} else if ( seed.length === 1 ) {
seed = seed[ 0 ];
if ( !isPositiveInteger( seed ) ) {
throw new TypeError( 'invalid option. `seed` option must be either a positive integer less than or equal to the maximum unsigned 32-bit integer or an array-like object containing integer values less than or equal to the maximum unsigned 32-bit integer. Option: `' + seed + '`.' );
}
if ( seed > MAX_SEED ) {
throw new RangeError( 'invalid option. `seed` option must be either a positive integer less than or equal to the maximum unsigned 32-bit integer or an array-like object containing integer values less than or equal to the maximum unsigned 32-bit integer. Option: `' + seed + '`.' );
}
seed >>>= 0; // asm type annotation
} else {
slen = seed.length;
STATE = new Uint32Array( STATE_FIXED_LENGTH+slen );
// Initialize sections:
STATE[ 0 ] = STATE_ARRAY_VERSION;
STATE[ 1 ] = NUM_STATE_SECTIONS;
STATE[ STATE_SECTION_OFFSET ] = N;
STATE[ OTHER_SECTION_OFFSET ] = 1;
STATE[ OTHER_SECTION_OFFSET+1 ] = N; // state index
STATE[ SEED_SECTION_OFFSET ] = slen;
// Copy the provided seed array to prevent external mutation, as mutation would lead to an inability to reproduce PRNG values according to the PRNG's stated seed:
gcopy.ndarray( slen, seed, 1, 0, STATE, 1, SEED_SECTION_OFFSET+1 );
// Create a state "view":
state = new Uint32Array( STATE.buffer, STATE.byteOffset+((STATE_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), N );
// Create a seed "view":
seed = new Uint32Array( STATE.buffer, STATE.byteOffset+((SEED_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), slen );
// Initialize the internal PRNG state:
state = createState( state, N, SEED_ARRAY_INIT_STATE );
state = initState( state, N, seed, slen );
}
} else {
seed = randuint32() >>> 0; // asm type annotation
}
}
} else {
seed = randuint32() >>> 0; // asm type annotation
}
if ( state === void 0 ) {
STATE = new Uint32Array( STATE_FIXED_LENGTH+1 );
// Initialize sections:
STATE[ 0 ] = STATE_ARRAY_VERSION;
STATE[ 1 ] = NUM_STATE_SECTIONS;
STATE[ STATE_SECTION_OFFSET ] = N;
STATE[ OTHER_SECTION_OFFSET ] = 1;
STATE[ OTHER_SECTION_OFFSET+1 ] = N; // state index
STATE[ SEED_SECTION_OFFSET ] = 1;
STATE[ SEED_SECTION_OFFSET+1 ] = seed;
// Create a state "view":
state = new Uint32Array( STATE.buffer, STATE.byteOffset+((STATE_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), N );
// Create a seed "view":
seed = new Uint32Array( STATE.buffer, STATE.byteOffset+((SEED_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), 1 );
// Initialize the internal PRNG state:
state = createState( state, N, seed );
}
// Note: property order matters in order to maintain consistency of PRNG "shape" (hidden classes).
setReadOnly( mt19937, 'NAME', 'mt19937' );
setReadOnlyAccessor( mt19937, 'seed', getSeed );
setReadOnlyAccessor( mt19937, 'seedLength', getSeedLength );
setReadWriteAccessor( mt19937, 'state', getState, setState );
setReadOnlyAccessor( mt19937, 'stateLength', getStateLength );
setReadOnlyAccessor( mt19937, 'byteLength', getStateSize );
setReadOnly( mt19937, 'toJSON', toJSON );
setReadOnly( mt19937, 'MIN', 1 );
setReadOnly( mt19937, 'MAX', UINT32_MAX );
setReadOnly( mt19937, 'normalized', normalized );
setReadOnly( normalized, 'NAME', mt19937.NAME );
setReadOnlyAccessor( normalized, 'seed', getSeed );
setReadOnlyAccessor( normalized, 'seedLength', getSeedLength );
setReadWriteAccessor( normalized, 'state', getState, setState );
setReadOnlyAccessor( normalized, 'stateLength', getStateLength );
setReadOnlyAccessor( normalized, 'byteLength', getStateSize );
setReadOnly( normalized, 'toJSON', toJSON );
setReadOnly( normalized, 'MIN', 0.0 );
setReadOnly( normalized, 'MAX', MAX_NORMALIZED );
return mt19937;
/**
* Returns the PRNG seed.
*
* @private
* @returns {PRNGSeedMT19937} seed
*/
function getSeed() {
var len = STATE[ SEED_SECTION_OFFSET ];
return gcopy( len, seed, 1, new Uint32Array( len ), 1 );
}
/**
* Returns the PRNG seed length.
*
* @private
* @returns {PositiveInteger} seed length
*/
function getSeedLength() {
return STATE[ SEED_SECTION_OFFSET ];
}
/**
* Returns the PRNG state length.
*
* @private
* @returns {PositiveInteger} state length
*/
function getStateLength() {
return STATE.length;
}
/**
* Returns the PRNG state size (in bytes).
*
* @private
* @returns {PositiveInteger} state size (in bytes)
*/
function getStateSize() {
return STATE.byteLength;
}
/**
* Returns the current PRNG state.
*
* ## Notes
*
* - The PRNG state array is comprised of a preamble followed by `3` sections:
*
* 0. preamble (version + number of sections)
* 1. internal PRNG state
* 2. auxiliary state information
* 3. PRNG seed
*
* - The first element of the PRNG state array preamble is the state array schema version.
*
* - The second element of the PRNG state array preamble is the number of state array sections (i.e., `3`).
*
* - The first element of each section following the preamble specifies the section length. The remaining section elements comprise the section contents.
*
* @private
* @returns {PRNGStateMT19937} current state
*/
function getState() {
var len = STATE.length;
return gcopy( len, STATE, 1, new Uint32Array( len ), 1 );
}
/**
* Sets the PRNG state.
*
* ## Notes
*
* - If PRNG state is "shared" (meaning a state array was provided during PRNG creation and **not** copied) and one sets the generator state to a state array having a different length, the PRNG does **not** update the existing shared state and, instead, points to the newly provided state array. In order to synchronize PRNG output according to the new shared state array, the state array for **each** relevant PRNG must be **explicitly** set.
* - If PRNG state is "shared" and one sets the generator state to a state array of the same length, the PRNG state is updated (along with the state of all other PRNGs sharing the PRNG's state array).
*
* @private
* @param {PRNGStateMT19937} s - generator state
* @throws {TypeError} must provide a `Uint32Array`
* @throws {Error} must provide a valid state
*/
function setState( s ) {
var err;
if ( !isUint32Array( s ) ) {
throw new TypeError( 'invalid argument. Must provide a Uint32Array. Value: `' + s + '`.' );
}
err = verifyState( s, false );
if ( err ) {
throw err;
}
if ( opts.copy === false ) {
if ( opts.state && s.length === STATE.length ) {
gcopy( s.length, s, 1, STATE, 1 ); // update current shared state
} else {
STATE = s; // point to new shared state
opts.state = true; // setting this flag allows updating a shared state even if a state array was not provided at PRNG creation
}
} else {
// Check if we can reuse allocated memory...
if ( s.length !== STATE.length ) {
STATE = new Uint32Array( s.length ); // reallocate
}
gcopy( s.length, s, 1, STATE, 1 );
}
// Create a new state "view":
state = new Uint32Array( STATE.buffer, STATE.byteOffset+((STATE_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), N );
// Create a new seed "view":
seed = new Uint32Array( STATE.buffer, STATE.byteOffset+((SEED_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), STATE[ SEED_SECTION_OFFSET ] );
}
/**
* Serializes the pseudorandom number generator as a JSON object.
*
* ## Notes
*
* - `JSON.stringify()` implicitly calls this method when stringifying a PRNG.
*
* @private
* @returns {Object} JSON representation
*/
function toJSON() {
var out = {};
out.type = 'PRNG';
out.name = mt19937.NAME;
out.state = typedarray2json( STATE );
out.params = [];
return out;
}
/**
* Generates a pseudorandom integer on the interval \\( [1,2^{32}-1) \\).
*
* @private
* @returns {uinteger32} pseudorandom integer
*
* @example
* var r = mt19937();
* // returns <number>
*/
function mt19937() {
var r;
var i;
// Retrieve the current state index:
i = STATE[ OTHER_SECTION_OFFSET+1 ];
// Determine whether we need to update the PRNG state:
if ( i >= N ) {
state = twist( state );
i = 0;
}
// Get the next word of "raw"/untempered state:
r = state[ i ];
// Update the state index:
STATE[ OTHER_SECTION_OFFSET+1 ] = i + 1;
// Tempering transform to compensate for the reduced dimensionality of equidistribution:
r ^= r >>> 11;
r ^= ( r << 7 ) & TEMPERING_COEFFICIENT_1;
r ^= ( r << 15 ) & TEMPERING_COEFFICIENT_2;
r ^= r >>> 18;
return r >>> 0;
}
/**
* Generates a pseudorandom number on the interval \\( [0,1) \\).
*
* ## Notes
*
* - The original C implementation credits Isaku Wada for this algorithm (2002/01/09).
*
* @private
* @returns {number} pseudorandom number
*
* @example
* var r = normalized();
* // returns <number>
*/
function normalized() {
var x = mt19937() >>> 5;
var y = mt19937() >>> 6;
return ( (x*TWO_26)+y ) * FLOAT64_NORMALIZATION_CONSTANT;
}
}
// EXPORTS //
module.exports = factory;
},{"./rand_uint32.js":367,"@stdlib/array/to-json":17,"@stdlib/array/uint32":23,"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-boolean":81,"@stdlib/assert/is-collection":90,"@stdlib/assert/is-plain-object":147,"@stdlib/assert/is-positive-integer":149,"@stdlib/assert/is-uint32array":174,"@stdlib/blas/base/gcopy":229,"@stdlib/constants/float64/max-safe-integer":251,"@stdlib/constants/uint32/max":264,"@stdlib/math/base/special/max":318,"@stdlib/math/base/special/uimul":339,"@stdlib/utils/define-nonenumerable-read-only-accessor":426,"@stdlib/utils/define-nonenumerable-read-only-property":428,"@stdlib/utils/define-nonenumerable-read-write-accessor":430}],365:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* A 32-bit Mersenne Twister pseudorandom number generator.
*
* @module @stdlib/random/base/mt19937
*
* @example
* var mt19937 = require( '@stdlib/random/base/mt19937' );
*
* var v = mt19937();
* // returns <number>
*
* @example
* var factory = require( '@stdlib/random/base/mt19937' ).factory;
*
* var mt19937 = factory({
* 'seed': 1234
* });
*
* var v = mt19937();
* // returns 822569775
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var mt19937 = require( './main.js' );
var factory = require( './factory.js' );
// MAIN //
setReadOnly( mt19937, 'factory', factory );
// EXPORTS //
module.exports = mt19937;
},{"./factory.js":364,"./main.js":366,"@stdlib/utils/define-nonenumerable-read-only-property":428}],366:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var factory = require( './factory.js' );
var randuint32 = require( './rand_uint32.js' );
// MAIN //
/**
* Generates a pseudorandom integer on the interval \\( [1,2^{32}-1) \\).
*
* ## Method
*
* - When generating normalized double-precision floating-point numbers, we first generate two pseudorandom integers \\( x \\) and \\( y \\) on the interval \\( [1,2^{32}-1) \\) for a combined \\( 64 \\) random bits.
*
* - We would like \\( 53 \\) random bits to generate a 53-bit precision integer and, thus, want to discard \\( 11 \\) of the generated bits.
*
* - We do so by discarding \\( 5 \\) bits from \\( x \\) and \\( 6 \\) bits from \\( y \\).
*
* - Accordingly, \\( x \\) contains \\( 27 \\) random bits, which are subsequently shifted left \\( 26 \\) bits (multiplied by \\( 2^{26} \\), and \\( y \\) contains \\( 26 \\) random bits to fill in the lower \\( 26 \\) bits. When summed, they combine to comprise \\( 53 \\) random bits of a double-precision floating-point integer.
*
* - As an example, suppose, for the sake of argument, the 32-bit PRNG generates the maximum unsigned 32-bit integer \\( 2^{32}-1 \\) twice in a row. Then,
*
* ```javascript
* x = 4294967295 >>> 5; // 00000111111111111111111111111111
* y = 4294967295 >>> 6; // 00000011111111111111111111111111
* ```
*
* Multiplying \\( x \\) by \\( 2^{26} \\) returns \\( 9007199187632128 \\), which, in binary, is
*
* ```binarystring
* 0 10000110011 11111111111111111111 11111100000000000000000000000000
* ```
*
* Adding \\( y \\) yields \\( 9007199254740991 \\) (the maximum "safe" double-precision floating-point integer value), which, in binary, is
*
* ```binarystring
* 0 10000110011 11111111111111111111 11111111111111111111111111111111
* ```
*
* - Similarly, suppose the 32-bit PRNG generates the following values
*
* ```javascript
* x = 1 >>> 5; // 0 => 00000000000000000000000000000000
* y = 64 >>> 6; // 1 => 00000000000000000000000000000001
* ```
*
* Multiplying \\( x \\) by \\( 2^{26} \\) returns \\( 0 \\), which, in binary, is
*
* ```binarystring
* 0 00000000000 00000000000000000000 00000000000000000000000000000000
* ```
*
* Adding \\( y \\) yields \\( 1 \\), which, in binary, is
*
* ```binarystring
* 0 01111111111 00000000000000000000 00000000000000000000000000000000
* ```
*
* - As different combinations of \\( x \\) and \\( y \\) are generated, different combinations of double-precision floating-point exponent and significand bits will be toggled, thus generating pseudorandom double-precision floating-point numbers.
*
*
* ## References
*
* - Matsumoto, Makoto, and Takuji Nishimura. 1998. "Mersenne Twister: A 623-dimensionally Equidistributed Uniform Pseudo-random Number Generator." _ACM Transactions on Modeling and Computer Simulation_ 8 (1). New York, NY, USA: ACM: 3–30. doi:[10.1145/272991.272995][@matsumoto:1998a].
* - Harase, Shin. 2017. "Conversion of Mersenne Twister to double-precision floating-point numbers." _ArXiv_ abs/1708.06018 (September). <https://arxiv.org/abs/1708.06018>.
*
* [@matsumoto:1998a]: https://doi.org/10.1145/272991.272995
*
*
* @function mt19937
* @type {PRNG}
* @returns {PositiveInteger} pseudorandom integer
*
* @example
* var v = mt19937();
* // returns <number>
*/
var mt19937 = factory({
'seed': randuint32()
});
// EXPORTS //
module.exports = mt19937;
},{"./factory.js":364,"./rand_uint32.js":367}],367:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var UINT32_MAX = require( '@stdlib/constants/uint32/max' );
var floor = require( '@stdlib/math/base/special/floor' );
// VARIABLES //
var MAX = UINT32_MAX - 1;
// MAIN //
/**
* Returns a pseudorandom integer on the interval \\([1, 2^{32}-1)\\).
*
* @private
* @returns {PositiveInteger} pseudorandom integer
*
* @example
* var v = randuint32();
* // returns <number>
*/
function randuint32() {
var v = floor( 1.0 + (MAX*Math.random()) ); // eslint-disable-line stdlib/no-builtin-math
return v >>> 0; // asm type annotation
}
// EXPORTS //
module.exports = randuint32;
},{"@stdlib/constants/uint32/max":264,"@stdlib/math/base/special/floor":292}],368:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var setReadOnlyAccessor = require( '@stdlib/utils/define-nonenumerable-read-only-accessor' );
var setReadWriteAccessor = require( '@stdlib/utils/define-nonenumerable-read-write-accessor' );
var isPositive = require( '@stdlib/assert/is-positive-number' ).isPrimitive;
var isObject = require( '@stdlib/assert/is-plain-object' );
var isFunction = require( '@stdlib/assert/is-function' );
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var constantFunction = require( '@stdlib/utils/constant-function' );
var noop = require( '@stdlib/utils/noop' );
var randu = require( '@stdlib/random/base/mt19937' ).factory;
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var typedarray2json = require( '@stdlib/array/to-json' );
var poisson0 = require( './poisson.js' );
// MAIN //
/**
* Returns a pseudorandom number generator for generating Poisson distributed random numbers.
*
* @param {PositiveNumber} [lambda] - mean
* @param {Options} [options] - function options
* @param {PRNG} [options.prng] - pseudorandom number generator which generates uniformly distributed pseudorandom numbers
* @param {PRNGSeedMT19937} [options.seed] - pseudorandom number generator seed
* @param {PRNGStateMT19937} [options.state] - pseudorandom number generator state
* @param {boolean} [options.copy=true] - boolean indicating whether to copy a provided pseudorandom number generator state
* @throws {TypeError} `lambda` must be a positive number
* @throws {TypeError} options argument must be an object
* @throws {TypeError} must provide valid options
* @throws {Error} must provide a valid state
* @returns {PRNG} pseudorandom number generator
*
* @example
* var poisson = factory( 5.0 );
* var v = poisson();
* // returns <number>
*
* @example
* var poisson = factory( 8.0, {
* 'seed': 297
* });
* var v = poisson();
* // returns <number>
*
* @example
* var poisson = factory();
* var v = poisson( 0.5 );
* // returns <number>
*/
function factory() {
var lambda;
var opts;
var rand;
var prng;
if ( arguments.length === 0 ) {
rand = randu();
} else if (
arguments.length === 1 &&
isObject( arguments[ 0 ] )
) {
opts = arguments[ 0 ];
if ( hasOwnProp( opts, 'prng' ) ) {
if ( !isFunction( opts.prng ) ) {
throw new TypeError( 'invalid option. `prng` option must be a pseudorandom number generator function. Option: `' + opts.prng + '`.' );
}
rand = opts.prng;
} else {
rand = randu( opts );
}
} else {
lambda = arguments[ 0 ];
if ( !isPositive( lambda ) ) {
throw new TypeError( 'invalid argument. First argument must be a positive number. Value: `' + lambda + '`.' );
}
if ( arguments.length > 1 ) {
opts = arguments[ 1 ];
if ( !isObject( opts ) ) {
throw new TypeError( 'invalid argument. Options argument must be an object. Value: `' + opts + '`.' );
}
if ( hasOwnProp( opts, 'prng' ) ) {
if ( !isFunction( opts.prng ) ) {
throw new TypeError( 'invalid option. `prng` option must be a pseudorandom number generator function. Option: `' + opts.prng + '`.' );
}
rand = opts.prng;
} else {
rand = randu( opts );
}
} else {
rand = randu();
}
}
if ( lambda === void 0 ) {
prng = poisson2;
} else {
prng = poisson1;
}
setReadOnly( prng, 'NAME', 'poisson' );
// If we are provided an "external" PRNG, we don't support getting or setting PRNG state, as we'd need to check for compatible state value types, etc, entailing considerable complexity.
if ( opts && opts.prng ) {
setReadOnly( prng, 'seed', null );
setReadOnly( prng, 'seedLength', null );
setReadWriteAccessor( prng, 'state', constantFunction( null ), noop );
setReadOnly( prng, 'stateLength', null );
setReadOnly( prng, 'byteLength', null );
setReadOnly( prng, 'toJSON', constantFunction( null ) );
setReadOnly( prng, 'PRNG', rand );
} else {
setReadOnlyAccessor( prng, 'seed', getSeed );
setReadOnlyAccessor( prng, 'seedLength', getSeedLength );
setReadWriteAccessor( prng, 'state', getState, setState );
setReadOnlyAccessor( prng, 'stateLength', getStateLength );
setReadOnlyAccessor( prng, 'byteLength', getStateSize );
setReadOnly( prng, 'toJSON', toJSON );
setReadOnly( prng, 'PRNG', rand );
rand = rand.normalized;
}
return prng;
/**
* Returns the PRNG seed.
*
* @private
* @returns {PRNGSeedMT19937} seed
*/
function getSeed() {
return rand.seed;
}
/**
* Returns the PRNG seed length.
*
* @private
* @returns {PositiveInteger} seed length
*/
function getSeedLength() {
return rand.seedLength;
}
/**
* Returns the PRNG state length.
*
* @private
* @returns {PositiveInteger} state length
*/
function getStateLength() {
return rand.stateLength;
}
/**
* Returns the PRNG state size (in bytes).
*
* @private
* @returns {PositiveInteger} state size (in bytes)
*/
function getStateSize() {
return rand.byteLength;
}
/**
* Returns the current pseudorandom number generator state.
*
* @private
* @returns {PRNGStateMT19937} current state
*/
function getState() {
return rand.state;
}
/**
* Sets the pseudorandom number generator state.
*
* @private
* @param {PRNGStateMT19937} s - generator state
* @throws {Error} must provide a valid state
*/
function setState( s ) {
rand.state = s;
}
/**
* Serializes the pseudorandom number generator as a JSON object.
*
* ## Notes
*
* - `JSON.stringify()` implicitly calls this method when stringifying a PRNG.
*
* @private
* @returns {Object} JSON representation
*/
function toJSON() {
var out = {};
out.type = 'PRNG';
out.name = prng.NAME;
out.state = typedarray2json( rand.state );
if ( lambda === void 0 ) {
out.params = [];
} else {
out.params = [ lambda ];
}
return out;
}
/**
* Returns a pseudorandom number drawn from a Poisson distribution.
*
* @private
* @returns {NonNegativeInteger} pseudorandom number
*
* @example
* var v = poisson1();
* // returns <number>
*/
function poisson1() {
return poisson0( rand, lambda );
}
/**
* Returns a pseudorandom number drawn from a Poisson distribution.
*
* @private
* @param {PositiveNumber} lambda - mean
* @returns {NonNegativeInteger} pseudorandom number
*
* @example
* var v = poisson2( 0.5 );
* // returns <number>
*
* @example
* var v = poisson2( NaN );
* // returns NaN
*
* @example
* var v = poisson2( -1.0 );
* // returns NaN
*/
function poisson2( lambda ) {
if (
isnan( lambda ) ||
lambda <= 0.0
) {
return NaN;
}
return poisson0( rand, lambda );
}
}
// EXPORTS //
module.exports = factory;
},{"./poisson.js":372,"@stdlib/array/to-json":17,"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-function":102,"@stdlib/assert/is-plain-object":147,"@stdlib/assert/is-positive-number":153,"@stdlib/math/base/assert/is-nan":272,"@stdlib/random/base/mt19937":365,"@stdlib/utils/constant-function":417,"@stdlib/utils/define-nonenumerable-read-only-accessor":426,"@stdlib/utils/define-nonenumerable-read-only-property":428,"@stdlib/utils/define-nonenumerable-read-write-accessor":430,"@stdlib/utils/noop":488}],369:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Poisson distributed pseudorandom numbers.
*
* @module @stdlib/random/base/poisson
*
* @example
* var poisson = require( '@stdlib/random/base/poisson' );
*
* var v = poisson( 4.0 );
* // returns <number>
*
* @example
* var factory = require( '@stdlib/random/base/poisson' ).factory;
* var poisson = factory( 4.0, {
* 'seed': 297
* });
*
* var v = poisson();
* // returns <number>
*
* @example
* var factory = require( '@stdlib/random/base/poisson' ).factory;
* var poisson = factory({
* 'seed': 297
* });
*
* var v = poisson( 3.0 );
* // returns <number>
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var poisson = require( './main.js' );
var factory = require( './factory.js' );
// MAIN //
setReadOnly( poisson, 'factory', factory );
// EXPORTS //
module.exports = poisson;
},{"./factory.js":368,"./main.js":371,"@stdlib/utils/define-nonenumerable-read-only-property":428}],370:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var exp = require( '@stdlib/math/base/special/exp' );
// MAIN //
/**
* Returns a pseudorandom number drawn from a Poisson distribution.
*
* ## Notes
*
* - Appropriate for \\(lambda < 30\\).
*
*
* ## References
*
* - Knuth, Donald E. 1997. _The Art of Computer Programming, Volume 2 (3rd Ed.): Seminumerical Algorithms_. Boston, MA, USA: Addison-Wesley Longman Publishing Co., Inc.
*
*
* @private
* @param {PRNG} rand - PRNG for generating uniformly distributed numbers
* @param {PositiveNumber} lambda - mean
* @returns {NonNegativeInteger} pseudorandom number
*/
function poisson( rand, lambda ) {
var p = rand();
var k = 1;
while ( p > exp( -lambda ) ) {
k += 1;
p *= rand();
}
return k - 1;
}
// EXPORTS //
module.exports = poisson;
},{"@stdlib/math/base/special/exp":288}],371:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var factory = require( './factory.js' );
// MAIN //
/**
* Returns a pseudorandom number drawn from a Poisson distribution with parameter `lambda`.
*
* ## Method
*
* - When \\(\lambda < 30\\), use Knuth's method.
* - When \\(lambda \geq 30\\), use transformed rejection method as Knuth's method does not scale well with \\(\lambda\\).
*
* ## References
*
* - Knuth, Donald E. 1997. _The Art of Computer Programming, Volume 2 (3rd Ed.): Seminumerical Algorithms_. Boston, MA, USA: Addison-Wesley Longman Publishing Co., Inc.
* - Hörmann, W. 1993. "The transformed rejection method for generating Poisson random variables." _Insurance: Mathematics and Economics_ 12 (1): 39–45. doi:[10.1016/0167-6687(93)90997-4][@hormann:1993b].
*
* [@hormann:1993b]: http://dx.doi.org/10.1016/0167-6687(93)90997-4
*
*
* @name poisson
* @type {PRNG}
* @param {PositiveNumber} lambda - mean
* @returns {NonNegativeInteger} pseudorandom number
*
* @example
* var v = poisson( 0.5 );
* // returns <number>
*
* @example
* var v = poisson( 0.0 );
* // returns NaN
*
* @example
* var v = poisson( NaN );
* // returns NaN
*/
var poisson = factory();
// EXPORTS //
module.exports = poisson;
},{"./factory.js":368}],372:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var knuth = require( './knuth.js' );
var rejection = require( './rejection.js' );
// MAIN //
/**
* Returns a pseudorandom number drawn from a Poisson distribution with parameter `lambda`.
*
* @private
* @param {PRNG} rand - PRNG for generating uniformly distributed numbers
* @param {PositiveNumber} lambda - mean
* @returns {NonNegativeInteger} pseudorandom number
*/
function poisson( rand, lambda ) {
if ( lambda < 30.0 ) {
return knuth( rand, lambda );
}
return rejection( rand, lambda );
}
// EXPORTS //
module.exports = poisson;
},{"./knuth.js":370,"./rejection.js":373}],373:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var factorialln = require( '@stdlib/math/base/special/factorialln' );
var floor = require( '@stdlib/math/base/special/floor' );
var sign = require( '@stdlib/math/base/special/signum' );
var sqrt = require( '@stdlib/math/base/special/sqrt' );
var abs = require( '@stdlib/math/base/special/abs' );
var ln = require( '@stdlib/math/base/special/ln' );
var LN_SQRT_TWO_PI = require( '@stdlib/constants/float64/ln-sqrt-two-pi' );
// VARIABLES //
var ONE_12 = 1.0 / 12.0;
var ONE_360 = 1.0 / 360.0;
// MAIN //
/**
* Returns a pseudorandom number drawn from a Poisson distribution with parameter `lambda`.
*
* ## References
*
* - Hörmann, W. 1993. "The transformed rejection method for generating Poisson random variables." _Insurance: Mathematics and Economics_ 12 (1): 39–45. doi:[10.1016/0167-6687(93)90997-4][@hormann:1993b].
*
* [@hormann:1993b]: http://dx.doi.org/10.1016/0167-6687(93)90997-4
*
*
* @private
* @param {PRNG} rand - PRNG for generating uniformly distributed numbers
* @param {PositiveNumber} lambda - mean
* @returns {NonNegativeInteger} pseudorandom number
*/
function poisson( rand, lambda ) {
var slambda;
var ainv;
var urvr;
var us;
var vr;
var a;
var b;
var k;
var u;
var v;
slambda = sqrt( lambda );
b = (2.53*slambda) + 0.931;
a = (0.02483*b) - 0.059;
ainv = (1.1328/(b-3.4)) + 1.1239;
vr = (-3.6224/(b-2.0)) + 0.9277;
urvr = 0.86 * vr;
while ( true ) {
v = rand();
if ( v <= urvr ) {
u = (v / vr) - 0.43;
u *= (2.0*a / (0.5-abs(u))) + b;
u += lambda + 0.445;
return floor( u );
}
if ( v >= vr ) {
u = rand() - 0.5;
} else {
u = (v / vr) - 0.93;
u = (sign( u )*0.5) - u;
v = vr * rand();
}
us = 0.5 - abs( u );
if (
us >= 0.013 ||
us >= v
) {
k = floor( (((2.0*a/us) + b)*u) + lambda + 0.445 );
v *= ainv / ( (a/(us*us)) + b );
u = (k+0.5) * ln( lambda/k );
u += -lambda - LN_SQRT_TWO_PI + k;
u -= ( ONE_12 - (ONE_360/(k*k)) ) / k;
if (
k >= 10 &&
u >= ln( v*slambda )
) {
return k;
}
u = (k*ln( lambda )) - lambda - factorialln( k );
if (
k >= 0 &&
k <= 9 &&
u >= ln( v )
) {
return k;
}
}
}
}
// EXPORTS //
module.exports = poisson;
},{"@stdlib/constants/float64/ln-sqrt-two-pi":248,"@stdlib/math/base/special/abs":278,"@stdlib/math/base/special/factorialln":291,"@stdlib/math/base/special/floor":292,"@stdlib/math/base/special/ln":314,"@stdlib/math/base/special/signum":329,"@stdlib/math/base/special/sqrt":335}],374:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var Readable = require( 'readable-stream' ).Readable;
var bench = require( '@stdlib/bench' );
var pkg = require( './../package.json' ).name;
var randomStream = require( './../lib' );
// MAIN //
bench( pkg, function benchmark( b ) {
var s;
var i;
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
s = randomStream( 3.0 );
if ( typeof s !== 'object' ) {
b.fail( 'should return an object' );
}
}
b.toc();
if ( !( s instanceof Readable ) ) {
b.fail( 'should return a readable stream' );
}
b.pass( 'benchmark finished' );
b.end();
});
bench( pkg+'::seed', function benchmark( b ) {
var opts;
var s;
var i;
opts = {
'seed': 12345
};
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
s = randomStream( 3.0, opts );
if ( typeof s !== 'object' ) {
b.fail( 'should return an object' );
}
}
b.toc();
if ( !( s instanceof Readable ) ) {
b.fail( 'should return a readable stream' );
}
b.pass( 'benchmark finished' );
b.end();
});
bench( pkg+':objectMode', function benchmark( b ) {
var s;
var i;
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
s = randomStream.objectMode( 3.0 );
if ( typeof s !== 'object' ) {
b.fail( 'should return an object' );
}
}
b.toc();
if ( !( s instanceof Readable ) ) {
b.fail( 'should return a readable stream' );
}
b.pass( 'benchmark finished' );
b.end();
});
bench( pkg+'::factory', function benchmark( b ) {
var createStream;
var s;
var i;
createStream = randomStream.factory( 3.0 );
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
s = createStream();
if ( typeof s !== 'object' ) {
b.fail( 'should return an object' );
}
}
b.toc();
if ( !( s instanceof Readable ) ) {
b.fail( 'should return a readable stream' );
}
b.pass( 'benchmark finished' );
b.end();
});
},{"./../lib":379,"./../package.json":383,"@stdlib/bench":228,"readable-stream":533}],375:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var WritableStream = require( 'readable-stream' ).Writable; // eslint-disable-line stdlib/no-redeclare
var bench = require( '@stdlib/bench' );
var inherit = require( '@stdlib/utils/inherit' );
var nextTick = require( '@stdlib/utils/next-tick' );
var pkg = require( './../package.json' ).name;
var randomStream = require( './../lib' );
// MAIN //
bench( pkg+'::throughput,baseline', function benchmark( b ) {
var i;
i = 0;
b.tic();
return next();
function next() {
i += 1;
if ( i <= b.iterations ) {
return nextTick( onTick );
}
b.toc();
b.pass( 'benchmark finished' );
b.end();
}
function onTick() {
if ( i !== i ) {
b.fail( 'should not be NaN' );
}
next();
}
});
bench( pkg+'::throughput:highWaterMark=<default>', function benchmark( b ) {
var rStream;
var wStream;
var opts;
var i;
function Writable( opts ) {
WritableStream.call( this, opts );
return this;
}
inherit( Writable, WritableStream );
Writable.prototype._write = next; // eslint-disable-line no-underscore-dangle
// Create a source stream:
opts = {};
rStream = randomStream( 3.0, opts );
// Create a sink stream:
opts = {};
wStream = new Writable( opts );
i = 0;
b.tic();
return pipe();
function pipe() {
// Begin data flow...
rStream.pipe( wStream );
}
function next( chunk, encoding, clbk ) {
i += 1;
if ( i < b.iterations ) {
return clbk();
}
b.toc();
rStream.destroy();
b.pass( 'benchmark finished' );
b.end();
}
});
bench( pkg+'::throughput:highWaterMark=0', function benchmark( b ) {
var rStream;
var wStream;
var opts;
var i;
function Writable( opts ) {
WritableStream.call( this, opts );
return this;
}
inherit( Writable, WritableStream );
Writable.prototype._write = next; // eslint-disable-line no-underscore-dangle
// Create a source stream:
opts = {
'highWaterMark': 0
};
rStream = randomStream( 3.0, opts );
// Create a sink stream:
opts = {};
wStream = new Writable( opts );
i = 0;
b.tic();
return pipe();
function pipe() {
// Begin data flow...
rStream.pipe( wStream );
}
function next( chunk, encoding, clbk ) {
i += 1;
if ( i < b.iterations ) {
return clbk();
}
b.toc();
rStream.destroy();
b.pass( 'benchmark finished' );
b.end();
}
});
bench( pkg+'::throughput,object_mode:highWaterMark=<default>', function benchmark( b ) {
var rStream;
var wStream;
var opts;
var i;
function Writable( opts ) {
WritableStream.call( this, opts );
return this;
}
inherit( Writable, WritableStream );
Writable.prototype._write = next; // eslint-disable-line no-underscore-dangle
// Create a source stream:
opts = {};
rStream = randomStream.objectMode( 3.0, opts );
// Create a sink stream:
opts = {
'objectMode': true
};
wStream = new Writable( opts );
i = 0;
b.tic();
return pipe();
function pipe() {
// Begin data flow...
rStream.pipe( wStream );
}
function next( chunk, encoding, clbk ) {
i += 1;
if ( i < b.iterations ) {
return clbk();
}
b.toc();
rStream.destroy();
b.pass( 'benchmark finished' );
b.end();
}
});
bench( pkg+'::throughput,object_mode:highWaterMark=0', function benchmark( b ) {
var rStream;
var wStream;
var opts;
var i;
function Writable( opts ) {
WritableStream.call( this, opts );
return this;
}
inherit( Writable, WritableStream );
Writable.prototype._write = next; // eslint-disable-line no-underscore-dangle
// Create a source stream:
opts = {
'highWaterMark': 0
};
rStream = randomStream.objectMode( 3.0, opts );
// Create a sink stream:
opts = {
'objectMode': true
};
wStream = new Writable( opts );
i = 0;
b.tic();
return pipe();
function pipe() {
// Begin data flow...
rStream.pipe( wStream );
}
function next( chunk, encoding, clbk ) {
i += 1;
if ( i < b.iterations ) {
return clbk();
}
b.toc();
rStream.destroy();
b.pass( 'benchmark finished' );
b.end();
}
});
},{"./../lib":379,"./../package.json":383,"@stdlib/bench":228,"@stdlib/utils/inherit":460,"@stdlib/utils/next-tick":486,"readable-stream":533}],376:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var logger = require( 'debug' );
// MAIN //
var debug = logger( 'random:streams:poisson' );
// EXPORTS //
module.exports = debug;
},{"debug":516}],377:[function(require,module,exports){
module.exports={
"objectMode": false,
"encoding": null,
"sep": "\n",
"copy": true,
"siter": 1e308
}
},{}],378:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isPositive = require( '@stdlib/assert/is-positive-number' ).isPrimitive;
var copy = require( '@stdlib/utils/copy' );
var RandomStream = require( './main.js' );
// MAIN //
/**
* Returns a function for creating readable streams which generate pseudorandom numbers drawn from a Poisson distribution.
*
* @param {PositiveNumber} [lambda] - mean
* @param {Options} [options] - stream options
* @param {boolean} [options.objectMode=false] - specifies whether a stream should operate in object mode
* @param {(string|null)} [options.encoding=null] - specifies how `Buffer` objects should be decoded to `strings`
* @param {NonNegativeNumber} [options.highWaterMark] - specifies the maximum number of bytes to store in an internal buffer before ceasing to generate additional pseudorandom numbers
* @param {string} [options.sep='\n'] - separator used to join streamed data
* @param {NonNegativeInteger} [options.iter] - number of iterations
* @param {PRNG} [options.prng] - pseudorandom number generator which generates uniformly distributed pseudorandom numbers
* @param {PRNGSeedMT19937} [options.seed] - pseudorandom number generator seed
* @param {PRNGStateMT19937} [options.state] - pseudorandom number generator state
* @param {boolean} [options.copy=true] - boolean indicating whether to copy a provided pseudorandom number generator state
* @param {PositiveInteger} [options.siter] - number of iterations after which to emit the PRNG state
* @returns {Function} stream factory
*
* @example
* var opts = {
* 'sep': ',',
* 'objectMode': false,
* 'encoding': 'utf8',
* 'highWaterMark': 64
* };
*
* var createStream = factory( opts );
*
* // Create 10 identically configured streams...
* var streams = [];
* var i;
* for ( i = 0; i < 10; i++ ) {
* streams.push( createStream( 3.0 ) );
* }
*/
function factory( lambda, options ) {
var nargs;
var opts;
var fcn;
nargs = arguments.length;
if ( nargs > 1 ) {
fcn = createStream2;
opts = copy( options, 1 );
} else if ( nargs === 1 ) {
if ( isPositive( lambda ) ) {
fcn = createStream2;
opts = {};
} else {
opts = copy( lambda, 1 );
fcn = createStream1;
}
} else {
opts = {};
fcn = createStream1;
}
return fcn;
/**
* Returns a readable stream for generating pseudorandom numbers drawn from a Poisson distribution.
*
* @private
* @param {PositiveNumber} lambda - mean
* @throws {TypeError} `lambda` must be a positive number
* @throws {TypeError} options argument must be an object
* @throws {TypeError} must provide valid options
* @throws {Error} must provide a valid state
* @returns {RandomStream} Stream instance
*/
function createStream1( lambda ) {
return new RandomStream( lambda, opts );
}
/**
* Returns a readable stream for generating pseudorandom numbers drawn from a Poisson distribution.
*
* @private
* @throws {TypeError} `lambda` must be a positive number
* @throws {TypeError} options argument must be an object
* @throws {TypeError} must provide valid options
* @throws {Error} must provide a valid state
* @returns {RandomStream} Stream instance
*/
function createStream2() {
return new RandomStream( lambda, opts );
}
}
// EXPORTS //
module.exports = factory;
},{"./main.js":380,"@stdlib/assert/is-positive-number":153,"@stdlib/utils/copy":422}],379:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Create a readable stream for generating pseudorandom numbers drawn from a Poisson distribution.
*
* @module @stdlib/random/streams/poisson
*
* @example
* var inspectStream = require( '@stdlib/streams/node/inspect-sink' );
* var randomStream = require( '@stdlib/random/streams/poisson' );
*
* function log( chunk ) {
* console.log( chunk.toString() );
* }
*
* var opts = {
* 'iter': 10
* };
*
* var stream = randomStream( 2.0, opts );
*
* stream.pipe( inspectStream( log ) );
*
* @example
* var randomStream = require( '@stdlib/random/streams/poisson' );
*
* var opts = {
* 'sep': ',',
* 'objectMode': false,
* 'encoding': 'utf8',
* 'highWaterMark': 64
* };
*
* var createStream = randomStream.factory( opts );
*
* // Create 10 identically configured streams...
* var streams = [];
* var i;
* for ( i = 0; i < 10; i++ ) {
* streams.push( createStream( 2.0 ) );
* }
*
* @example
* var inspectStream = require( '@stdlib/streams/node/inspect-sink' );
* var randomStream = require( '@stdlib/random/streams/poisson' );
*
* function log( v ) {
* console.log( v );
* }
*
* var opts = {
* 'iter': 10
* };
*
* var stream = randomStream.objectMode( 2.0, opts );
*
* stream.pipe( inspectStream.objectMode( log ) );
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var stream = require( './main.js' );
var objectMode = require( './object_mode.js' );
var factory = require( './factory.js' );
// MAIN //
setReadOnly( stream, 'objectMode', objectMode );
setReadOnly( stream, 'factory', factory );
// EXPORTS //
module.exports = stream;
},{"./factory.js":378,"./main.js":380,"./object_mode.js":381,"@stdlib/utils/define-nonenumerable-read-only-property":428}],380:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var Readable = require( 'readable-stream' ).Readable;
var isPositiveNumber = require( '@stdlib/assert/is-positive-number' ).isPrimitive;
var isError = require( '@stdlib/assert/is-error' );
var copy = require( '@stdlib/utils/copy' );
var inherit = require( '@stdlib/utils/inherit' );
var setNonEnumerable = require( '@stdlib/utils/define-nonenumerable-property' );
var setNonEnumerableReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var setReadOnlyAccessor = require( '@stdlib/utils/define-read-only-accessor' );
var setReadWriteAccessor = require( '@stdlib/utils/define-read-write-accessor' );
var rpoisson = require( '@stdlib/random/base/poisson' ).factory;
var string2buffer = require( '@stdlib/buffer/from-string' );
var nextTick = require( '@stdlib/utils/next-tick' );
var DEFAULTS = require( './defaults.json' );
var validate = require( './validate.js' );
var debug = require( './debug.js' );
// FUNCTIONS //
/**
* Returns the PRNG seed.
*
* @private
* @returns {(PRNGSeedMT19937|null)} seed
*/
function getSeed() {
return this._prng.seed; // eslint-disable-line no-invalid-this
}
/**
* Returns the PRNG seed length.
*
* @private
* @returns {(PositiveInteger|null)} seed length
*/
function getSeedLength() {
return this._prng.seedLength; // eslint-disable-line no-invalid-this
}
/**
* Returns the PRNG state length.
*
* @private
* @returns {(PositiveInteger|null)} state length
*/
function getStateLength() {
return this._prng.stateLength; // eslint-disable-line no-invalid-this
}
/**
* Returns the PRNG state size (in bytes).
*
* @private
* @returns {(PositiveInteger|null)} state size (in bytes)
*/
function getStateSize() {
return this._prng.byteLength; // eslint-disable-line no-invalid-this
}
/**
* Returns the current PRNG state.
*
* @private
* @returns {(PRNGStateMT19937|null)} current state
*/
function getState() {
return this._prng.state; // eslint-disable-line no-invalid-this
}
/**
* Sets the PRNG state.
*
* @private
* @param {PRNGStateMT19937} s - generator state
* @throws {Error} must provide a valid state
*/
function setState( s ) {
this._prng.state = s; // eslint-disable-line no-invalid-this
}
/**
* Implements the `_read` method.
*
* @private
* @param {number} size - number (of bytes) to read
* @returns {void}
*/
function read() {
/* eslint-disable no-invalid-this */
var FLG;
var r;
if ( this._destroyed ) {
return;
}
FLG = true;
while ( FLG ) {
this._i += 1;
if ( this._i > this._iter ) {
debug( 'Finished generating pseudorandom numbers.' );
return this.push( null );
}
r = this._prng();
debug( 'Generated a new pseudorandom number. Value: %d. Iter: %d.', r, this._i );
if ( this._objectMode === false ) {
r = r.toString();
if ( this._i === 1 ) {
r = string2buffer( r );
} else {
r = string2buffer( this._sep+r );
}
}
FLG = this.push( r );
if ( this._i%this._siter === 0 ) {
this.emit( 'state', this.state );
}
}
/* eslint-enable no-invalid-this */
}
/**
* Gracefully destroys a stream, providing backward compatibility.
*
* @private
* @param {(string|Object|Error)} [error] - error
* @returns {RandomStream} Stream instance
*/
function destroy( error ) {
/* eslint-disable no-invalid-this */
var self;
if ( this._destroyed ) {
debug( 'Attempted to destroy an already destroyed stream.' );
return this;
}
self = this;
this._destroyed = true;
nextTick( close );
return this;
/**
* Closes a stream.
*
* @private
*/
function close() {
if ( error ) {
debug( 'Stream was destroyed due to an error. Error: %s.', ( isError( error ) ) ? error.message : JSON.stringify( error ) );
self.emit( 'error', error );
}
debug( 'Closing the stream...' );
self.emit( 'close' );
}
/* eslint-enable no-invalid-this */
}
// MAIN //
/**
* Stream constructor for generating a stream of pseudorandom numbers drawn from a Poisson distribution.
*
* @constructor
* @param {PositiveNumber} lambda - mean
* @param {Options} [options] - stream options
* @param {boolean} [options.objectMode=false] - specifies whether the stream should operate in object mode
* @param {(string|null)} [options.encoding=null] - specifies how `Buffer` objects should be decoded to strings
* @param {NonNegativeNumber} [options.highWaterMark] - specifies the maximum number of bytes to store in an internal buffer before ceasing to generate additional pseudorandom numbers
* @param {string} [options.sep='\n'] - separator used to join streamed data
* @param {NonNegativeInteger} [options.iter] - number of iterations
* @param {PRNG} [options.prng] - pseudorandom number generator which generates uniformly distributed pseudorandom numbers
* @param {PRNGSeedMT19937} [options.seed] - pseudorandom number generator seed
* @param {PRNGStateMT19937} [options.state] - pseudorandom number generator state
* @param {boolean} [options.copy=true] - boolean indicating whether to copy a provided pseudorandom number generator state
* @param {PositiveInteger} [options.siter] - number of iterations after which to emit the PRNG state
* @throws {TypeError} `lambda` must be a positive number
* @throws {TypeError} options argument must be an object
* @throws {TypeError} must provide valid options
* @throws {Error} must provide a valid state
* @returns {RandomStream} Stream instance
*
* @example
* var inspectStream = require( '@stdlib/streams/node/inspect-sink' );
*
* function log( chunk ) {
* console.log( chunk.toString() );
* }
*
* var opts = {
* 'iter': 10
* };
*
* var stream = new RandomStream( 2.0, opts );
*
* stream.pipe( inspectStream( log ) );
*/
function RandomStream( lambda, options ) {
var opts;
var err;
if ( !( this instanceof RandomStream ) ) {
if ( arguments.length > 1 ) {
return new RandomStream( lambda, options );
}
return new RandomStream( lambda );
}
if ( !isPositiveNumber( lambda ) ) {
throw new TypeError( 'invalid argument. First argument must be a positive number. Value: `'+lambda+'`.' );
}
opts = copy( DEFAULTS );
if ( arguments.length > 1 ) {
err = validate( opts, options );
if ( err ) {
throw err;
}
}
// Make the stream a readable stream:
debug( 'Creating a readable stream configured with the following options: %s.', JSON.stringify( opts ) );
Readable.call( this, opts );
// Destruction state:
setNonEnumerable( this, '_destroyed', false );
// Cache whether the stream is operating in object mode:
setNonEnumerableReadOnly( this, '_objectMode', opts.objectMode );
// Cache the separator:
setNonEnumerableReadOnly( this, '_sep', opts.sep );
// Cache the total number of iterations:
setNonEnumerableReadOnly( this, '_iter', opts.iter );
// Cache the number of iterations after which to emit the underlying PRNG state:
setNonEnumerableReadOnly( this, '_siter', opts.siter );
// Initialize an iteration counter:
setNonEnumerable( this, '_i', 0 );
// Create the underlying PRNG:
setNonEnumerableReadOnly( this, '_prng', rpoisson( lambda, opts ) );
setNonEnumerableReadOnly( this, 'PRNG', this._prng.PRNG );
return this;
}
/*
* Inherit from the `Readable` prototype.
*/
inherit( RandomStream, Readable );
/**
* PRNG seed.
*
* @name seed
* @memberof RandomStream.prototype
* @type {(PRNGSeedMT19937|null)}
*/
setReadOnlyAccessor( RandomStream.prototype, 'seed', getSeed );
/**
* PRNG seed length.
*
* @name seedLength
* @memberof RandomStream.prototype
* @type {(PositiveInteger|null)}
*/
setReadOnlyAccessor( RandomStream.prototype, 'seedLength', getSeedLength );
/**
* PRNG state getter/setter.
*
* @name state
* @memberof RandomStream.prototype
* @type {(PRNGStateMT19937|null)}
* @throws {Error} must provide a valid state
*/
setReadWriteAccessor( RandomStream.prototype, 'state', getState, setState );
/**
* PRNG state length.
*
* @name stateLength
* @memberof RandomStream.prototype
* @type {(PositiveInteger|null)}
*/
setReadOnlyAccessor( RandomStream.prototype, 'stateLength', getStateLength );
/**
* PRNG state size (in bytes).
*
* @name byteLength
* @memberof RandomStream.prototype
* @type {(PositiveInteger|null)}
*/
setReadOnlyAccessor( RandomStream.prototype, 'byteLength', getStateSize );
/**
* Implements the `_read` method.
*
* @private
* @name _read
* @memberof RandomStream.prototype
* @type {Function}
* @param {number} size - number (of bytes) to read
* @returns {void}
*/
setNonEnumerableReadOnly( RandomStream.prototype, '_read', read );
/**
* Gracefully destroys a stream, providing backward compatibility.
*
* @name destroy
* @memberof RandomStream.prototype
* @type {Function}
* @param {(string|Object|Error)} [error] - error
* @returns {RandomStream} Stream instance
*/
setNonEnumerableReadOnly( RandomStream.prototype, 'destroy', destroy );
// EXPORTS //
module.exports = RandomStream;
},{"./debug.js":376,"./defaults.json":377,"./validate.js":382,"@stdlib/assert/is-error":96,"@stdlib/assert/is-positive-number":153,"@stdlib/buffer/from-string":240,"@stdlib/random/base/poisson":369,"@stdlib/utils/copy":422,"@stdlib/utils/define-nonenumerable-property":424,"@stdlib/utils/define-nonenumerable-read-only-property":428,"@stdlib/utils/define-read-only-accessor":437,"@stdlib/utils/define-read-write-accessor":439,"@stdlib/utils/inherit":460,"@stdlib/utils/next-tick":486,"readable-stream":533}],381:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isObject = require( '@stdlib/assert/is-plain-object' );
var copy = require( '@stdlib/utils/copy' );
var RandomStream = require( './main.js' );
// MAIN //
/**
* Returns an "objectMode" readable stream for generating pseudorandom numbers drawn from a Poisson distribution.
*
* @param {PositiveNumber} lambda - mean
* @param {Options} [options] - stream options
* @param {(string|null)} [options.encoding=null] - specifies how `Buffer` objects should be decoded to `strings`
* @param {NonNegativeNumber} [options.highWaterMark] - specifies the maximum number of objects to store in an internal buffer before ceasing to generate additional pseudorandom numbers
* @param {NonNegativeInteger} [options.iter] - number of iterations
* @param {PRNG} [options.prng] - pseudorandom number generator which generates uniformly distributed pseudorandom numbers
* @param {PRNGSeedMT19937} [options.seed] - pseudorandom number generator seed
* @param {PRNGStateMT19937} [options.state] - pseudorandom number generator state
* @param {boolean} [options.copy=true] - boolean indicating whether to copy a provided pseudorandom number generator state
* @param {PositiveInteger} [options.siter] - number of iterations after which to emit the PRNG state
* @throws {TypeError} `lambda` must be a positive number
* @throws {TypeError} options argument must be an object
* @throws {TypeError} must provide valid options
* @throws {Error} must provide a valid state
* @returns {RandomStream} Stream instance
*
* @example
* var inspectStream = require( '@stdlib/streams/node/inspect-sink' );
*
* function log( v ) {
* console.log( v );
* }
*
* var opts = {
* 'iter': 10
* };
*
* var stream = objectMode( 1.0, opts );
*
* stream.pipe( inspectStream.objectMode( log ) );
*/
function objectMode( lambda, options ) {
var opts;
if ( arguments.length > 1 ) {
opts = options;
if ( !isObject( opts ) ) {
throw new TypeError( 'invalid argument. Options must be an object. Value: `' + opts + '`.' );
}
opts = copy( options, 1 );
} else {
opts = {};
}
opts.objectMode = true;
return new RandomStream( lambda, opts );
}
// EXPORTS //
module.exports = objectMode;
},{"./main.js":380,"@stdlib/assert/is-plain-object":147,"@stdlib/utils/copy":422}],382:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isObject = require( '@stdlib/assert/is-plain-object' );
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive;
var isNonNegative = require( '@stdlib/assert/is-nonnegative-number' ).isPrimitive;
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var isPositiveInteger = require( '@stdlib/assert/is-positive-integer' ).isPrimitive;
var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ).isPrimitive;
// MAIN //
/**
* Validates function options.
*
* @private
* @param {Object} opts - destination object
* @param {Options} options - function options
* @param {string} [options.sep] - separator used to join streamed data
* @param {boolean} [options.objectMode] - specifies whether a stream should operate in object mode
* @param {(string|null)} [options.encoding] - specifies how `Buffer` objects should be decoded to `strings`
* @param {NonNegativeNumber} [options.highWaterMark] - specifies the maximum number of bytes to store in the internal buffer before ceasing to generate additional pseudorandom numbers
* @param {NonNegativeInteger} [options.iter] - number of iterations
* @param {PRNG} [options.prng] - pseudorandom number generator which generates uniformly distributed pseudorandom numbers
* @param {PRNGSeedMT19937} [options.seed] - pseudorandom number generator seed
* @param {PRNGStateMT19937} [options.state] - pseudorandom number generator state
* @param {boolean} [options.copy] - boolean indicating whether to copy a provided pseudorandom number generator state
* @param {PositiveInteger} [options.siter] - number of iterations after which to emit the PRNG state
* @returns {(Error|null)} null or an error object
*
* @example
* var opts = {};
* var options = {
* 'objectMode': true
* };
* var err= validate( opts, options );
* if ( err ) {
* throw err;
* }
*/
function validate( opts, options ) {
if ( !isObject( options ) ) {
return new TypeError( 'invalid argument. Options must be an object. Value: `' + options + '`.' );
}
if ( hasOwnProp( options, 'sep' ) ) {
opts.sep = options.sep;
if ( !isString( opts.sep ) ) {
return new TypeError( 'invalid option. `sep` option must be a primitive string. Option: `' + opts.sep + '`.' );
}
}
if ( hasOwnProp( options, 'objectMode' ) ) {
opts.objectMode = options.objectMode;
if ( !isBoolean( opts.objectMode ) ) {
return new TypeError( 'invalid option. `objectMode` option must be a primitive boolean. Option: `' + opts.objectMode + '`.' );
}
}
if ( hasOwnProp( options, 'encoding' ) ) {
opts.encoding = options.encoding;
if ( !isString( opts.encoding ) && opts.encoding !== null ) {
return new TypeError( 'invalid option. `encoding` option must be a primitive string or null. Option: `' + opts.encoding + '`.' );
}
}
if ( hasOwnProp( options, 'highWaterMark' ) ) {
opts.highWaterMark = options.highWaterMark;
if ( !isNonNegative( opts.highWaterMark ) ) {
return new TypeError( 'invalid option. `highWaterMark` option must be a nonnegative number. Option: `' + opts.highWaterMark + '`.' );
}
}
if ( hasOwnProp( options, 'iter' ) ) {
opts.iter = options.iter;
if ( !isNonNegativeInteger( opts.iter ) ) {
return new TypeError( 'invalid option. `iter` option must be a nonnegative integer. Option: `' + opts.iter + '`.' );
}
}
if ( hasOwnProp( options, 'siter' ) ) {
opts.siter = options.siter;
if ( !isPositiveInteger( opts.siter ) ) {
return new TypeError( 'invalid option. `siter` option must be a positive integer. Option: `' + opts.siter + '`.' );
}
}
// Pass through options...
if ( hasOwnProp( options, 'prng' ) ) {
opts.prng = options.prng;
}
if ( hasOwnProp( options, 'seed' ) ) {
opts.seed = options.seed;
}
if ( hasOwnProp( options, 'state' ) ) {
opts.state = options.state;
}
if ( hasOwnProp( options, 'copy' ) ) {
opts.copy = options.copy;
}
return null;
}
// EXPORTS //
module.exports = validate;
},{"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-boolean":81,"@stdlib/assert/is-nonnegative-integer":127,"@stdlib/assert/is-nonnegative-number":131,"@stdlib/assert/is-plain-object":147,"@stdlib/assert/is-positive-integer":149,"@stdlib/assert/is-string":162}],383:[function(require,module,exports){
module.exports={
"name": "@stdlib/random/streams/poisson",
"version": "0.0.0",
"description": "Create a readable stream for generating pseudorandom numbers drawn from a Poisson distribution.",
"license": "Apache-2.0",
"author": {
"name": "The Stdlib Authors",
"url": "https://github.com/stdlib-js/stdlib/graphs/contributors"
},
"contributors": [
{
"name": "The Stdlib Authors",
"url": "https://github.com/stdlib-js/stdlib/graphs/contributors"
}
],
"bin": {
"random-poisson": "./bin/cli"
},
"main": "./lib",
"directories": {
"benchmark": "./benchmark",
"doc": "./docs",
"example": "./examples",
"lib": "./lib",
"test": "./test"
},
"types": "./docs/types",
"scripts": {},
"homepage": "https://github.com/stdlib-js/stdlib",
"repository": {
"type": "git",
"url": "git://github.com/stdlib-js/stdlib.git"
},
"bugs": {
"url": "https://github.com/stdlib-js/stdlib/issues"
},
"dependencies": {},
"devDependencies": {},
"engines": {
"node": ">=0.10.0",
"npm": ">2.7.0"
},
"os": [
"aix",
"darwin",
"freebsd",
"linux",
"macos",
"openbsd",
"sunos",
"win32",
"windows"
],
"keywords": [
"stdlib",
"stdmath",
"mathematics",
"math",
"statistics",
"stats",
"prng",
"rng",
"pseudorandom",
"random",
"rand",
"poisson",
"continuous",
"readable",
"stream",
"seed",
"seedable"
]
}
},{}],384:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Regular expression to match a newline character sequence.
*
* @module @stdlib/regexp/eol
*
* @example
* var reEOL = require( '@stdlib/regexp/eol' );
* var RE_EOL = reEOL();
*
* var bool = RE_EOL.test( '\n' );
* // returns true
*
* bool = RE_EOL.test( '\\r\\n' );
* // returns false
*
* @example
* var reEOL = require( '@stdlib/regexp/eol' );
* var replace = require( '@stdlib/string/replace' );
*
* var RE_EOL = reEOL({
* 'flags': 'g'
* });
* var str = '1\n2\n3';
* var out = replace( str, RE_EOL, '' );
*
* @example
* var reEOL = require( '@stdlib/regexp/eol' );
* var bool = reEOL.REGEXP.test( '\r\n' );
* // returns true
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var reEOL = require( './main.js' );
var REGEXP_CAPTURE = require( './regexp_capture.js' );
var REGEXP = require( './regexp.js' );
// MAIN //
setReadOnly( reEOL, 'REGEXP', REGEXP );
setReadOnly( reEOL, 'REGEXP_CAPTURE', REGEXP_CAPTURE );
// EXPORTS //
module.exports = reEOL;
},{"./main.js":385,"./regexp.js":386,"./regexp_capture.js":387,"@stdlib/utils/define-nonenumerable-read-only-property":428}],385:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var validate = require( './validate.js' );
// VARIABLES //
var REGEXP_STRING = '\\r?\\n';
// MAIN //
/**
* Returns a regular expression to match a newline character sequence.
*
* @param {Options} [options] - function options
* @param {string} [options.flags=''] - regular expression flags
* @param {boolean} [options.capture=false] - boolean indicating whether to create a capture group for the match
* @throws {TypeError} options argument must be an object
* @throws {TypeError} must provide valid options
* @returns {RegExp} regular expression
*
* @example
* var RE_EOL = reEOL();
* var bool = RE_EOL.test( '\r\n' );
* // returns true
*
* @example
* var replace = require( '@stdlib/string/replace' );
*
* var RE_EOL = reEOL({
* 'flags': 'g'
* });
* var str = '1\n2\n3';
* var out = replace( str, RE_EOL, '' );
*/
function reEOL( options ) {
var opts;
var err;
if ( arguments.length > 0 ) {
opts = {};
err = validate( opts, options );
if ( err ) {
throw err;
}
if ( opts.capture ) {
return new RegExp( '('+REGEXP_STRING+')', opts.flags );
}
return new RegExp( REGEXP_STRING, opts.flags );
}
return /\r?\n/;
}
// EXPORTS //
module.exports = reEOL;
},{"./validate.js":388}],386:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var reEOL = require( './main.js' );
// MAIN //
/**
* Matches a newline character sequence.
*
* Regular expression: `/\r?\n/`
*
* - `\r?`
* - match a carriage return character (optional)
*
* - `\n`
* - match a line feed character
*
* @constant
* @type {RegExp}
* @default /\r?\n/
*/
var REGEXP = reEOL();
// EXPORTS //
module.exports = REGEXP;
},{"./main.js":385}],387:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var reEOL = require( './main.js' );
// MAIN //
/**
* Captures a newline character sequence.
*
* Regular expression: `/\r?\n/`
*
* - `()`
* - capture
*
* - `\r?`
* - match a carriage return character (optional)
*
* - `\n`
* - match a line feed character
*
* @constant
* @type {RegExp}
* @default /(\r?\n)/
*/
var REGEXP_CAPTURE = reEOL({
'capture': true
});
// EXPORTS //
module.exports = REGEXP_CAPTURE;
},{"./main.js":385}],388:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isObject = require( '@stdlib/assert/is-plain-object' );
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive;
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
// MAIN //
/**
* Validates function options.
*
* @private
* @param {Object} opts - destination object
* @param {Options} options - function options
* @param {string} [options.flags] - regular expression flags
* @param {boolean} [options.capture] - boolean indicating whether to wrap a regular expression matching a decimal number with a capture group
* @returns {(Error|null)} null or an error object
*
* @example
* var opts = {};
* var options = {
* 'flags': 'gm'
* };
* var err = validate( opts, options );
* if ( err ) {
* throw err;
* }
*/
function validate( opts, options ) {
if ( !isObject( options ) ) {
return new TypeError( 'invalid argument. Options must be an object. Value: `' + options + '`.' );
}
if ( hasOwnProp( options, 'flags' ) ) {
opts.flags = options.flags;
if ( !isString( opts.flags ) ) {
return new TypeError( 'invalid option. `flags` option must be a string primitive. Option: `' + opts.flags + '`.' );
}
}
if ( hasOwnProp( options, 'capture' ) ) {
opts.capture = options.capture;
if ( !isBoolean( opts.capture ) ) {
return new TypeError( 'invalid option. `capture` option must be a boolean primitive. Option: `' + opts.capture + '`.' );
}
}
return null;
}
// EXPORTS //
module.exports = validate;
},{"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-boolean":81,"@stdlib/assert/is-plain-object":147,"@stdlib/assert/is-string":162}],389:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Regular expression to capture everything that is not a space immediately after the `function` keyword and before the first left parenthesis.
*
* @module @stdlib/regexp/function-name
*
* @example
* var reFunctionName = require( '@stdlib/regexp/function-name' );
* var RE_FUNCTION_NAME = reFunctionName();
*
* function fname( fcn ) {
* return RE_FUNCTION_NAME.exec( fcn.toString() )[ 1 ];
* }
*
* var fn = fname( Math.sqrt );
* // returns 'sqrt'
*
* fn = fname( Int8Array );
* // returns 'Int8Array'
*
* fn = fname( Object.prototype.toString );
* // returns 'toString'
*
* fn = fname( function(){} );
* // returns ''
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var reFunctionName = require( './main.js' );
var REGEXP = require( './regexp.js' );
// MAIN //
setReadOnly( reFunctionName, 'REGEXP', REGEXP );
// EXPORTS //
module.exports = reFunctionName;
},{"./main.js":390,"./regexp.js":391,"@stdlib/utils/define-nonenumerable-read-only-property":428}],390:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Returns a regular expression to capture everything that is not a space immediately after the `function` keyword and before the first left parenthesis.
*
* @returns {RegExp} regular expression
*
* @example
* var RE_FUNCTION_NAME = reFunctionName();
*
* function fname( fcn ) {
* return RE_FUNCTION_NAME.exec( fcn.toString() )[ 1 ];
* }
*
* var fn = fname( Math.sqrt );
* // returns 'sqrt'
*
* fn = fname( Int8Array );
* // returns 'Int8Array'
*
* fn = fname( Object.prototype.toString );
* // returns 'toString'
*
* fn = fname( function(){} );
* // returns ''
*/
function reFunctionName() {
return /^\s*function\s*([^(]*)/i;
}
// EXPORTS //
module.exports = reFunctionName;
},{}],391:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var reFunctionName = require( './main.js' );
// MAIN //
/**
* Captures everything that is not a space immediately after the `function` keyword and before the first left parenthesis.
*
* Regular expression: `/^\s*function\s*([^(]*)/i`
*
* - `/^\s*`
* - Match zero or more spaces at beginning
*
* - `function`
* - Match the word `function`
*
* - `\s*`
* - Match zero or more spaces after the word `function`
*
* - `()`
* - Capture
*
* - `[^(]*`
* - Match anything except a left parenthesis `(` zero or more times
*
* - `/i`
* - ignore case
*
* @constant
* @type {RegExp}
* @default /^\s*function\s*([^(]*)/i
*/
var RE_FUNCTION_NAME = reFunctionName();
// EXPORTS //
module.exports = RE_FUNCTION_NAME;
},{"./main.js":390}],392:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Return a regular expression to parse a regular expression string.
*
* @module @stdlib/regexp/regexp
*
* @example
* var reRegExp = require( '@stdlib/regexp/regexp' );
*
* var RE_REGEXP = reRegExp();
*
* var bool = RE_REGEXP.test( '/^beep$/' );
* // returns true
*
* bool = RE_REGEXP.test( '' );
* // returns false
*
* @example
* var reRegExp = require( '@stdlib/regexp/regexp' );
*
* var RE_REGEXP = reRegExp();
*
* var parts = RE_REGEXP.exec( '/^.*$/ig' );
* // returns [ '/^.*$/ig', '^.*$', 'ig', 'index': 0, 'input': '/^.*$/ig' ]
*/
// MAIN //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var reRegExp = require( './main.js' );
var REGEXP = require( './regexp.js' );
// MAIN //
setReadOnly( reRegExp, 'REGEXP', REGEXP );
// EXPORTS //
module.exports = reRegExp;
// EXPORTS //
module.exports = reRegExp;
},{"./main.js":393,"./regexp.js":394,"@stdlib/utils/define-nonenumerable-read-only-property":428}],393:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Returns a regular expression to parse a regular expression string.
*
* @returns {RegExp} regular expression
*
* @example
* var RE_REGEXP = reRegExp();
*
* var bool = RE_REGEXP.test( '/^beep$/' );
* // returns true
*
* bool = RE_REGEXP.test( '' );
* // returns false
*/
function reRegExp() {
return /^\/((?:\\\/|[^\/])+)\/([imgy]*)$/; // eslint-disable-line no-useless-escape
}
// EXPORTS //
module.exports = reRegExp;
},{}],394:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var reRegExp = require( './main.js' );
// MAIN //
/**
* Matches parts of a regular expression string.
*
* Regular expression: `/^\/((?:\\\/|[^\/])+)\/([imgy]*)$/`
*
* - `/^\/`
* - match a string that begins with a `/`
*
* - `()`
* - capture
*
* - `(?:)+`
* - capture, but do not remember, a group of characters which occur one or more times
*
* - `\\\/`
* - match the literal `\/`
*
* - `|`
* - OR
*
* - `[^\/]`
* - anything which is not the literal `\/`
*
* - `\/`
* - match the literal `/`
*
* - `([imgy]*)`
* - capture any characters matching `imgy` occurring zero or more times
*
* - `$/`
* - string end
*
*
* @constant
* @type {RegExp}
* @default /^\/((?:\\\/|[^\/])+)\/([imgy]*)$/
*/
var RE_REGEXP = reRegExp();
// EXPORTS //
module.exports = RE_REGEXP;
},{"./main.js":393}],395:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var logger = require( 'debug' );
// VARIABLES //
var debug = logger( 'transform-stream:transform' );
// MAIN //
/**
* Implements the `_transform` method as a pass through.
*
* @private
* @param {(Uint8Array|Buffer|string)} chunk - streamed chunk
* @param {string} encoding - Buffer encoding
* @param {Callback} clbk - callback to invoke after transforming the streamed chunk
*/
function transform( chunk, encoding, clbk ) {
debug( 'Received a new chunk. Chunk: %s. Encoding: %s.', chunk.toString(), encoding );
clbk( null, chunk );
}
// EXPORTS //
module.exports = transform;
},{"debug":516}],396:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var logger = require( 'debug' );
var Transform = require( 'readable-stream' ).Transform;
var inherit = require( '@stdlib/utils/inherit' );
var copy = require( '@stdlib/utils/copy' );
var DEFAULTS = require( './defaults.json' );
var validate = require( './validate.js' );
var destroy = require( './destroy.js' );
var _transform = require( './_transform.js' ); // eslint-disable-line no-underscore-dangle
// VARIABLES //
var debug = logger( 'transform-stream:ctor' );
// MAIN //
/**
* Transform stream constructor factory.
*
* @param {Options} [options] - stream options
* @param {Function} [options.transform] - callback to invoke upon receiving a new chunk
* @param {Function} [options.flush] - callback to invoke after receiving all chunks and prior to the stream closing
* @param {boolean} [options.objectMode=false] - specifies whether a stream should operate in object mode
* @param {(string|null)} [options.encoding=null] - specifies how `Buffer` objects should be decoded to `strings`
* @param {NonNegativeNumber} [options.highWaterMark] - specifies the `Buffer` level for when `write()` starts returning `false`
* @param {boolean} [options.allowHalfOpen=false] - specifies whether the stream should remain open even if one side ends
* @param {boolean} [options.decodeStrings=true] - specifies whether to decode `strings` into `Buffer` objects when writing
* @throws {TypeError} options argument must be an object
* @throws {TypeError} must provide valid options
* @returns {Function} Transform stream constructor
*
* @example
* var stdout = require( '@stdlib/streams/node/stdout' );
*
* function transform( chunk, enc, clbk ) {
* clbk( null, chunk.toString()+'\n' );
* }
*
* var opts = {
* 'transform': transform
* };
*
* var TransformStream = ctor( opts );
*
* var stream = new TransformStream();
*
* stream.pipe( stdout );
*
* stream.write( '1' );
* stream.write( '2' );
* stream.write( '3' );
*
* stream.end();
*
* // prints: '1\n2\n3\n'
*/
function ctor( options ) {
var transform;
var copts;
var err;
copts = copy( DEFAULTS );
if ( arguments.length ) {
err = validate( copts, options );
if ( err ) {
throw err;
}
}
if ( copts.transform ) {
transform = copts.transform;
} else {
transform = _transform;
}
/**
* Transform stream constructor.
*
* @private
* @constructor
* @param {Options} [options] - stream options
* @param {boolean} [options.objectMode=false] - specifies whether a stream should operate in object mode
* @param {(string|null)} [options.encoding=null] - specifies how `Buffer` objects should be decoded to `strings`
* @param {NonNegativeNumber} [options.highWaterMark] - specifies the `Buffer` level for when `write()` starts returning `false`
* @param {boolean} [options.allowHalfOpen=false] - specifies whether the stream should remain open even if one side ends
* @param {boolean} [options.decodeStrings=true] - specifies whether to decode `strings` into `Buffer` objects when writing
* @throws {TypeError} options argument must be an object
* @throws {TypeError} must provide valid options
* @returns {TransformStream} transform stream
*
* @example
* var stdout = require( '@stdlib/streams/node/stdout' );
*
* var stream = new TransformStream();
*
* stream.pipe( stdout );
*
* stream.write( '1' );
* stream.write( '2' );
* stream.write( '3' );
*
* stream.end();
*
* // prints: '1\n2\n3\n'
*/
function TransformStream( options ) {
var opts;
var err;
if ( !( this instanceof TransformStream ) ) {
if ( arguments.length ) {
return new TransformStream( options );
}
return new TransformStream();
}
opts = copy( copts );
if ( arguments.length ) {
err = validate( opts, options );
if ( err ) {
throw err;
}
}
debug( 'Creating a transform stream configured with the following options: %s.', JSON.stringify( opts ) );
Transform.call( this, opts );
this._destroyed = false;
return this;
}
/**
* Inherit from the `Transform` prototype.
*/
inherit( TransformStream, Transform );
/**
* Implements the `_transform` method.
*
* @private
* @name _transform
* @memberof TransformStream.prototype
* @type {Function}
* @param {(Buffer|string)} chunk - streamed chunk
* @param {string} encoding - Buffer encoding
* @param {Callback} clbk - callback to invoke after transforming the streamed chunk
*/
TransformStream.prototype._transform = transform; // eslint-disable-line no-underscore-dangle
if ( copts.flush ) {
/**
* Implements the `_flush` method.
*
* @private
* @name _flush
* @memberof TransformStream.prototype
* @type {Function}
* @param {Callback} callback to invoke after performing flush tasks
*/
TransformStream.prototype._flush = copts.flush; // eslint-disable-line no-underscore-dangle
}
/**
* Gracefully destroys a stream, providing backward compatibility.
*
* @private
* @name destroy
* @memberof TransformStream.prototype
* @type {Function}
* @param {Object} [error] - optional error message
* @returns {TransformStream} stream instance
*/
TransformStream.prototype.destroy = destroy;
return TransformStream;
}
// EXPORTS //
module.exports = ctor;
},{"./_transform.js":395,"./defaults.json":397,"./destroy.js":398,"./validate.js":403,"@stdlib/utils/copy":422,"@stdlib/utils/inherit":460,"debug":516,"readable-stream":533}],397:[function(require,module,exports){
module.exports={
"objectMode": false,
"encoding": null,
"allowHalfOpen": false,
"decodeStrings": true
}
},{}],398:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var logger = require( 'debug' );
var nextTick = require( '@stdlib/utils/next-tick' );
// VARIABLES //
var debug = logger( 'transform-stream:destroy' );
// MAIN //
/**
* Gracefully destroys a stream, providing backward compatibility.
*
* @private
* @param {Object} [error] - optional error message
* @returns {Stream} stream instance
*/
function destroy( error ) {
/* eslint-disable no-invalid-this */
var self;
if ( this._destroyed ) {
debug( 'Attempted to destroy an already destroyed stream.' );
return this;
}
self = this;
this._destroyed = true;
nextTick( close );
return this;
/**
* Closes a stream.
*
* @private
*/
function close() {
if ( error ) {
debug( 'Stream was destroyed due to an error. Error: %s.', JSON.stringify( error ) );
self.emit( 'error', error );
}
debug( 'Closing the stream...' );
self.emit( 'close' );
}
}
// EXPORTS //
module.exports = destroy;
},{"@stdlib/utils/next-tick":486,"debug":516}],399:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isObject = require( '@stdlib/assert/is-plain-object' );
var copy = require( '@stdlib/utils/copy' );
var Stream = require( './main.js' );
// MAIN //
/**
* Creates a reusable transform stream factory.
*
* @param {Options} [options] - stream options
* @param {boolean} [options.objectMode=false] - specifies whether a stream should operate in object mode
* @param {(string|null)} [options.encoding=null] - specifies how `Buffer` objects should be decoded to `strings`
* @param {NonNegativeNumber} [options.highWaterMark] - specifies the `Buffer` level for when `write()` starts returning `false`
* @param {boolean} [options.allowHalfOpen=false] - specifies whether the stream should remain open even if one side ends
* @param {boolean} [options.decodeStrings=true] - specifies whether to decode `strings` into `Buffer` objects when writing
* @throws {TypeError} options argument must be an object
* @returns {Function} transform stream factory
*
* @example
* function transform( chunk, enc, clbk ) {
* clbk( null, chunk.toString()+'\n' );
* }
*
* var opts = {
* 'objectMode': true,
* 'encoding': 'utf8',
* 'highWaterMark': 64,
* 'decodeStrings': false
* };
*
* var factory = streamFactory( opts );
*
* // Create 10 identically configured streams...
* var streams = [];
* var i;
* for ( i = 0; i < 10; i++ ) {
* streams.push( factory( transform ) );
* }
*/
function streamFactory( options ) {
var opts;
if ( arguments.length ) {
if ( !isObject( options ) ) {
throw new TypeError( 'invalid argument. Options argument must be an object. Value: `' + options + '`.' );
}
opts = copy( options );
} else {
opts = {};
}
return createStream;
/**
* Creates a transform stream.
*
* @private
* @param {Function} transform - callback to invoke upon receiving a new chunk
* @param {Function} [flush] - callback to invoke after receiving all chunks and prior to the stream closing
* @throws {TypeError} must provide valid options
* @throws {TypeError} transform callback must be a function
* @throws {TypeError} flush callback must be a function
* @returns {TransformStream} transform stream
*/
function createStream( transform, flush ) {
opts.transform = transform;
if ( arguments.length > 1 ) {
opts.flush = flush;
} else {
delete opts.flush; // clear any previous `flush`
}
return new Stream( opts );
}
}
// EXPORTS //
module.exports = streamFactory;
},{"./main.js":401,"@stdlib/assert/is-plain-object":147,"@stdlib/utils/copy":422}],400:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Transform stream.
*
* @module @stdlib/streams/node/transform
*
* @example
* var stdout = require( '@stdlib/streams/node/stdout' );
* var transformStream = require( '@stdlib/streams/node/transform' );
*
* function transform( chunk, enc, clbk ) {
* clbk( null, chunk.toString()+'\n' );
* }
*
* var opts = {
* 'transform': transform
* };
* var stream = transformStream( opts );
*
* stream.pipe( stdout );
*
* stream.write( '1' );
* stream.write( '2' );
* stream.write( '3' );
*
* stream.end();
* // => '1\n2\n3\n'
*
*
* @example
* var transformStream = require( '@stdlib/streams/node/transform' );
*
* function transform( chunk, enc, clbk ) {
* clbk( null, chunk.toString()+'\n' );
* }
*
* var opts = {
* 'objectMode': true,
* 'encoding': 'utf8',
* 'highWaterMark': 64,
* 'decodeStrings': false
* };
*
* var factory = transformStream.factory( opts );
*
* // Create 10 identically configured streams...
* var streams = [];
* var i;
* for ( i = 0; i < 10; i++ ) {
* streams.push( factory( transform ) );
* }
*
*
* @example
* var stdout = require( '@stdlib/streams/node/stdout' );
* var transformStream = require( '@stdlib/streams/node/transform' );
*
* function stringify( chunk, enc, clbk ) {
* clbk( null, JSON.stringify( chunk ) );
* }
*
* function newline( chunk, enc, clbk ) {
* clbk( null, chunk+'\n' );
* }
*
* var s1 = transformStream.objectMode({
* 'transform': stringify
* });
*
* var s2 = transformStream.objectMode({
* 'transform': newline
* });
*
* s1.pipe( s2 ).pipe( stdout );
*
* s1.write( {'value': 'a'} );
* s1.write( {'value': 'b'} );
* s1.write( {'value': 'c'} );
*
* s1.end();
* // => '{"value":"a"}\n{"value":"b"}\n{"value":"c"}\n'
*
*
* @example
* var stdout = require( '@stdlib/streams/node/stdout' );
* var transformStream = require( '@stdlib/streams/node/transform' );
*
* function transform( chunk, enc, clbk ) {
* clbk( null, chunk.toString()+'\n' );
* }
*
* var opts = {
* 'transform': transform
* };
*
* var Stream = transformStream.ctor( opts );
*
* var stream = new Stream();
*
* stream.pipe( stdout );
*
* stream.write( '1' );
* stream.write( '2' );
* stream.write( '3' );
*
* stream.end();
* // => '1\n2\n3\n'
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var transform = require( './main.js' );
var objectMode = require( './object_mode.js' );
var factory = require( './factory.js' );
var ctor = require( './ctor.js' );
// MAIN //
setReadOnly( transform, 'objectMode', objectMode );
setReadOnly( transform, 'factory', factory );
setReadOnly( transform, 'ctor', ctor );
// EXPORTS //
module.exports = transform;
},{"./ctor.js":396,"./factory.js":399,"./main.js":401,"./object_mode.js":402,"@stdlib/utils/define-nonenumerable-read-only-property":428}],401:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var logger = require( 'debug' );
var Transform = require( 'readable-stream' ).Transform;
var inherit = require( '@stdlib/utils/inherit' );
var copy = require( '@stdlib/utils/copy' );
var DEFAULTS = require( './defaults.json' );
var validate = require( './validate.js' );
var destroy = require( './destroy.js' );
var _transform = require( './_transform.js' ); // eslint-disable-line no-underscore-dangle
// VARIABLES //
var debug = logger( 'transform-stream:main' );
// MAIN //
/**
* Transform stream constructor.
*
* @constructor
* @param {Options} [options] - stream options
* @param {Function} [options.transform] - callback to invoke upon receiving a new chunk
* @param {Function} [options.flush] - callback to invoke after receiving all chunks and prior to the stream closing
* @param {boolean} [options.objectMode=false] - specifies whether stream should operate in object mode
* @param {(string|null)} [options.encoding=null] - specifies how `Buffer` objects should be decoded to `strings`
* @param {NonNegativeNumber} [options.highWaterMark] - specifies the `Buffer` level for when `write()` starts returning `false`
* @param {boolean} [options.allowHalfOpen=false] - specifies whether the stream should remain open even if one side ends
* @param {boolean} [options.decodeStrings=true] - specifies whether to decode `strings` into `Buffer` objects when writing
* @throws {TypeError} must provide valid options
* @returns {TransformStream} transform stream
*
* @example
* var stdout = require( '@stdlib/streams/node/stdout' );
*
* function transform( chunk, enc, clbk ) {
* clbk( null, chunk.toString()+'\n' );
* }
*
* var opts = {
* 'transform': transform
* };
* var stream = new TransformStream( opts );
*
* stream.pipe( stdout );
*
* stream.write( '1' );
* stream.write( '2' );
* stream.write( '3' );
*
* stream.end();
*
* // prints: '1\n2\n3\n'
*/
function TransformStream( options ) {
var opts;
var err;
if ( !( this instanceof TransformStream ) ) {
if ( arguments.length ) {
return new TransformStream( options );
}
return new TransformStream();
}
opts = copy( DEFAULTS );
if ( arguments.length ) {
err = validate( opts, options );
if ( err ) {
throw err;
}
}
debug( 'Creating a transform stream configured with the following options: %s.', JSON.stringify( opts ) );
Transform.call( this, opts );
this._destroyed = false;
if ( opts.transform ) {
this._transform = opts.transform;
} else {
this._transform = _transform;
}
if ( opts.flush ) {
this._flush = opts.flush;
}
return this;
}
/*
* Inherit from the `Transform` prototype.
*/
inherit( TransformStream, Transform );
/**
* Gracefully destroys a stream, providing backward compatibility.
*
* @name destroy
* @memberof TransformStream.prototype
* @type {Function}
* @param {Object} [error] - optional error message
* @returns {TransformStream} stream instance
*/
TransformStream.prototype.destroy = destroy;
// EXPORTS //
module.exports = TransformStream;
},{"./_transform.js":395,"./defaults.json":397,"./destroy.js":398,"./validate.js":403,"@stdlib/utils/copy":422,"@stdlib/utils/inherit":460,"debug":516,"readable-stream":533}],402:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isObject = require( '@stdlib/assert/is-plain-object' );
var copy = require( '@stdlib/utils/copy' );
var Stream = require( './main.js' );
// MAIN //
/**
* Returns a transform stream with `objectMode` set to `true`.
*
* @param {Options} [options] - stream options
* @param {Function} [options.transform] - callback to invoke upon receiving a new chunk
* @param {Function} [options.flush] - callback to invoke after receiving all chunks and prior to the stream closing
* @param {(string|null)} [options.encoding=null] - specifies how `Buffer` objects should be decoded to `strings`
* @param {NonNegativeNumber} [options.highWaterMark] - specifies the `Buffer` level for when `write()` starts returning `false`
* @param {boolean} [options.allowHalfOpen=false] - specifies whether the stream should remain open even if one side ends
* @param {boolean} [options.decodeStrings=true] - specifies whether to decode `strings` into `Buffer` objects when writing
* @throws {TypeError} options argument must be an object
* @throws {TypeError} must provide valid options
* @returns {TransformStream} transform stream
*
* @example
* var stdout = require( '@stdlib/streams/node/stdout' );
*
* function stringify( chunk, enc, clbk ) {
* clbk( null, JSON.stringify( chunk ) );
* }
*
* function newline( chunk, enc, clbk ) {
* clbk( null, chunk+'\n' );
* }
*
* var s1 = objectMode({
* 'transform': stringify
* });
*
* var s2 = objectMode({
* 'transform': newline
* });
*
* s1.pipe( s2 ).pipe( stdout );
*
* s1.write( {'value': 'a'} );
* s1.write( {'value': 'b'} );
* s1.write( {'value': 'c'} );
*
* s1.end();
*
* // prints: '{"value":"a"}\n{"value":"b"}\n{"value":"c"}\n'
*/
function objectMode( options ) {
var opts;
if ( arguments.length ) {
if ( !isObject( options ) ) {
throw new TypeError( 'invalid argument. Options argument must be an object. Value: `' + options + '`.' );
}
opts = copy( options );
} else {
opts = {};
}
opts.objectMode = true;
return new Stream( opts );
}
// EXPORTS //
module.exports = objectMode;
},{"./main.js":401,"@stdlib/assert/is-plain-object":147,"@stdlib/utils/copy":422}],403:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isObject = require( '@stdlib/assert/is-plain-object' );
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var isFunction = require( '@stdlib/assert/is-function' );
var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive;
var isNonNegative = require( '@stdlib/assert/is-nonnegative-number' ).isPrimitive;
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
// MAIN //
/**
* Validates function options.
*
* @private
* @param {Object} opts - destination object
* @param {Options} options - function options
* @param {Function} [options.transform] - callback to invoke upon receiving a new chunk
* @param {Function} [options.flush] - callback to invoke after receiving all chunks and prior to the stream closing
* @param {boolean} [options.objectMode] - specifies whether a stream should operate in object mode
* @param {(string|null)} [options.encoding] - specifies how `Buffer` objects should be decoded to `strings`
* @param {NonNegativeNumber} [options.highWaterMark] - specifies the `Buffer` level for when `write()` starts returning `false`
* @param {boolean} [options.allowHalfOpen] - specifies whether the stream should remain open even if one side ends
* @param {boolean} [options.decodeStrings] - specifies whether to decode `strings` into `Buffer` objects when writing
* @returns {(Error|null)} null or an error object
*/
function validate( opts, options ) {
if ( !isObject( options ) ) {
return new TypeError( 'invalid argument. Options must be an object. Value: `' + options + '`.' );
}
if ( hasOwnProp( options, 'transform' ) ) {
opts.transform = options.transform;
if ( !isFunction( opts.transform ) ) {
return new TypeError( 'invalid option. `transform` option must be a function. Option: `' + opts.transform + '`.' );
}
}
if ( hasOwnProp( options, 'flush' ) ) {
opts.flush = options.flush;
if ( !isFunction( opts.flush ) ) {
return new TypeError( 'invalid option. `flush` option must be a function. Option: `' + opts.flush + '`.' );
}
}
if ( hasOwnProp( options, 'objectMode' ) ) {
opts.objectMode = options.objectMode;
if ( !isBoolean( opts.objectMode ) ) {
return new TypeError( 'invalid option. `objectMode` option must be a primitive boolean. Option: `' + opts.objectMode + '`.' );
}
}
if ( hasOwnProp( options, 'encoding' ) ) {
opts.encoding = options.encoding;
if ( !isString( opts.encoding ) ) {
return new TypeError( 'invalid option. `encoding` option must be a primitive string. Option: `' + opts.encoding + '`.' );
}
}
if ( hasOwnProp( options, 'allowHalfOpen' ) ) {
opts.allowHalfOpen = options.allowHalfOpen;
if ( !isBoolean( opts.allowHalfOpen ) ) {
return new TypeError( 'invalid option. `allowHalfOpen` option must be a primitive boolean. Option: `' + opts.allowHalfOpen + '`.' );
}
}
if ( hasOwnProp( options, 'highWaterMark' ) ) {
opts.highWaterMark = options.highWaterMark;
if ( !isNonNegative( opts.highWaterMark ) ) {
return new TypeError( 'invalid option. `highWaterMark` option must be a nonnegative number. Option: `' + opts.highWaterMark + '`.' );
}
}
if ( hasOwnProp( options, 'decodeStrings' ) ) {
opts.decodeStrings = options.decodeStrings;
if ( !isBoolean( opts.decodeStrings ) ) {
return new TypeError( 'invalid option. `decodeStrings` option must be a primitive boolean. Option: `' + opts.decodeStrings + '`.' );
}
}
return null;
}
// EXPORTS //
module.exports = validate;
},{"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-boolean":81,"@stdlib/assert/is-function":102,"@stdlib/assert/is-nonnegative-number":131,"@stdlib/assert/is-plain-object":147,"@stdlib/assert/is-string":162}],404:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Create a string from a sequence of Unicode code points.
*
* @module @stdlib/string/from-code-point
*
* @example
* var fromCodePoint = require( '@stdlib/string/from-code-point' );
*
* var str = fromCodePoint( 9731 );
* // returns '☃'
*/
// MODULES //
var fromCodePoint = require( './main.js' );
// EXPORTS //
module.exports = fromCodePoint;
},{"./main.js":405}],405:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ).isPrimitive;
var isCollection = require( '@stdlib/assert/is-collection' );
var UNICODE_MAX = require( '@stdlib/constants/unicode/max' );
var UNICODE_MAX_BMP = require( '@stdlib/constants/unicode/max-bmp' );
// VARIABLES //
var fromCharCode = String.fromCharCode;
// Factor to rescale a code point from a supplementary plane:
var Ox10000 = 0x10000|0; // 65536
// Factor added to obtain a high surrogate:
var OxD800 = 0xD800|0; // 55296
// Factor added to obtain a low surrogate:
var OxDC00 = 0xDC00|0; // 56320
// 10-bit mask: 2^10-1 = 1023 => 0x3ff => 00000000 00000000 00000011 11111111
var Ox3FF = 1023|0;
// MAIN //
/**
* Creates a string from a sequence of Unicode code points.
*
* ## Notes
*
* - UTF-16 encoding uses one 16-bit unit for non-surrogates (U+0000 to U+D7FF and U+E000 to U+FFFF).
* - UTF-16 encoding uses two 16-bit units (surrogate pairs) for U+10000 to U+10FFFF and encodes U+10000-U+10FFFF by subtracting 0x10000 from the code point, expressing the result as a 20-bit binary, and splitting the 20 bits of 0x0-0xFFFFF as upper and lower 10-bits. The respective 10-bits are stored in two 16-bit words: a high and a low surrogate.
*
*
* @param {...NonNegativeInteger} args - sequence of code points
* @throws {Error} must provide either an array-like object of code points or one or more code points as separate arguments
* @throws {TypeError} a code point must be a nonnegative integer
* @throws {RangeError} must provide a valid Unicode code point
* @returns {string} created string
*
* @example
* var str = fromCodePoint( 9731 );
* // returns '☃'
*/
function fromCodePoint( args ) {
var len;
var str;
var arr;
var low;
var hi;
var pt;
var i;
len = arguments.length;
if ( len === 1 && isCollection( args ) ) {
arr = arguments[ 0 ];
len = arr.length;
} else {
arr = [];
for ( i = 0; i < len; i++ ) {
arr.push( arguments[ i ] );
}
}
if ( len === 0 ) {
throw new Error( 'insufficient input arguments. Must provide either an array of code points or one or more code points as separate arguments.' );
}
str = '';
for ( i = 0; i < len; i++ ) {
pt = arr[ i ];
if ( !isNonNegativeInteger( pt ) ) {
throw new TypeError( 'invalid argument. Must provide valid code points (nonnegative integers). Value: `'+pt+'`.' );
}
if ( pt > UNICODE_MAX ) {
throw new RangeError( 'invalid argument. Must provide a valid code point (cannot exceed max). Value: `'+pt+'`.' );
}
if ( pt <= UNICODE_MAX_BMP ) {
str += fromCharCode( pt );
} else {
// Code point from a supplementary plane. Split into two 16-bit code units (surrogate pair).
pt -= Ox10000;
hi = (pt >> 10) + OxD800;
low = (pt & Ox3FF) + OxDC00;
str += fromCharCode( hi, low );
}
}
return str;
}
// EXPORTS //
module.exports = fromCodePoint;
},{"@stdlib/assert/is-collection":90,"@stdlib/assert/is-nonnegative-integer":127,"@stdlib/constants/unicode/max":267,"@stdlib/constants/unicode/max-bmp":266}],406:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Replace search occurrences with a replacement string.
*
* @module @stdlib/string/replace
*
* @example
* var replace = require( '@stdlib/string/replace' );
*
* var str = 'beep';
* var out = replace( str, 'e', 'o' );
* // returns 'boop'
*
* str = 'Hello World';
* out = replace( str, /world/i, 'Mr. President' );
* // returns 'Hello Mr. President'
*/
// MODULES //
var replace = require( './replace.js' );
// EXPORTS //
module.exports = replace;
},{"./replace.js":407}],407:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var rescape = require( '@stdlib/utils/escape-regexp-string' );
var isFunction = require( '@stdlib/assert/is-function' );
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var isRegExp = require( '@stdlib/assert/is-regexp' );
// MAIN //
/**
* Replace search occurrences with a replacement string.
*
* @param {string} str - input string
* @param {(string|RegExp)} search - search expression
* @param {(string|Function)} newval - replacement value or function
* @throws {TypeError} first argument must be a string primitive
* @throws {TypeError} second argument argument must be a string primitive or regular expression
* @throws {TypeError} third argument must be a string primitive or function
* @returns {string} new string containing replacement(s)
*
* @example
* var str = 'beep';
* var out = replace( str, 'e', 'o' );
* // returns 'boop'
*
* @example
* var str = 'Hello World';
* var out = replace( str, /world/i, 'Mr. President' );
* // returns 'Hello Mr. President'
*
* @example
* var capitalize = require( '@stdlib/string/capitalize' );
*
* var str = 'Oranges and lemons say the bells of St. Clement\'s';
*
* function replacer( match, p1 ) {
* return capitalize( p1 );
* }
*
* var out = replace( str, /([^\s]*)/gi, replacer);
* // returns 'Oranges And Lemons Say The Bells Of St. Clement\'s'
*/
function replace( str, search, newval ) {
if ( !isString( str ) ) {
throw new TypeError( 'invalid argument. First argument must be a string primitive. Value: `' + str + '`.' );
}
if ( isString( search ) ) {
search = rescape( search );
search = new RegExp( search, 'g' );
}
else if ( !isRegExp( search ) ) {
throw new TypeError( 'invalid argument. Second argument must be a string primitive or regular expression. Value: `' + search + '`.' );
}
if ( !isString( newval ) && !isFunction( newval ) ) {
throw new TypeError( 'invalid argument. Third argument must be a string primitive or replacement function. Value: `' + newval + '`.' );
}
return str.replace( search, newval );
}
// EXPORTS //
module.exports = replace;
},{"@stdlib/assert/is-function":102,"@stdlib/assert/is-regexp":158,"@stdlib/assert/is-string":162,"@stdlib/utils/escape-regexp-string":441}],408:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Trim whitespace characters from the beginning and end of a string.
*
* @module @stdlib/string/trim
*
* @example
* var trim = require( '@stdlib/string/trim' );
*
* var out = trim( ' Whitespace ' );
* // returns 'Whitespace'
*
* out = trim( '\t\t\tTabs\t\t\t' );
* // returns 'Tabs'
*
* out = trim( '\n\n\nNew Lines\n\n\n' );
* // returns 'New Lines'
*/
// MODULES //
var trim = require( './trim.js' );
// EXPORTS //
module.exports = trim;
},{"./trim.js":409}],409:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var replace = require( '@stdlib/string/replace' );
// VARIABLES //
// The following regular expression should suffice to polyfill (most?) all environments.
var RE = /^[\u0020\f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]*([\S\s]*?)[\u0020\f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]*$/;
// MAIN //
/**
* Trim whitespace characters from beginning and end of a string.
*
* @param {string} str - input string
* @throws {TypeError} must provide a string primitive
* @returns {string} trimmed string
*
* @example
* var out = trim( ' Whitespace ' );
* // returns 'Whitespace'
*
* @example
* var out = trim( '\t\t\tTabs\t\t\t' );
* // returns 'Tabs'
*
* @example
* var out = trim( '\n\n\nNew Lines\n\n\n' );
* // returns 'New Lines'
*/
function trim( str ) {
if ( !isString( str ) ) {
throw new TypeError( 'invalid argument. Must provide a string primitive. Value: `' + str + '`.' );
}
return replace( str, RE, '$1' );
}
// EXPORTS //
module.exports = trim;
},{"@stdlib/assert/is-string":162,"@stdlib/string/replace":406}],410:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var getGlobal = require( '@stdlib/utils/global' );
var isObject = require( '@stdlib/assert/is-object' );
var modf = require( '@stdlib/math/base/special/modf' );
var round = require( '@stdlib/math/base/special/round' );
var now = require( './now.js' );
// VARIABLES //
var Global = getGlobal();
var ts;
var ns;
if ( isObject( Global.performance ) ) {
ns = Global.performance;
} else {
ns = {};
}
if ( ns.now ) {
ts = ns.now.bind( ns );
} else if ( ns.mozNow ) {
ts = ns.mozNow.bind( ns );
} else if ( ns.msNow ) {
ts = ns.msNow.bind( ns );
} else if ( ns.oNow ) {
ts = ns.oNow.bind( ns );
} else if ( ns.webkitNow ) {
ts = ns.webkitNow.bind( ns );
} else {
ts = now;
}
// MAIN //
/**
* Returns a high-resolution time.
*
* ## Notes
*
* - Output format: `[seconds, nanoseconds]`.
*
*
* @private
* @returns {NumberArray} high-resolution time
*
* @example
* var t = tic();
* // returns [<number>,<number>]
*/
function tic() {
var parts;
var t;
// Get a millisecond timestamp and convert to seconds:
t = ts() / 1000;
// Decompose the timestamp into integer (seconds) and fractional parts:
parts = modf( t );
// Convert the fractional part to nanoseconds:
parts[ 1 ] = round( parts[1] * 1.0e9 );
// Return the high-resolution time:
return parts;
}
// EXPORTS //
module.exports = tic;
},{"./now.js":412,"@stdlib/assert/is-object":145,"@stdlib/math/base/special/modf":320,"@stdlib/math/base/special/round":327,"@stdlib/utils/global":453}],411:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isFunction = require( '@stdlib/assert/is-function' );
// MAIN //
var bool = isFunction( Date.now );
// EXPORTS //
module.exports = bool;
},{"@stdlib/assert/is-function":102}],412:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var bool = require( './detect.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var now;
if ( bool ) {
now = Date.now;
} else {
now = polyfill;
}
// EXPORTS //
module.exports = now;
},{"./detect.js":411,"./polyfill.js":413}],413:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Returns the time in milliseconds since the epoch.
*
* @private
* @returns {number} time
*
* @example
* var ts = now();
* // returns <number>
*/
function now() {
var d = new Date();
return d.getTime();
}
// EXPORTS //
module.exports = now;
},{}],414:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Return a high-resolution time difference.
*
* @module @stdlib/time/toc
*
* @example
* var tic = require( '@stdlib/time/tic' );
* var toc = require( '@stdlib/time/toc' );
*
* var start = tic();
* var delta = toc( start );
* // returns [<number>,<number>]
*/
// MODULES //
var toc = require( './toc.js' );
// EXPORTS //
module.exports = toc;
},{"./toc.js":415}],415:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isNonNegativeIntegerArray = require( '@stdlib/assert/is-nonnegative-integer-array' ).primitives;
var tic = require( '@stdlib/time/tic' );
// MAIN //
/**
* Returns a high-resolution time difference.
*
* ## Notes
*
* - Output format: `[seconds, nanoseconds]`.
*
*
* @param {NonNegativeIntegerArray} time - high-resolution time
* @throws {TypeError} must provide a nonnegative integer array
* @throws {RangeError} input array must have length `2`
* @returns {NumberArray} high resolution time difference
*
* @example
* var tic = require( '@stdlib/time/tic' );
*
* var start = tic();
* var delta = toc( start );
* // returns [<number>,<number>]
*/
function toc( time ) {
var now = tic();
var sec;
var ns;
if ( !isNonNegativeIntegerArray( time ) ) {
throw new TypeError( 'invalid argument. Must provide an array of nonnegative integers. Value: `' + time + '`.' );
}
if ( time.length !== 2 ) {
throw new RangeError( 'invalid argument. Input array must have length `2`.' );
}
sec = now[ 0 ] - time[ 0 ];
ns = now[ 1 ] - time[ 1 ];
if ( sec > 0 && ns < 0 ) {
sec -= 1;
ns += 1e9;
}
else if ( sec < 0 && ns > 0 ) {
sec += 1;
ns -= 1e9;
}
return [ sec, ns ];
}
// EXPORTS //
module.exports = toc;
},{"@stdlib/assert/is-nonnegative-integer-array":126,"@stdlib/time/tic":410}],416:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Creates a function which always returns the same value.
*
* @param {*} [value] - value to always return
* @returns {Function} constant function
*
* @example
* var fcn = wrap( 3.14 );
*
* var v = fcn();
* // returns 3.14
*
* v = fcn();
* // returns 3.14
*
* v = fcn();
* // returns 3.14
*/
function wrap( value ) {
return constantFunction;
/**
* Constant function.
*
* @private
* @returns {*} constant value
*/
function constantFunction() {
return value;
}
}
// EXPORTS //
module.exports = wrap;
},{}],417:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Create a constant function.
*
* @module @stdlib/utils/constant-function
*
* @example
* var constantFunction = require( '@stdlib/utils/constant-function' );
*
* var fcn = constantFunction( 3.14 );
*
* var v = fcn();
* // returns 3.14
*
* v = fcn();
* // returns 3.14
*
* v = fcn();
* // returns 3.14
*/
// MODULES //
var constantFunction = require( './constant_function.js' );
// EXPORTS //
module.exports = constantFunction;
},{"./constant_function.js":416}],418:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Determine the name of a value's constructor.
*
* @module @stdlib/utils/constructor-name
*
* @example
* var constructorName = require( '@stdlib/utils/constructor-name' );
*
* var v = constructorName( 'a' );
* // returns 'String'
*
* v = constructorName( {} );
* // returns 'Object'
*
* v = constructorName( true );
* // returns 'Boolean'
*/
// MODULES //
var constructorName = require( './main.js' );
// EXPORTS //
module.exports = constructorName;
},{"./main.js":419}],419:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var nativeClass = require( '@stdlib/utils/native-class' );
var RE = require( '@stdlib/regexp/function-name' ).REGEXP;
var isBuffer = require( '@stdlib/assert/is-buffer' );
// MAIN //
/**
* Determines the name of a value's constructor.
*
* @param {*} v - input value
* @returns {string} name of a value's constructor
*
* @example
* var v = constructorName( 'a' );
* // returns 'String'
*
* @example
* var v = constructorName( 5 );
* // returns 'Number'
*
* @example
* var v = constructorName( null );
* // returns 'Null'
*
* @example
* var v = constructorName( undefined );
* // returns 'Undefined'
*
* @example
* var v = constructorName( function noop() {} );
* // returns 'Function'
*/
function constructorName( v ) {
var match;
var name;
var ctor;
name = nativeClass( v ).slice( 8, -1 );
if ( (name === 'Object' || name === 'Error') && v.constructor ) {
ctor = v.constructor;
if ( typeof ctor.name === 'string' ) {
return ctor.name;
}
match = RE.exec( ctor.toString() );
if ( match ) {
return match[ 1 ];
}
}
if ( isBuffer( v ) ) {
return 'Buffer';
}
return name;
}
// EXPORTS //
module.exports = constructorName;
},{"@stdlib/assert/is-buffer":88,"@stdlib/regexp/function-name":389,"@stdlib/utils/native-class":481}],420:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isArray = require( '@stdlib/assert/is-array' );
var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ).isPrimitive;
var PINF = require( '@stdlib/constants/float64/pinf' );
var deepCopy = require( './deep_copy.js' );
// MAIN //
/**
* Copies or deep clones a value to an arbitrary depth.
*
* @param {*} value - value to copy
* @param {NonNegativeInteger} [level=+infinity] - copy depth
* @throws {TypeError} `level` must be a nonnegative integer
* @returns {*} value copy
*
* @example
* var out = copy( 'beep' );
* // returns 'beep'
*
* @example
* var value = [
* {
* 'a': 1,
* 'b': true,
* 'c': [ 1, 2, 3 ]
* }
* ];
* var out = copy( value );
* // returns [ { 'a': 1, 'b': true, 'c': [ 1, 2, 3 ] } ]
*
* var bool = ( value[0].c === out[0].c );
* // returns false
*/
function copy( value, level ) {
var out;
if ( arguments.length > 1 ) {
if ( !isNonNegativeInteger( level ) ) {
throw new TypeError( 'invalid argument. `level` must be a nonnegative integer. Value: `' + level + '`.' );
}
if ( level === 0 ) {
return value;
}
} else {
level = PINF;
}
out = ( isArray( value ) ) ? new Array( value.length ) : {};
return deepCopy( value, out, [value], [out], level );
}
// EXPORTS //
module.exports = copy;
},{"./deep_copy.js":421,"@stdlib/assert/is-array":79,"@stdlib/assert/is-nonnegative-integer":127,"@stdlib/constants/float64/pinf":255}],421:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var isArray = require( '@stdlib/assert/is-array' );
var isBuffer = require( '@stdlib/assert/is-buffer' );
var isError = require( '@stdlib/assert/is-error' );
var typeOf = require( '@stdlib/utils/type-of' );
var regexp = require( '@stdlib/utils/regexp-from-string' );
var indexOf = require( '@stdlib/utils/index-of' );
var objectKeys = require( '@stdlib/utils/keys' );
var propertyNames = require( '@stdlib/utils/property-names' );
var propertyDescriptor = require( '@stdlib/utils/property-descriptor' );
var getPrototypeOf = require( '@stdlib/utils/get-prototype-of' );
var defineProperty = require( '@stdlib/utils/define-property' );
var copyBuffer = require( '@stdlib/buffer/from-buffer' );
var typedArrays = require( './typed_arrays.js' );
// FUNCTIONS //
/**
* Clones a class instance.
*
* ## Notes
*
* - This should **only** be used for simple cases. Any instances with privileged access to variables (e.g., within closures) cannot be cloned. This approach should be considered **fragile**.
* - The function is greedy, disregarding the notion of a `level`. Instead, the function deep copies all properties, as we assume the concept of `level` applies only to the class instance reference but not to its internal state. This prevents, in theory, two instances from sharing state.
*
*
* @private
* @param {Object} val - class instance
* @returns {Object} new instance
*/
function cloneInstance( val ) {
var cache;
var names;
var name;
var refs;
var desc;
var tmp;
var ref;
var i;
cache = [];
refs = [];
ref = Object.create( getPrototypeOf( val ) );
cache.push( val );
refs.push( ref );
names = propertyNames( val );
for ( i = 0; i < names.length; i++ ) {
name = names[ i ];
desc = propertyDescriptor( val, name );
if ( hasOwnProp( desc, 'value' ) ) {
tmp = ( isArray( val[name] ) ) ? [] : {};
desc.value = deepCopy( val[name], tmp, cache, refs, -1 );
}
defineProperty( ref, name, desc );
}
if ( !Object.isExtensible( val ) ) {
Object.preventExtensions( ref );
}
if ( Object.isSealed( val ) ) {
Object.seal( ref );
}
if ( Object.isFrozen( val ) ) {
Object.freeze( ref );
}
return ref;
}
/**
* Copies an error object.
*
* @private
* @param {(Error|TypeError|SyntaxError|URIError|ReferenceError|RangeError|EvalError)} error - error to copy
* @returns {(Error|TypeError|SyntaxError|URIError|ReferenceError|RangeError|EvalError)} error copy
*
* @example
* var err1 = new TypeError( 'beep' );
*
* var err2 = copyError( err1 );
* // returns <TypeError>
*/
function copyError( error ) {
var cache = [];
var refs = [];
var keys;
var desc;
var tmp;
var key;
var err;
var i;
// Create a new error...
err = new error.constructor( error.message );
cache.push( error );
refs.push( err );
// If a `stack` property is present, copy it over...
if ( error.stack ) {
err.stack = error.stack;
}
// Node.js specific (system errors)...
if ( error.code ) {
err.code = error.code;
}
if ( error.errno ) {
err.errno = error.errno;
}
if ( error.syscall ) {
err.syscall = error.syscall;
}
// Any enumerable properties...
keys = objectKeys( error );
for ( i = 0; i < keys.length; i++ ) {
key = keys[ i ];
desc = propertyDescriptor( error, key );
if ( hasOwnProp( desc, 'value' ) ) {
tmp = ( isArray( error[ key ] ) ) ? [] : {};
desc.value = deepCopy( error[ key ], tmp, cache, refs, -1 );
}
defineProperty( err, key, desc );
}
return err;
}
// MAIN //
/**
* Recursively performs a deep copy of an input object.
*
* @private
* @param {*} val - value to copy
* @param {(Array|Object)} copy - copy
* @param {Array} cache - an array of visited objects
* @param {Array} refs - an array of object references
* @param {NonNegativeInteger} level - copy depth
* @returns {*} deep copy
*/
function deepCopy( val, copy, cache, refs, level ) {
var parent;
var keys;
var name;
var desc;
var ctor;
var key;
var ref;
var x;
var i;
var j;
level -= 1;
// Primitives and functions...
if (
typeof val !== 'object' ||
val === null
) {
return val;
}
if ( isBuffer( val ) ) {
return copyBuffer( val );
}
if ( isError( val ) ) {
return copyError( val );
}
// Objects...
name = typeOf( val );
if ( name === 'date' ) {
return new Date( +val );
}
if ( name === 'regexp' ) {
return regexp( val.toString() );
}
if ( name === 'set' ) {
return new Set( val );
}
if ( name === 'map' ) {
return new Map( val );
}
if (
name === 'string' ||
name === 'boolean' ||
name === 'number'
) {
// If provided an `Object`, return an equivalent primitive!
return val.valueOf();
}
ctor = typedArrays[ name ];
if ( ctor ) {
return ctor( val );
}
// Class instances...
if (
name !== 'array' &&
name !== 'object'
) {
// Cloning requires ES5 or higher...
if ( typeof Object.freeze === 'function' ) {
return cloneInstance( val );
}
return {};
}
// Arrays and plain objects...
keys = objectKeys( val );
if ( level > 0 ) {
parent = name;
for ( j = 0; j < keys.length; j++ ) {
key = keys[ j ];
x = val[ key ];
// Primitive, Buffer, special class instance...
name = typeOf( x );
if (
typeof x !== 'object' ||
x === null ||
(
name !== 'array' &&
name !== 'object'
) ||
isBuffer( x )
) {
if ( parent === 'object' ) {
desc = propertyDescriptor( val, key );
if ( hasOwnProp( desc, 'value' ) ) {
desc.value = deepCopy( x );
}
defineProperty( copy, key, desc );
} else {
copy[ key ] = deepCopy( x );
}
continue;
}
// Circular reference...
i = indexOf( cache, x );
if ( i !== -1 ) {
copy[ key ] = refs[ i ];
continue;
}
// Plain array or object...
ref = ( isArray( x ) ) ? new Array( x.length ) : {};
cache.push( x );
refs.push( ref );
if ( parent === 'array' ) {
copy[ key ] = deepCopy( x, ref, cache, refs, level );
} else {
desc = propertyDescriptor( val, key );
if ( hasOwnProp( desc, 'value' ) ) {
desc.value = deepCopy( x, ref, cache, refs, level );
}
defineProperty( copy, key, desc );
}
}
} else if ( name === 'array' ) {
for ( j = 0; j < keys.length; j++ ) {
key = keys[ j ];
copy[ key ] = val[ key ];
}
} else {
for ( j = 0; j < keys.length; j++ ) {
key = keys[ j ];
desc = propertyDescriptor( val, key );
defineProperty( copy, key, desc );
}
}
if ( !Object.isExtensible( val ) ) {
Object.preventExtensions( copy );
}
if ( Object.isSealed( val ) ) {
Object.seal( copy );
}
if ( Object.isFrozen( val ) ) {
Object.freeze( copy );
}
return copy;
}
// EXPORTS //
module.exports = deepCopy;
},{"./typed_arrays.js":423,"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-array":79,"@stdlib/assert/is-buffer":88,"@stdlib/assert/is-error":96,"@stdlib/buffer/from-buffer":236,"@stdlib/utils/define-property":435,"@stdlib/utils/get-prototype-of":447,"@stdlib/utils/index-of":457,"@stdlib/utils/keys":474,"@stdlib/utils/property-descriptor":496,"@stdlib/utils/property-names":500,"@stdlib/utils/regexp-from-string":503,"@stdlib/utils/type-of":508}],422:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Copy or deep clone a value to an arbitrary depth.
*
* @module @stdlib/utils/copy
*
* @example
* var copy = require( '@stdlib/utils/copy' );
*
* var out = copy( 'beep' );
* // returns 'beep'
*
* @example
* var copy = require( '@stdlib/utils/copy' );
*
* var value = [
* {
* 'a': 1,
* 'b': true,
* 'c': [ 1, 2, 3 ]
* }
* ];
* var out = copy( value );
* // returns [ {'a': 1, 'b': true, 'c': [ 1, 2, 3 ] } ]
*
* var bool = ( value[0].c === out[0].c );
* // returns false
*/
// MODULES //
var copy = require( './copy.js' );
// EXPORTS //
module.exports = copy;
},{"./copy.js":420}],423:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var Int8Array = require( '@stdlib/array/int8' );
var Uint8Array = require( '@stdlib/array/uint8' );
var Uint8ClampedArray = require( '@stdlib/array/uint8c' );
var Int16Array = require( '@stdlib/array/int16' );
var Uint16Array = require( '@stdlib/array/uint16' );
var Int32Array = require( '@stdlib/array/int32' );
var Uint32Array = require( '@stdlib/array/uint32' );
var Float32Array = require( '@stdlib/array/float32' );
var Float64Array = require( '@stdlib/array/float64' );
// VARIABLES //
var hash;
// FUNCTIONS //
/**
* Copies an `Int8Array`.
*
* @private
* @param {Int8Array} arr - array to copy
* @returns {Int8Array} new array
*/
function int8array( arr ) {
return new Int8Array( arr );
}
/**
* Copies a `Uint8Array`.
*
* @private
* @param {Uint8Array} arr - array to copy
* @returns {Uint8Array} new array
*/
function uint8array( arr ) {
return new Uint8Array( arr );
}
/**
* Copies a `Uint8ClampedArray`.
*
* @private
* @param {Uint8ClampedArray} arr - array to copy
* @returns {Uint8ClampedArray} new array
*/
function uint8clampedarray( arr ) {
return new Uint8ClampedArray( arr );
}
/**
* Copies an `Int16Array`.
*
* @private
* @param {Int16Array} arr - array to copy
* @returns {Int16Array} new array
*/
function int16array( arr ) {
return new Int16Array( arr );
}
/**
* Copies a `Uint16Array`.
*
* @private
* @param {Uint16Array} arr - array to copy
* @returns {Uint16Array} new array
*/
function uint16array( arr ) {
return new Uint16Array( arr );
}
/**
* Copies an `Int32Array`.
*
* @private
* @param {Int32Array} arr - array to copy
* @returns {Int32Array} new array
*/
function int32array( arr ) {
return new Int32Array( arr );
}
/**
* Copies a `Uint32Array`.
*
* @private
* @param {Uint32Array} arr - array to copy
* @returns {Uint32Array} new array
*/
function uint32array( arr ) {
return new Uint32Array( arr );
}
/**
* Copies a `Float32Array`.
*
* @private
* @param {Float32Array} arr - array to copy
* @returns {Float32Array} new array
*/
function float32array( arr ) {
return new Float32Array( arr );
}
/**
* Copies a `Float64Array`.
*
* @private
* @param {Float64Array} arr - array to copy
* @returns {Float64Array} new array
*/
function float64array( arr ) {
return new Float64Array( arr );
}
/**
* Returns a hash of functions for copying typed arrays.
*
* @private
* @returns {Object} function hash
*/
function typedarrays() {
var out = {
'int8array': int8array,
'uint8array': uint8array,
'uint8clampedarray': uint8clampedarray,
'int16array': int16array,
'uint16array': uint16array,
'int32array': int32array,
'uint32array': uint32array,
'float32array': float32array,
'float64array': float64array
};
return out;
}
// MAIN //
hash = typedarrays();
// EXPORTS //
module.exports = hash;
},{"@stdlib/array/float32":2,"@stdlib/array/float64":5,"@stdlib/array/int16":7,"@stdlib/array/int32":10,"@stdlib/array/int8":13,"@stdlib/array/uint16":20,"@stdlib/array/uint32":23,"@stdlib/array/uint8":26,"@stdlib/array/uint8c":29}],424:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Define a non-enumerable property.
*
* @module @stdlib/utils/define-nonenumerable-property
*
* @example
* var objectKeys = require( '@stdlib/utils/keys' );
* var setNonEnumerableProperty = require( '@stdlib/utils/define-nonenumerable-property' );
*
* var obj = {};
*
* setNonEnumerableProperty( obj, 'foo', 'bar' );
*
* var v = obj.foo;
* // returns 'bar'
*
* var keys = objectKeys( obj );
* // returns []
*/
// MODULES //
var setNonEnumerableProperty = require( './main.js' );
// EXPORTS //
module.exports = setNonEnumerableProperty;
},{"./main.js":425}],425:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var defineProperty = require( '@stdlib/utils/define-property' );
// MAIN //
/**
* Defines a non-enumerable property.
*
* @param {Object} obj - object on which to define the property
* @param {(string|symbol)} prop - property name
* @param {*} value - value to set
*
* @example
* var objectKeys = require( '@stdlib/utils/keys' );
*
* var obj = {};
*
* setNonEnumerableProperty( obj, 'foo', 'bar' );
*
* var v = obj.foo;
* // returns 'bar'
*
* var keys = objectKeys( obj );
* // returns []
*/
function setNonEnumerableProperty( obj, prop, value ) {
defineProperty( obj, prop, {
'configurable': true,
'enumerable': false,
'writable': true,
'value': value
});
}
// EXPORTS //
module.exports = setNonEnumerableProperty;
},{"@stdlib/utils/define-property":435}],426:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Define a non-enumerable read-only accessor.
*
* @module @stdlib/utils/define-nonenumerable-read-only-accessor
*
* @example
* var setNonEnumerableReadOnlyAccessor = require( '@stdlib/utils/define-nonenumerable-read-only-accessor' );
*
* function getter() {
* return 'bar';
* }
*
* var obj = {};
*
* setNonEnumerableReadOnlyAccessor( obj, 'foo', getter );
*
* try {
* obj.foo = 'boop';
* } catch ( err ) {
* console.error( err.message );
* }
*/
// MODULES //
var setNonEnumerableReadOnlyAccessor = require( './main.js' ); // eslint-disable-line id-length
// EXPORTS //
module.exports = setNonEnumerableReadOnlyAccessor;
},{"./main.js":427}],427:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var defineProperty = require( '@stdlib/utils/define-property' );
// MAIN //
/**
* Defines a non-enumerable read-only accessor.
*
* @param {Object} obj - object on which to define the property
* @param {(string|symbol)} prop - property name
* @param {Function} getter - accessor
*
* @example
* function getter() {
* return 'bar';
* }
*
* var obj = {};
*
* setNonEnumerableReadOnlyAccessor( obj, 'foo', getter );
*
* try {
* obj.foo = 'boop';
* } catch ( err ) {
* console.error( err.message );
* }
*/
function setNonEnumerableReadOnlyAccessor( obj, prop, getter ) { // eslint-disable-line id-length
defineProperty( obj, prop, {
'configurable': false,
'enumerable': false,
'get': getter
});
}
// EXPORTS //
module.exports = setNonEnumerableReadOnlyAccessor;
},{"@stdlib/utils/define-property":435}],428:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Define a non-enumerable read-only property.
*
* @module @stdlib/utils/define-nonenumerable-read-only-property
*
* @example
* var setNonEnumerableReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
*
* var obj = {};
*
* setNonEnumerableReadOnly( obj, 'foo', 'bar' );
*
* try {
* obj.foo = 'boop';
* } catch ( err ) {
* console.error( err.message );
* }
*/
// MODULES //
var setNonEnumerableReadOnly = require( './main.js' );
// EXPORTS //
module.exports = setNonEnumerableReadOnly;
},{"./main.js":429}],429:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var defineProperty = require( '@stdlib/utils/define-property' );
// MAIN //
/**
* Defines a non-enumerable read-only property.
*
* @param {Object} obj - object on which to define the property
* @param {(string|symbol)} prop - property name
* @param {*} value - value to set
*
* @example
* var obj = {};
*
* setNonEnumerableReadOnly( obj, 'foo', 'bar' );
*
* try {
* obj.foo = 'boop';
* } catch ( err ) {
* console.error( err.message );
* }
*/
function setNonEnumerableReadOnly( obj, prop, value ) {
defineProperty( obj, prop, {
'configurable': false,
'enumerable': false,
'writable': false,
'value': value
});
}
// EXPORTS //
module.exports = setNonEnumerableReadOnly;
},{"@stdlib/utils/define-property":435}],430:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Define a non-enumerable read-write accessor.
*
* @module @stdlib/utils/define-nonenumerable-read-write-accessor
*
* @example
* var setNonEnumerableReadWriteAccessor = require( '@stdlib/utils/define-nonenumerable-read-write-accessor' );
*
* function getter() {
* return name + ' foo';
* }
*
* function setter( v ) {
* name = v;
* }
*
* var name = 'bar';
* var obj = {};
*
* setNonEnumerableReadWriteAccessor( obj, 'foo', getter, setter );
*
* var v = obj.foo;
* // returns 'bar foo'
*
* obj.foo = 'beep';
*
* v = obj.foo;
* // returns 'beep foo'
*/
// MODULES //
var setNonEnumerableReadWriteAccessor = require( './main.js' );
// EXPORTS //
module.exports = setNonEnumerableReadWriteAccessor;
},{"./main.js":431}],431:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var defineProperty = require( '@stdlib/utils/define-property' );
// MAIN //
/**
* Defines a non-enumerable read-write accessor.
*
* @param {Object} obj - object on which to define the property
* @param {(string|symbol)} prop - property name
* @param {Function} getter - get accessor
* @param {Function} setter - set accessor
*
* @example
* function getter() {
* return name + ' foo';
* }
*
* function setter( v ) {
* name = v;
* }
*
* var name = 'bar';
* var obj = {};
*
* setNonEnumerableReadWriteAccessor( obj, 'foo', getter, setter );
*
* var v = obj.foo;
* // returns 'bar foo'
*
* obj.foo = 'beep';
*
* v = obj.foo;
* // returns 'beep foo'
*/
function setNonEnumerableReadWriteAccessor( obj, prop, getter, setter ) { // eslint-disable-line id-length
defineProperty( obj, prop, {
'configurable': false,
'enumerable': false,
'get': getter,
'set': setter
});
}
// EXPORTS //
module.exports = setNonEnumerableReadWriteAccessor;
},{"@stdlib/utils/define-property":435}],432:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Defines (or modifies) an object property.
*
* ## Notes
*
* - Property descriptors come in two flavors: **data descriptors** and **accessor descriptors**. A data descriptor is a property that has a value, which may or may not be writable. An accessor descriptor is a property described by a getter-setter function pair. A descriptor must be one of these two flavors and cannot be both.
*
* @name defineProperty
* @type {Function}
* @param {Object} obj - object on which to define the property
* @param {(string|symbol)} prop - property name
* @param {Object} descriptor - property descriptor
* @param {boolean} [descriptor.configurable=false] - boolean indicating if property descriptor can be changed and if the property can be deleted from the provided object
* @param {boolean} [descriptor.enumerable=false] - boolean indicating if the property shows up when enumerating object properties
* @param {boolean} [descriptor.writable=false] - boolean indicating if the value associated with the property can be changed with an assignment operator
* @param {*} [descriptor.value] - property value
* @param {(Function|void)} [descriptor.get=undefined] - function which serves as a getter for the property, or, if no getter, undefined. When the property is accessed, a getter function is called without arguments and with the `this` context set to the object through which the property is accessed (which may not be the object on which the property is defined due to inheritance). The return value will be used as the property value.
* @param {(Function|void)} [descriptor.set=undefined] - function which serves as a setter for the property, or, if no setter, undefined. When assigning a property value, a setter function is called with one argument (the value being assigned to the property) and with the `this` context set to the object through which the property is assigned.
* @throws {TypeError} first argument must be an object
* @throws {TypeError} third argument must be an object
* @throws {Error} property descriptor cannot have both a value and a setter and/or getter
* @returns {Object} object with added property
*
* @example
* var obj = {};
*
* defineProperty( obj, 'foo', {
* 'value': 'bar'
* });
*
* var str = obj.foo;
* // returns 'bar'
*/
var defineProperty = Object.defineProperty;
// EXPORTS //
module.exports = defineProperty;
},{}],433:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var main = ( typeof Object.defineProperty === 'function' ) ? Object.defineProperty : null;
// EXPORTS //
module.exports = main;
},{}],434:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var defineProperty = require( './define_property.js' );
// MAIN //
/**
* Tests for `Object.defineProperty` support.
*
* @private
* @returns {boolean} boolean indicating if an environment has `Object.defineProperty` support
*
* @example
* var bool = hasDefinePropertySupport();
* // returns <boolean>
*/
function hasDefinePropertySupport() {
// Test basic support...
try {
defineProperty( {}, 'x', {} );
return true;
} catch ( err ) { // eslint-disable-line no-unused-vars
return false;
}
}
// EXPORTS //
module.exports = hasDefinePropertySupport;
},{"./define_property.js":433}],435:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Define (or modify) an object property.
*
* @module @stdlib/utils/define-property
*
* @example
* var defineProperty = require( '@stdlib/utils/define-property' );
*
* var obj = {};
* defineProperty( obj, 'foo', {
* 'value': 'bar',
* 'writable': false,
* 'configurable': false,
* 'enumerable': false
* });
* obj.foo = 'boop'; // => throws
*/
// MODULES //
var hasDefinePropertySupport = require( './has_define_property_support.js' );
var builtin = require( './builtin.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var defineProperty;
if ( hasDefinePropertySupport() ) {
defineProperty = builtin;
} else {
defineProperty = polyfill;
}
// EXPORTS //
module.exports = defineProperty;
},{"./builtin.js":432,"./has_define_property_support.js":434,"./polyfill.js":436}],436:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
/* eslint-disable no-underscore-dangle, no-proto */
'use strict';
// VARIABLES //
var objectProtoype = Object.prototype;
var toStr = objectProtoype.toString;
var defineGetter = objectProtoype.__defineGetter__;
var defineSetter = objectProtoype.__defineSetter__;
var lookupGetter = objectProtoype.__lookupGetter__;
var lookupSetter = objectProtoype.__lookupSetter__;
// MAIN //
/**
* Defines (or modifies) an object property.
*
* ## Notes
*
* - Property descriptors come in two flavors: **data descriptors** and **accessor descriptors**. A data descriptor is a property that has a value, which may or may not be writable. An accessor descriptor is a property described by a getter-setter function pair. A descriptor must be one of these two flavors and cannot be both.
*
* @param {Object} obj - object on which to define the property
* @param {string} prop - property name
* @param {Object} descriptor - property descriptor
* @param {boolean} [descriptor.configurable=false] - boolean indicating if property descriptor can be changed and if the property can be deleted from the provided object
* @param {boolean} [descriptor.enumerable=false] - boolean indicating if the property shows up when enumerating object properties
* @param {boolean} [descriptor.writable=false] - boolean indicating if the value associated with the property can be changed with an assignment operator
* @param {*} [descriptor.value] - property value
* @param {(Function|void)} [descriptor.get=undefined] - function which serves as a getter for the property, or, if no getter, undefined. When the property is accessed, a getter function is called without arguments and with the `this` context set to the object through which the property is accessed (which may not be the object on which the property is defined due to inheritance). The return value will be used as the property value.
* @param {(Function|void)} [descriptor.set=undefined] - function which serves as a setter for the property, or, if no setter, undefined. When assigning a property value, a setter function is called with one argument (the value being assigned to the property) and with the `this` context set to the object through which the property is assigned.
* @throws {TypeError} first argument must be an object
* @throws {TypeError} third argument must be an object
* @throws {Error} property descriptor cannot have both a value and a setter and/or getter
* @returns {Object} object with added property
*
* @example
* var obj = {};
*
* defineProperty( obj, 'foo', {
* 'value': 'bar'
* });
*
* var str = obj.foo;
* // returns 'bar'
*/
function defineProperty( obj, prop, descriptor ) {
var prototype;
var hasValue;
var hasGet;
var hasSet;
if ( typeof obj !== 'object' || obj === null || toStr.call( obj ) === '[object Array]' ) {
throw new TypeError( 'invalid argument. First argument must be an object. Value: `' + obj + '`.' );
}
if ( typeof descriptor !== 'object' || descriptor === null || toStr.call( descriptor ) === '[object Array]' ) {
throw new TypeError( 'invalid argument. Property descriptor must be an object. Value: `' + descriptor + '`.' );
}
hasValue = ( 'value' in descriptor );
if ( hasValue ) {
if (
lookupGetter.call( obj, prop ) ||
lookupSetter.call( obj, prop )
) {
// Override `__proto__` to avoid touching inherited accessors:
prototype = obj.__proto__;
obj.__proto__ = objectProtoype;
// Delete property as existing getters/setters prevent assigning value to specified property:
delete obj[ prop ];
obj[ prop ] = descriptor.value;
// Restore original prototype:
obj.__proto__ = prototype;
} else {
obj[ prop ] = descriptor.value;
}
}
hasGet = ( 'get' in descriptor );
hasSet = ( 'set' in descriptor );
if ( hasValue && ( hasGet || hasSet ) ) {
throw new Error( 'invalid argument. Cannot specify one or more accessors and a value or writable attribute in the property descriptor.' );
}
if ( hasGet && defineGetter ) {
defineGetter.call( obj, prop, descriptor.get );
}
if ( hasSet && defineSetter ) {
defineSetter.call( obj, prop, descriptor.set );
}
return obj;
}
// EXPORTS //
module.exports = defineProperty;
},{}],437:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Define a read-only accessor.
*
* @module @stdlib/utils/define-read-only-accessor
*
* @example
* var setReadOnlyAccessor = require( '@stdlib/utils/define-read-only-accessor' );
*
* function getter() {
* return 'bar';
* }
*
* var obj = {};
*
* setReadOnlyAccessor( obj, 'foo', getter );
*
* try {
* obj.foo = 'boop';
* } catch ( err ) {
* console.error( err.message );
* }
*/
// MODULES //
var setReadOnlyAccessor = require( './main.js' );
// EXPORTS //
module.exports = setReadOnlyAccessor;
},{"./main.js":438}],438:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var defineProperty = require( '@stdlib/utils/define-property' );
// MAIN //
/**
* Defines a read-only accessor.
*
* @param {Object} obj - object on which to define the property
* @param {(string|symbol)} prop - property name
* @param {Function} getter - accessor
*
* @example
* function getter() {
* return 'bar';
* }
*
* var obj = {};
*
* setReadOnlyAccessor( obj, 'foo', getter );
*
* try {
* obj.foo = 'boop';
* } catch ( err ) {
* console.error( err.message );
* }
*/
function setReadOnlyAccessor( obj, prop, getter ) {
defineProperty( obj, prop, {
'configurable': false,
'enumerable': true,
'get': getter
});
}
// EXPORTS //
module.exports = setReadOnlyAccessor;
},{"@stdlib/utils/define-property":435}],439:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Define a read-write accessor.
*
* @module @stdlib/utils/define-read-write-accessor
*
* @example
* var setReadWriteAccessor = require( '@stdlib/utils/define-read-write-accessor' );
*
* function getter() {
* return name + ' foo';
* }
*
* function setter( v ) {
* name = v;
* }
*
* var name = 'bar';
* var obj = {};
*
* setReadWriteAccessor( obj, 'foo', getter, setter );
*
* var v = obj.foo;
* // returns 'bar foo'
*
* obj.foo = 'beep';
*
* v = obj.foo;
* // returns 'beep foo'
*/
// MODULES //
var setReadWriteAccessor = require( './main.js' );
// EXPORTS //
module.exports = setReadWriteAccessor;
},{"./main.js":440}],440:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var defineProperty = require( '@stdlib/utils/define-property' );
// MAIN //
/**
* Defines a read-write accessor.
*
* @param {Object} obj - object on which to define the property
* @param {(string|symbol)} prop - property name
* @param {Function} getter - get accessor
* @param {Function} setter - set accessor
*
* @example
* function getter() {
* return name + ' foo';
* }
*
* function setter( v ) {
* name = v;
* }
*
* var name = 'bar';
* var obj = {};
*
* setReadWriteAccessor( obj, 'foo', getter, setter );
*
* var v = obj.foo;
* // returns 'bar foo'
*
* obj.foo = 'beep';
*
* v = obj.foo;
* // returns 'beep foo'
*/
function setReadWriteAccessor( obj, prop, getter, setter ) {
defineProperty( obj, prop, {
'configurable': false,
'enumerable': true,
'get': getter,
'set': setter
});
}
// EXPORTS //
module.exports = setReadWriteAccessor;
},{"@stdlib/utils/define-property":435}],441:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Escape a regular expression string or pattern.
*
* @module @stdlib/utils/escape-regexp-string
*
* @example
* var rescape = require( '@stdlib/utils/escape-regexp-string' );
*
* var str = rescape( '[A-Z]*' );
* // returns '\\[A\\-Z\\]\\*'
*/
// MODULES //
var rescape = require( './main.js' );
// EXPORTS //
module.exports = rescape;
},{"./main.js":442}],442:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
// VARIABLES //
var RE_CHARS = /[-\/\\^$*+?.()|[\]{}]/g; // eslint-disable-line no-useless-escape
// MAIN //
/**
* Escapes a regular expression string.
*
* @param {string} str - regular expression string
* @throws {TypeError} first argument must be a string primitive
* @returns {string} escaped string
*
* @example
* var str = rescape( '[A-Z]*' );
* // returns '\\[A\\-Z\\]\\*'
*/
function rescape( str ) {
var len;
var s;
var i;
if ( !isString( str ) ) {
throw new TypeError( 'invalid argument. Must provide a regular expression string. Value: `' + str + '`.' );
}
// Check if the string starts with a forward slash...
if ( str[ 0 ] === '/' ) {
// Find the last forward slash...
len = str.length;
for ( i = len-1; i >= 0; i-- ) {
if ( str[ i ] === '/' ) {
break;
}
}
}
// If we searched the string to no avail or if the first letter is not `/`, assume that the string is not of the form `/[...]/[guimy]`:
if ( i === void 0 || i <= 0 ) {
return str.replace( RE_CHARS, '\\$&' );
}
// We need to de-construct the string...
s = str.substring( 1, i );
// Only escape the characters between the `/`:
s = s.replace( RE_CHARS, '\\$&' );
// Reassemble:
str = str[ 0 ] + s + str.substring( i );
return str;
}
// EXPORTS //
module.exports = rescape;
},{"@stdlib/assert/is-string":162}],443:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isFunction = require( '@stdlib/assert/is-function' );
var hasFunctionNameSupport = require( '@stdlib/assert/has-function-name-support' );
var RE = require( '@stdlib/regexp/function-name' ).REGEXP;
// VARIABLES //
var isFunctionNameSupported = hasFunctionNameSupport();
// MAIN //
/**
* Returns the name of a function.
*
* @param {Function} fcn - input function
* @throws {TypeError} must provide a function
* @returns {string} function name
*
* @example
* var v = functionName( Math.sqrt );
* // returns 'sqrt'
*
* @example
* var v = functionName( function foo(){} );
* // returns 'foo'
*
* @example
* var v = functionName( function(){} );
* // returns '' || 'anonymous'
*
* @example
* var v = functionName( String );
* // returns 'String'
*/
function functionName( fcn ) {
// TODO: add support for generator functions?
if ( isFunction( fcn ) === false ) {
throw new TypeError( 'invalid argument. Must provide a function. Value: `' + fcn + '`.' );
}
if ( isFunctionNameSupported ) {
return fcn.name;
}
return RE.exec( fcn.toString() )[ 1 ];
}
// EXPORTS //
module.exports = functionName;
},{"@stdlib/assert/has-function-name-support":39,"@stdlib/assert/is-function":102,"@stdlib/regexp/function-name":389}],444:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Return the name of a function.
*
* @module @stdlib/utils/function-name
*
* @example
* var functionName = require( '@stdlib/utils/function-name' );
*
* var v = functionName( String );
* // returns 'String'
*
* v = functionName( function foo(){} );
* // returns 'foo'
*
* v = functionName( function(){} );
* // returns '' || 'anonymous'
*/
// MODULES //
var functionName = require( './function_name.js' );
// EXPORTS //
module.exports = functionName;
},{"./function_name.js":443}],445:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isFunction = require( '@stdlib/assert/is-function' );
var builtin = require( './native.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var getProto;
if ( isFunction( Object.getPrototypeOf ) ) {
getProto = builtin;
} else {
getProto = polyfill;
}
// EXPORTS //
module.exports = getProto;
},{"./native.js":448,"./polyfill.js":449,"@stdlib/assert/is-function":102}],446:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var getProto = require( './detect.js' );
// MAIN //
/**
* Returns the prototype of a provided object.
*
* @param {*} value - input value
* @returns {(Object|null)} prototype
*
* @example
* var proto = getPrototypeOf( {} );
* // returns {}
*/
function getPrototypeOf( value ) {
if (
value === null ||
value === void 0
) {
return null;
}
// In order to ensure consistent ES5/ES6 behavior, cast input value to an object (strings, numbers, booleans); ES5 `Object.getPrototypeOf` throws when provided primitives and ES6 `Object.getPrototypeOf` casts:
value = Object( value );
return getProto( value );
}
// EXPORTS //
module.exports = getPrototypeOf;
},{"./detect.js":445}],447:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Return the prototype of a provided object.
*
* @module @stdlib/utils/get-prototype-of
*
* @example
* var getPrototype = require( '@stdlib/utils/get-prototype-of' );
*
* var proto = getPrototype( {} );
* // returns {}
*/
// MODULES //
var getPrototype = require( './get_prototype_of.js' );
// EXPORTS //
module.exports = getPrototype;
},{"./get_prototype_of.js":446}],448:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var getProto = Object.getPrototypeOf;
// EXPORTS //
module.exports = getProto;
},{}],449:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var nativeClass = require( '@stdlib/utils/native-class' );
var getProto = require( './proto.js' );
// MAIN //
/**
* Returns the prototype of a provided object.
*
* @private
* @param {Object} obj - input object
* @returns {(Object|null)} prototype
*/
function getPrototypeOf( obj ) {
var proto = getProto( obj );
if ( proto || proto === null ) {
return proto;
}
if ( nativeClass( obj.constructor ) === '[object Function]' ) {
// May break if the constructor has been tampered with...
return obj.constructor.prototype;
}
if ( obj instanceof Object ) {
return Object.prototype;
}
// Return `null` for objects created via `Object.create( null )`. Also return `null` for cross-realm objects on browsers that lack `__proto__` support, such as IE < 11.
return null;
}
// EXPORTS //
module.exports = getPrototypeOf;
},{"./proto.js":450,"@stdlib/utils/native-class":481}],450:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Returns the value of the `__proto__` property.
*
* @private
* @param {Object} obj - input object
* @returns {*} value of `__proto__` property
*/
function getProto( obj ) {
// eslint-disable-next-line no-proto
return obj.__proto__;
}
// EXPORTS //
module.exports = getProto;
},{}],451:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Returns the global object using code generation.
*
* @private
* @returns {Object} global object
*/
function getGlobal() {
return new Function( 'return this;' )(); // eslint-disable-line no-new-func
}
// EXPORTS //
module.exports = getGlobal;
},{}],452:[function(require,module,exports){
(function (global){(function (){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var obj = ( typeof global === 'object' ) ? global : null;
// EXPORTS //
module.exports = obj;
}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],453:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Return the global object.
*
* @module @stdlib/utils/global
*
* @example
* var getGlobal = require( '@stdlib/utils/global' );
*
* var g = getGlobal();
* // returns {...}
*/
// MODULES //
var getGlobal = require( './main.js' );
// EXPORTS //
module.exports = getGlobal;
},{"./main.js":454}],454:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive;
var getThis = require( './codegen.js' );
var Self = require( './self.js' );
var Win = require( './window.js' );
var Global = require( './global.js' );
// MAIN //
/**
* Returns the global object.
*
* ## Notes
*
* - Using code generation is the **most** reliable way to resolve the global object; however, doing so is likely to violate content security policies (CSPs) in, e.g., Chrome Apps and elsewhere.
*
* @param {boolean} [codegen=false] - boolean indicating whether to use code generation to resolve the global object
* @throws {TypeError} must provide a boolean
* @throws {Error} unable to resolve global object
* @returns {Object} global object
*
* @example
* var g = getGlobal();
* // returns {...}
*/
function getGlobal( codegen ) {
if ( arguments.length ) {
if ( !isBoolean( codegen ) ) {
throw new TypeError( 'invalid argument. Must provide a boolean primitive. Value: `'+codegen+'`.' );
}
if ( codegen ) {
return getThis();
}
// Fall through...
}
// Case: browsers and web workers
if ( Self ) {
return Self;
}
// Case: browsers
if ( Win ) {
return Win;
}
// Case: Node.js
if ( Global ) {
return Global;
}
// Case: unknown
throw new Error( 'unexpected error. Unable to resolve global object.' );
}
// EXPORTS //
module.exports = getGlobal;
},{"./codegen.js":451,"./global.js":452,"./self.js":455,"./window.js":456,"@stdlib/assert/is-boolean":81}],455:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var obj = ( typeof self === 'object' ) ? self : null;
// EXPORTS //
module.exports = obj;
},{}],456:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var obj = ( typeof window === 'object' ) ? window : null;
// EXPORTS //
module.exports = obj;
},{}],457:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Return the first index at which a given element can be found.
*
* @module @stdlib/utils/index-of
*
* @example
* var indexOf = require( '@stdlib/utils/index-of' );
*
* var arr = [ 4, 3, 2, 1 ];
* var idx = indexOf( arr, 3 );
* // returns 1
*
* arr = [ 4, 3, 2, 1 ];
* idx = indexOf( arr, 5 );
* // returns -1
*
* // Using a `fromIndex`:
* arr = [ 1, 2, 3, 4, 5, 2, 6 ];
* idx = indexOf( arr, 2, 3 );
* // returns 5
*
* // `fromIndex` which exceeds `array` length:
* arr = [ 1, 2, 3, 4, 2, 5 ];
* idx = indexOf( arr, 2, 10 );
* // returns -1
*
* // Negative `fromIndex`:
* arr = [ 1, 2, 3, 4, 5, 2, 6, 2 ];
* idx = indexOf( arr, 2, -4 );
* // returns 5
*
* idx = indexOf( arr, 2, -1 );
* // returns 7
*
* // Negative `fromIndex` exceeding input `array` length:
* arr = [ 1, 2, 3, 4, 5, 2, 6 ];
* idx = indexOf( arr, 2, -10 );
* // returns 1
*
* // Array-like objects:
* var str = 'bebop';
* idx = indexOf( str, 'o' );
* // returns 3
*/
// MODULES //
var indexOf = require( './index_of.js' );
// EXPORTS //
module.exports = indexOf;
},{"./index_of.js":458}],458:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isnan = require( '@stdlib/assert/is-nan' );
var isCollection = require( '@stdlib/assert/is-collection' );
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var isInteger = require( '@stdlib/assert/is-integer' ).isPrimitive;
// MAIN //
/**
* Returns the first index at which a given element can be found.
*
* @param {ArrayLike} arr - array-like object
* @param {*} searchElement - element to find
* @param {integer} [fromIndex] - starting index (if negative, the start index is determined relative to last element)
* @throws {TypeError} must provide an array-like object
* @throws {TypeError} `fromIndex` must be an integer
* @returns {integer} index or -1
*
* @example
* var arr = [ 4, 3, 2, 1 ];
* var idx = indexOf( arr, 3 );
* // returns 1
*
* @example
* var arr = [ 4, 3, 2, 1 ];
* var idx = indexOf( arr, 5 );
* // returns -1
*
* @example
* // Using a `fromIndex`:
* var arr = [ 1, 2, 3, 4, 5, 2, 6 ];
* var idx = indexOf( arr, 2, 3 );
* // returns 5
*
* @example
* // `fromIndex` which exceeds `array` length:
* var arr = [ 1, 2, 3, 4, 2, 5 ];
* var idx = indexOf( arr, 2, 10 );
* // returns -1
*
* @example
* // Negative `fromIndex`:
* var arr = [ 1, 2, 3, 4, 5, 2, 6, 2 ];
* var idx = indexOf( arr, 2, -4 );
* // returns 5
*
* idx = indexOf( arr, 2, -1 );
* // returns 7
*
* @example
* // Negative `fromIndex` exceeding input `array` length:
* var arr = [ 1, 2, 3, 4, 5, 2, 6 ];
* var idx = indexOf( arr, 2, -10 );
* // returns 1
*
* @example
* // Array-like objects:
* var str = 'bebop';
* var idx = indexOf( str, 'o' );
* // returns 3
*/
function indexOf( arr, searchElement, fromIndex ) {
var len;
var i;
if ( !isCollection( arr ) && !isString( arr ) ) {
throw new TypeError( 'invalid argument. First argument must be an array-like object. Value: `' + arr + '`.' );
}
len = arr.length;
if ( len === 0 ) {
return -1;
}
if ( arguments.length === 3 ) {
if ( !isInteger( fromIndex ) ) {
throw new TypeError( 'invalid argument. `fromIndex` must be an integer. Value: `' + fromIndex + '`.' );
}
if ( fromIndex >= 0 ) {
if ( fromIndex >= len ) {
return -1;
}
i = fromIndex;
} else {
i = len + fromIndex;
if ( i < 0 ) {
i = 0;
}
}
} else {
i = 0;
}
// Check for `NaN`...
if ( isnan( searchElement ) ) {
for ( ; i < len; i++ ) {
if ( isnan( arr[i] ) ) {
return i;
}
}
} else {
for ( ; i < len; i++ ) {
if ( arr[ i ] === searchElement ) {
return i;
}
}
}
return -1;
}
// EXPORTS //
module.exports = indexOf;
},{"@stdlib/assert/is-collection":90,"@stdlib/assert/is-integer":110,"@stdlib/assert/is-nan":118,"@stdlib/assert/is-string":162}],459:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var builtin = require( './native.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var createObject;
if ( typeof builtin === 'function' ) {
createObject = builtin;
} else {
createObject = polyfill;
}
// EXPORTS //
module.exports = createObject;
},{"./native.js":462,"./polyfill.js":463}],460:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Implement prototypical inheritance by replacing the prototype of one constructor with the prototype of another constructor.
*
* @module @stdlib/utils/inherit
*
* @example
* var inherit = require( '@stdlib/utils/inherit' );
*
* function Foo() {
* return this;
* }
* Foo.prototype.beep = function beep() {
* return 'boop';
* };
*
* function Bar() {
* Foo.call( this );
* return this;
* }
* inherit( Bar, Foo );
*
* var bar = new Bar();
* var v = bar.beep();
* // returns 'boop'
*/
// MODULES //
var inherit = require( './inherit.js' );
// EXPORTS //
module.exports = inherit;
},{"./inherit.js":461}],461:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var defineProperty = require( '@stdlib/utils/define-property' );
var validate = require( './validate.js' );
var createObject = require( './detect.js' );
// MAIN //
/**
* Implements prototypical inheritance by replacing the prototype of one constructor with the prototype of another constructor.
*
* ## Notes
*
* - This implementation is not designed to work with ES2015/ES6 classes. For ES2015/ES6 classes, use `class` with `extends`.
* - For reference, see [node#3455](https://github.com/nodejs/node/pull/3455), [node#4179](https://github.com/nodejs/node/issues/4179), [node#3452](https://github.com/nodejs/node/issues/3452), and [node commit](https://github.com/nodejs/node/commit/29da8cf8d7ab8f66b9091ab22664067d4468461e#diff-3deb3f32958bb937ae05c6f3e4abbdf5).
*
*
* @param {(Object|Function)} ctor - constructor which will inherit
* @param {(Object|Function)} superCtor - super (parent) constructor
* @throws {TypeError} first argument must be either an object or a function which can inherit
* @throws {TypeError} second argument must be either an object or a function from which a constructor can inherit
* @throws {TypeError} second argument must have an inheritable prototype
* @returns {(Object|Function)} child constructor
*
* @example
* function Foo() {
* return this;
* }
* Foo.prototype.beep = function beep() {
* return 'boop';
* };
*
* function Bar() {
* Foo.call( this );
* return this;
* }
* inherit( Bar, Foo );
*
* var bar = new Bar();
* var v = bar.beep();
* // returns 'boop'
*/
function inherit( ctor, superCtor ) {
var err = validate( ctor );
if ( err ) {
throw err;
}
err = validate( superCtor );
if ( err ) {
throw err;
}
if ( typeof superCtor.prototype === 'undefined' ) {
throw new TypeError( 'invalid argument. Second argument must have a prototype from which another object can inherit. Value: `'+superCtor.prototype+'`.' );
}
// Create a prototype which inherits from the parent prototype:
ctor.prototype = createObject( superCtor.prototype );
// Set the constructor to refer to the child constructor:
defineProperty( ctor.prototype, 'constructor', {
'configurable': true,
'enumerable': false,
'writable': true,
'value': ctor
});
return ctor;
}
// EXPORTS //
module.exports = inherit;
},{"./detect.js":459,"./validate.js":464,"@stdlib/utils/define-property":435}],462:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// EXPORTS //
module.exports = Object.create;
},{}],463:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// FUNCTIONS //
/**
* Dummy constructor.
*
* @private
*/
function Ctor() {
// Empty...
}
// MAIN //
/**
* An `Object.create` shim for older JavaScript engines.
*
* @private
* @param {Object} proto - prototype
* @returns {Object} created object
*
* @example
* var obj = createObject( Object.prototype );
* // returns {}
*/
function createObject( proto ) {
Ctor.prototype = proto;
return new Ctor();
}
// EXPORTS //
module.exports = createObject;
},{}],464:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Tests that a value is a valid constructor.
*
* @private
* @param {*} value - value to test
* @returns {(Error|null)} error object or null
*
* @example
* var ctor = function ctor() {};
*
* var err = validate( ctor );
* // returns null
*
* err = validate( null );
* // returns <TypeError>
*/
function validate( value ) {
var type = typeof value;
if (
value === null ||
(type !== 'object' && type !== 'function')
) {
return new TypeError( 'invalid argument. A provided constructor must be either an object (except null) or a function. Value: `'+value+'`.' );
}
return null;
}
// EXPORTS //
module.exports = validate;
},{}],465:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Returns an array of an object's own enumerable property names.
*
* ## Notes
*
* - In contrast to the built-in `Object.keys()`, this function returns an empty array if provided `undefined` or `null`, rather than throwing an error.
*
* @private
* @param {*} value - input object
* @returns {Array} a list of own enumerable property names
*
* @example
* var obj = {
* 'beep': 'boop',
* 'foo': 3.14
* };
*
* var k = keys( obj );
* // e.g., returns [ 'beep', 'foo' ]
*/
function keys( value ) {
return Object.keys( Object( value ) );
}
// EXPORTS //
module.exports = keys;
},{}],466:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isArguments = require( '@stdlib/assert/is-arguments' );
var builtin = require( './builtin.js' );
// VARIABLES //
var slice = Array.prototype.slice;
// MAIN //
/**
* Returns an array of an object's own enumerable property names.
*
* @private
* @param {*} value - input object
* @returns {Array} a list of own enumerable property names
*
* @example
* var obj = {
* 'beep': 'boop',
* 'foo': 3.14
* };
*
* var k = keys( obj );
* // e.g., returns [ 'beep', 'foo' ]
*/
function keys( value ) {
if ( isArguments( value ) ) {
return builtin( slice.call( value ) );
}
return builtin( value );
}
// EXPORTS //
module.exports = keys;
},{"./builtin.js":465,"@stdlib/assert/is-arguments":74}],467:[function(require,module,exports){
module.exports=[
"console",
"external",
"frame",
"frameElement",
"frames",
"innerHeight",
"innerWidth",
"outerHeight",
"outerWidth",
"pageXOffset",
"pageYOffset",
"parent",
"scrollLeft",
"scrollTop",
"scrollX",
"scrollY",
"self",
"webkitIndexedDB",
"webkitStorageInfo",
"window"
]
},{}],468:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var keys = require( './builtin.js' );
// FUNCTIONS //
/**
* Tests the built-in `Object.keys()` implementation when provided `arguments`.
*
* @private
* @returns {boolean} boolean indicating whether the built-in implementation returns the expected number of keys
*/
function test() {
return ( keys( arguments ) || '' ).length !== 2;
}
// MAIN //
/**
* Tests whether the built-in `Object.keys()` implementation supports providing `arguments` as an input value.
*
* ## Notes
*
* - Safari 5.0 does **not** support `arguments` as an input value.
*
* @private
* @returns {boolean} boolean indicating whether a built-in implementation supports `arguments`
*/
function check() {
return test( 1, 2 );
}
// EXPORTS //
module.exports = check;
},{"./builtin.js":465}],469:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var indexOf = require( '@stdlib/utils/index-of' );
var typeOf = require( '@stdlib/utils/type-of' );
var isConstructorPrototype = require( './is_constructor_prototype.js' );
var EXCLUDED_KEYS = require( './excluded_keys.json' );
var win = require( './window.js' );
// VARIABLES //
var bool;
// FUNCTIONS //
/**
* Determines whether an environment throws when comparing to the prototype of a value's constructor (e.g., [IE9][1]).
*
* [1]: https://stackoverflow.com/questions/7688070/why-is-comparing-the-constructor-property-of-two-windows-unreliable
*
* @private
* @returns {boolean} boolean indicating whether an environment is buggy
*/
function check() {
var k;
if ( typeOf( win ) === 'undefined' ) {
return false;
}
for ( k in win ) { // eslint-disable-line guard-for-in
try {
if (
indexOf( EXCLUDED_KEYS, k ) === -1 &&
hasOwnProp( win, k ) &&
win[ k ] !== null &&
typeOf( win[ k ] ) === 'object'
) {
isConstructorPrototype( win[ k ] );
}
} catch ( err ) { // eslint-disable-line no-unused-vars
return true;
}
}
return false;
}
// MAIN //
bool = check();
// EXPORTS //
module.exports = bool;
},{"./excluded_keys.json":467,"./is_constructor_prototype.js":475,"./window.js":480,"@stdlib/assert/has-own-property":53,"@stdlib/utils/index-of":457,"@stdlib/utils/type-of":508}],470:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var bool = ( typeof Object.keys !== 'undefined' );
// EXPORTS //
module.exports = bool;
},{}],471:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isEnumerableProperty = require( '@stdlib/assert/is-enumerable-property' );
var noop = require( '@stdlib/utils/noop' );
// MAIN //
// Note: certain environments treat an object's prototype as enumerable, which, as a matter of convention, it shouldn't be...
var bool = isEnumerableProperty( noop, 'prototype' );
// EXPORTS //
module.exports = bool;
},{"@stdlib/assert/is-enumerable-property":93,"@stdlib/utils/noop":488}],472:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isEnumerableProperty = require( '@stdlib/assert/is-enumerable-property' );
// VARIABLES //
var obj = {
'toString': null
};
// MAIN //
// Note: certain environments don't allow enumeration of overwritten properties which are considered non-enumerable...
var bool = !isEnumerableProperty( obj, 'toString' );
// EXPORTS //
module.exports = bool;
},{"@stdlib/assert/is-enumerable-property":93}],473:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var bool = ( typeof window !== 'undefined' );
// EXPORTS //
module.exports = bool;
},{}],474:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Return an array of an object's own enumerable property names.
*
* @module @stdlib/utils/keys
*
* @example
* var keys = require( '@stdlib/utils/keys' );
*
* var obj = {
* 'beep': 'boop',
* 'foo': 3.14
* };
*
* var k = keys( obj );
* // e.g., returns [ 'beep', 'foo' ]
*/
// MODULES //
var keys = require( './main.js' );
// EXPORTS //
module.exports = keys;
},{"./main.js":477}],475:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Tests whether a value equals the prototype of its constructor.
*
* @private
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether a value equals the prototype of its constructor
*/
function isConstructorPrototype( value ) {
return ( value.constructor && value.constructor.prototype === value );
}
// EXPORTS //
module.exports = isConstructorPrototype;
},{}],476:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var hasAutomationEqualityBug = require( './has_automation_equality_bug.js' );
var isConstructorPrototype = require( './is_constructor_prototype.js' );
var HAS_WINDOW = require( './has_window.js' );
// MAIN //
/**
* Wraps the test for constructor prototype equality to accommodate buggy environments (e.g., environments which throw when testing equality).
*
* @private
* @param {*} value - value to test
* @returns {boolean} boolean indicating whether a value equals the prototype of its constructor
*/
function wrapper( value ) {
if ( HAS_WINDOW === false && !hasAutomationEqualityBug ) {
return isConstructorPrototype( value );
}
try {
return isConstructorPrototype( value );
} catch ( error ) { // eslint-disable-line no-unused-vars
return false;
}
}
// EXPORTS //
module.exports = wrapper;
},{"./has_automation_equality_bug.js":469,"./has_window.js":473,"./is_constructor_prototype.js":475}],477:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var hasArgumentsBug = require( './has_arguments_bug.js' );
var HAS_BUILTIN = require( './has_builtin.js' );
var builtin = require( './builtin.js' );
var wrapper = require( './builtin_wrapper.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
/**
* Returns an array of an object's own enumerable property names.
*
* @name keys
* @type {Function}
* @param {*} value - input object
* @returns {Array} a list of own enumerable property names
*
* @example
* var obj = {
* 'beep': 'boop',
* 'foo': 3.14
* };
*
* var k = keys( obj );
* // e.g., returns [ 'beep', 'foo' ]
*/
var keys;
if ( HAS_BUILTIN ) {
if ( hasArgumentsBug() ) {
keys = wrapper;
} else {
keys = builtin;
}
} else {
keys = polyfill;
}
// EXPORTS //
module.exports = keys;
},{"./builtin.js":465,"./builtin_wrapper.js":466,"./has_arguments_bug.js":468,"./has_builtin.js":470,"./polyfill.js":479}],478:[function(require,module,exports){
module.exports=[
"toString",
"toLocaleString",
"valueOf",
"hasOwnProperty",
"isPrototypeOf",
"propertyIsEnumerable",
"constructor"
]
},{}],479:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isObjectLike = require( '@stdlib/assert/is-object-like' );
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var isArguments = require( '@stdlib/assert/is-arguments' );
var HAS_ENUM_PROTO_BUG = require( './has_enumerable_prototype_bug.js' );
var HAS_NON_ENUM_PROPS_BUG = require( './has_non_enumerable_properties_bug.js' );
var isConstructorPrototype = require( './is_constructor_prototype_wrapper.js' );
var NON_ENUMERABLE = require( './non_enumerable.json' );
// MAIN //
/**
* Returns an array of an object's own enumerable property names.
*
* @private
* @param {*} value - input object
* @returns {Array} a list of own enumerable property names
*
* @example
* var obj = {
* 'beep': 'boop',
* 'foo': 3.14
* };
*
* var k = keys( obj );
* // e.g., returns [ 'beep', 'foo' ]
*/
function keys( value ) {
var skipConstructor;
var skipPrototype;
var isFcn;
var out;
var k;
var p;
var i;
out = [];
if ( isArguments( value ) ) {
// Account for environments which treat `arguments` differently...
for ( i = 0; i < value.length; i++ ) {
out.push( i.toString() );
}
// Note: yes, we are precluding the `arguments` array-like object from having other enumerable properties; however, this should (1) be very rare and (2) not be encouraged (e.g., doing something like `arguments.a = 'b'`; in certain engines directly manipulating the `arguments` value results in automatic de-optimization).
return out;
}
if ( typeof value === 'string' ) {
// Account for environments which do not treat string character indices as "own" properties...
if ( value.length > 0 && !hasOwnProp( value, '0' ) ) {
for ( i = 0; i < value.length; i++ ) {
out.push( i.toString() );
}
}
} else {
isFcn = ( typeof value === 'function' );
if ( isFcn === false && !isObjectLike( value ) ) {
return out;
}
skipPrototype = ( HAS_ENUM_PROTO_BUG && isFcn );
}
for ( k in value ) {
if ( !( skipPrototype && k === 'prototype' ) && hasOwnProp( value, k ) ) {
out.push( String( k ) );
}
}
if ( HAS_NON_ENUM_PROPS_BUG ) {
skipConstructor = isConstructorPrototype( value );
for ( i = 0; i < NON_ENUMERABLE.length; i++ ) {
p = NON_ENUMERABLE[ i ];
if ( !( skipConstructor && p === 'constructor' ) && hasOwnProp( value, p ) ) {
out.push( String( p ) );
}
}
}
return out;
}
// EXPORTS //
module.exports = keys;
},{"./has_enumerable_prototype_bug.js":471,"./has_non_enumerable_properties_bug.js":472,"./is_constructor_prototype_wrapper.js":476,"./non_enumerable.json":478,"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-arguments":74,"@stdlib/assert/is-object-like":143}],480:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var w = ( typeof window === 'undefined' ) ? void 0 : window;
// EXPORTS //
module.exports = w;
},{}],481:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Return a string value indicating a specification defined classification of an object.
*
* @module @stdlib/utils/native-class
*
* @example
* var nativeClass = require( '@stdlib/utils/native-class' );
*
* var str = nativeClass( 'a' );
* // returns '[object String]'
*
* str = nativeClass( 5 );
* // returns '[object Number]'
*
* function Beep() {
* return this;
* }
* str = nativeClass( new Beep() );
* // returns '[object Object]'
*/
// MODULES //
var hasToStringTag = require( '@stdlib/assert/has-tostringtag-support' );
var builtin = require( './native_class.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var nativeClass;
if ( hasToStringTag() ) {
nativeClass = polyfill;
} else {
nativeClass = builtin;
}
// EXPORTS //
module.exports = nativeClass;
},{"./native_class.js":482,"./polyfill.js":483,"@stdlib/assert/has-tostringtag-support":57}],482:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var toStr = require( './tostring.js' );
// MAIN //
/**
* Returns a string value indicating a specification defined classification (via the internal property `[[Class]]`) of an object.
*
* @param {*} v - input value
* @returns {string} string value indicating a specification defined classification of the input value
*
* @example
* var str = nativeClass( 'a' );
* // returns '[object String]'
*
* @example
* var str = nativeClass( 5 );
* // returns '[object Number]'
*
* @example
* function Beep() {
* return this;
* }
* var str = nativeClass( new Beep() );
* // returns '[object Object]'
*/
function nativeClass( v ) {
return toStr.call( v );
}
// EXPORTS //
module.exports = nativeClass;
},{"./tostring.js":484}],483:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var toStringTag = require( './tostringtag.js' );
var toStr = require( './tostring.js' );
// MAIN //
/**
* Returns a string value indicating a specification defined classification of an object in environments supporting `Symbol.toStringTag`.
*
* @param {*} v - input value
* @returns {string} string value indicating a specification defined classification of the input value
*
* @example
* var str = nativeClass( 'a' );
* // returns '[object String]'
*
* @example
* var str = nativeClass( 5 );
* // returns '[object Number]'
*
* @example
* function Beep() {
* return this;
* }
* var str = nativeClass( new Beep() );
* // returns '[object Object]'
*/
function nativeClass( v ) {
var isOwn;
var tag;
var out;
if ( v === null || v === void 0 ) {
return toStr.call( v );
}
tag = v[ toStringTag ];
isOwn = hasOwnProp( v, toStringTag );
// Attempt to override the `toStringTag` property. For built-ins having a `Symbol.toStringTag` property (e.g., `JSON`, `Math`, etc), the `Symbol.toStringTag` property is read-only (e.g., , so we need to wrap in a `try/catch`.
try {
v[ toStringTag ] = void 0;
} catch ( err ) { // eslint-disable-line no-unused-vars
return toStr.call( v );
}
out = toStr.call( v );
if ( isOwn ) {
v[ toStringTag ] = tag;
} else {
delete v[ toStringTag ];
}
return out;
}
// EXPORTS //
module.exports = nativeClass;
},{"./tostring.js":484,"./tostringtag.js":485,"@stdlib/assert/has-own-property":53}],484:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var toStr = Object.prototype.toString;
// EXPORTS //
module.exports = toStr;
},{}],485:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var toStrTag = ( typeof Symbol === 'function' ) ? Symbol.toStringTag : '';
// EXPORTS //
module.exports = toStrTag;
},{}],486:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2020 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Add a callback to the "next tick queue".
*
* @module @stdlib/utils/next-tick
*
* @example
* var nextTick = require( '@stdlib/utils/next-tick' );
*
* function beep() {
* console.log( 'boop' );
* }
*
* nextTick( beep );
*/
// MODULES //
var nextTick = require( './main.js' );
// EXPORTS //
module.exports = nextTick;
},{"./main.js":487}],487:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2020 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var proc = require( 'process' );
// MAIN //
/**
* Adds a callback to the "next tick queue".
*
* ## Notes
*
* - The queue is fully drained after the current operation on the JavaScript stack runs to completion and before the event loop is allowed to continue.
*
* @param {Callback} clbk - callback
* @param {...*} [args] - arguments to provide to the callback upon invocation
*
* @example
* function beep() {
* console.log( 'boop' );
* }
*
* nextTick( beep );
*/
function nextTick( clbk ) {
var args;
var i;
args = [];
for ( i = 1; i < arguments.length; i++ ) {
args.push( arguments[ i ] );
}
proc.nextTick( wrapper );
/**
* Callback wrapper.
*
* ## Notes
*
* - The ability to provide additional arguments was added in Node.js v1.8.1. The wrapper provides support for earlier Node.js versions.
*
* @private
*/
function wrapper() {
clbk.apply( null, args );
}
}
// EXPORTS //
module.exports = nextTick;
},{"process":524}],488:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* No operation.
*
* @module @stdlib/utils/noop
*
* @example
* var noop = require( '@stdlib/utils/noop' );
*
* noop();
* // ...does nothing.
*/
// MODULES //
var noop = require( './noop.js' );
// EXPORTS //
module.exports = noop;
},{"./noop.js":489}],489:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* No operation.
*
* @example
* noop();
* // ...does nothing.
*/
function noop() {
// Empty function...
}
// EXPORTS //
module.exports = noop;
},{}],490:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Return a partial object copy excluding specified keys.
*
* @module @stdlib/utils/omit
*
* @example
* var omit = require( '@stdlib/utils/omit' );
*
* var obj1 = {
* 'a': 1,
* 'b': 2
* };
*
* var obj2 = omit( obj1, 'b' );
* // returns { 'a': 1 }
*/
// MODULES //
var omit = require( './omit.js' );
// EXPORTS //
module.exports = omit;
},{"./omit.js":491}],491:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var objectKeys = require( '@stdlib/utils/keys' );
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var isStringArray = require( '@stdlib/assert/is-string-array' ).primitives;
var indexOf = require( '@stdlib/utils/index-of' );
// MAIN //
/**
* Returns a partial object copy excluding specified keys.
*
* @param {Object} obj - source object
* @param {(string|StringArray)} keys - keys to exclude
* @throws {TypeError} first argument must be an object
* @throws {TypeError} second argument must be either a string or an array of strings
* @returns {Object} new object
*
* @example
* var obj1 = {
* 'a': 1,
* 'b': 2
* };
*
* var obj2 = omit( obj1, 'b' );
* // returns { 'a': 1 }
*/
function omit( obj, keys ) {
var ownKeys;
var out;
var key;
var i;
if ( typeof obj !== 'object' || obj === null ) {
throw new TypeError( 'invalid argument. First argument must be an object. Value: `'+obj+'`.' );
}
ownKeys = objectKeys( obj );
out = {};
if ( isString( keys ) ) {
for ( i = 0; i < ownKeys.length; i++ ) {
key = ownKeys[ i ];
if ( key !== keys ) {
out[ key ] = obj[ key ];
}
}
return out;
}
if ( isStringArray( keys ) ) {
for ( i = 0; i < ownKeys.length; i++ ) {
key = ownKeys[ i ];
if ( indexOf( keys, key ) === -1 ) {
out[ key ] = obj[ key ];
}
}
return out;
}
throw new TypeError( 'invalid argument. Second argument must be either a string primitive or an array of string primitives. Value: `'+keys+'`.' );
}
// EXPORTS //
module.exports = omit;
},{"@stdlib/assert/is-string":162,"@stdlib/assert/is-string-array":161,"@stdlib/utils/index-of":457,"@stdlib/utils/keys":474}],492:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Return a partial object copy containing only specified keys.
*
* @module @stdlib/utils/pick
*
* @example
* var pick = require( '@stdlib/utils/pick' );
*
* var obj1 = {
* 'a': 1,
* 'b': 2
* };
*
* var obj2 = pick( obj1, 'b' );
* // returns { 'b': 2 }
*/
// MODULES //
var pick = require( './pick.js' );
// EXPORTS //
module.exports = pick;
},{"./pick.js":493}],493:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var isStringArray = require( '@stdlib/assert/is-string-array' ).primitives;
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
// MAIN //
/**
* Returns a partial object copy containing only specified keys. If a key does not exist as an own property in a source object, the key is ignored.
*
* @param {Object} obj - source object
* @param {(string|StringArray)} keys - keys to copy
* @throws {TypeError} first argument must be an object
* @throws {TypeError} second argument must be either a string or an array of strings
* @returns {Object} new object
*
* @example
* var obj1 = {
* 'a': 1,
* 'b': 2
* };
*
* var obj2 = pick( obj1, 'b' );
* // returns { 'b': 2 }
*/
function pick( obj, keys ) {
var out;
var key;
var i;
if ( typeof obj !== 'object' || obj === null ) {
throw new TypeError( 'invalid argument. First argument must be an object. Value: `'+obj+'`.' );
}
out = {};
if ( isString( keys ) ) {
if ( hasOwnProp( obj, keys ) ) {
out[ keys ] = obj[ keys ];
}
return out;
}
if ( isStringArray( keys ) ) {
for ( i = 0; i < keys.length; i++ ) {
key = keys[ i ];
if ( hasOwnProp( obj, key ) ) {
out[ key ] = obj[ key ];
}
}
return out;
}
throw new TypeError( 'invalid argument. Second argument must be either a string primitive or an array of string primitives. Value: `'+keys+'`.' );
}
// EXPORTS //
module.exports = pick;
},{"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-string":162,"@stdlib/assert/is-string-array":161}],494:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// VARIABLES //
var propertyDescriptor = Object.getOwnPropertyDescriptor;
// MAIN //
/**
* Returns a property descriptor for an object's own property.
*
* ## Notes
*
* - In contrast to the built-in `Object.getOwnPropertyDescriptor()`, this function returns `null` if provided `undefined` or `null`, rather than throwing an error.
* - In contrast to the built-in `Object.getOwnPropertyDescriptor()`, this function returns `null` if an object does not have a provided property, rather than `undefined`.
*
* @private
* @param {*} value - input object
* @param {(string|symbol)} property - property
* @returns {(Object|null)} property descriptor or null
*
* @example
* var obj = {
* 'beep': 'boop',
* 'foo': 3.14
* };
*
* var desc = getOwnPropertyDescriptor( obj, 'foo' );
* // returns {'configurable':true,'enumerable':true,'writable':true,'value':3.14}
*/
function getOwnPropertyDescriptor( value, property ) {
var desc;
if ( value === null || value === void 0 ) {
return null;
}
desc = propertyDescriptor( value, property );
return ( desc === void 0 ) ? null : desc;
}
// EXPORTS //
module.exports = getOwnPropertyDescriptor;
},{}],495:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var bool = ( typeof Object.getOwnPropertyDescriptor !== 'undefined' );
// EXPORTS //
module.exports = bool;
},{}],496:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Return a property descriptor for an object's own property.
*
* @module @stdlib/utils/property-descriptor
*
* @example
* var getOwnPropertyDescriptor = require( '@stdlib/utils/property-descriptor' );
*
* var obj = {
* 'foo': 'bar',
* 'beep': 'boop'
* };
*
* var keys = getOwnPropertyDescriptor( obj, 'foo' );
* // returns {'configurable':true,'enumerable':true,'writable':true,'value':'bar'}
*/
// MODULES //
var HAS_BUILTIN = require( './has_builtin.js' );
var builtin = require( './builtin.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var main;
if ( HAS_BUILTIN ) {
main = builtin;
} else {
main = polyfill;
}
// EXPORTS //
module.exports = main;
},{"./builtin.js":494,"./has_builtin.js":495,"./polyfill.js":497}],497:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
// MAIN //
/**
* Returns a property descriptor for an object's own property.
*
* ## Notes
*
* - In contrast to the built-in `Object.getOwnPropertyDescriptor()`, this function returns `null` if provided `undefined` or `null`, rather than throwing an error.
* - In contrast to the built-in `Object.getOwnPropertyDescriptor()`, this function returns `null` if an object does not have a provided property, rather than `undefined`.
* - In environments lacking `Object.getOwnPropertyDescriptor()` support, property descriptors do not exist. In non-supporting environment, if an object has a provided property, this function returns a descriptor object equivalent to that returned in a supporting environment; otherwise, the function returns `null`.
*
* @private
* @param {*} value - input object
* @param {(string|symbol)} property - property
* @returns {(Object|null)} property descriptor or null
*
* @example
* var obj = {
* 'beep': 'boop',
* 'foo': 3.14
* };
*
* var desc = getOwnPropertyDescriptor( obj, 'foo' );
* // returns {'configurable':true,'enumerable':true,'writable':true,'value':3.14}
*/
function getOwnPropertyDescriptor( value, property ) {
if ( hasOwnProp( value, property ) ) {
return {
'configurable': true,
'enumerable': true,
'writable': true,
'value': value[ property ]
};
}
return null;
}
// EXPORTS //
module.exports = getOwnPropertyDescriptor;
},{"@stdlib/assert/has-own-property":53}],498:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// VARIABLES //
var propertyNames = Object.getOwnPropertyNames;
// MAIN //
/**
* Returns an array of an object's own enumerable and non-enumerable property names.
*
* ## Notes
*
* - In contrast to the built-in `Object.getOwnPropertyNames()`, this function returns an empty array if provided `undefined` or `null`, rather than throwing an error.
*
* @private
* @param {*} value - input object
* @returns {Array} a list of own property names
*
* @example
* var obj = {
* 'beep': 'boop',
* 'foo': 3.14
* };
*
* var keys = getOwnPropertyNames( obj );
* // e.g., returns [ 'beep', 'foo' ]
*/
function getOwnPropertyNames( value ) {
return propertyNames( Object( value ) );
}
// EXPORTS //
module.exports = getOwnPropertyNames;
},{}],499:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
var bool = ( typeof Object.getOwnPropertyNames !== 'undefined' );
// EXPORTS //
module.exports = bool;
},{}],500:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Return an array of an object's own enumerable and non-enumerable property names.
*
* @module @stdlib/utils/property-names
*
* @example
* var getOwnPropertyNames = require( '@stdlib/utils/property-names' );
*
* var keys = getOwnPropertyNames({
* 'foo': 'bar',
* 'beep': 'boop'
* });
* // e.g., returns [ 'foo', 'beep' ]
*/
// MODULES //
var HAS_BUILTIN = require( './has_builtin.js' );
var builtin = require( './builtin.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var main;
if ( HAS_BUILTIN ) {
main = builtin;
} else {
main = polyfill;
}
// EXPORTS //
module.exports = main;
},{"./builtin.js":498,"./has_builtin.js":499,"./polyfill.js":501}],501:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var keys = require( '@stdlib/utils/keys' );
// MAIN //
/**
* Returns an array of an object's own enumerable and non-enumerable property names.
*
* ## Notes
*
* - In contrast to the built-in `Object.getOwnPropertyNames()`, this function returns an empty array if provided `undefined` or `null`, rather than throwing an error.
* - In environments lacking support for `Object.getOwnPropertyNames()`, property descriptors are unavailable, and thus all properties can be safely assumed to be enumerable. Hence, we can defer to calling `Object.keys`, which retrieves all own enumerable property names.
*
* @private
* @param {*} value - input object
* @returns {Array} a list of own property names
*
* @example
* var obj = {
* 'beep': 'boop',
* 'foo': 3.14
* };
*
* var keys = getOwnPropertyNames( obj );
* // e.g., returns [ 'beep', 'foo' ]
*/
function getOwnPropertyNames( value ) {
return keys( Object( value ) );
}
// EXPORTS //
module.exports = getOwnPropertyNames;
},{"@stdlib/utils/keys":474}],502:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var reRegExp = require( '@stdlib/regexp/regexp' );
// MAIN //
/**
* Parses a regular expression string and returns a new regular expression.
*
* @param {string} str - regular expression string
* @throws {TypeError} must provide a regular expression string
* @returns {(RegExp|null)} regular expression or null
*
* @example
* var re = reFromString( '/beep/' );
* // returns /beep/
*/
function reFromString( str ) {
if ( !isString( str ) ) {
throw new TypeError( 'invalid argument. Must provide a regular expression string. Value: `' + str + '`.' );
}
// Capture the regular expression pattern and any flags:
str = reRegExp().exec( str );
// Create a new regular expression:
return ( str ) ? new RegExp( str[1], str[2] ) : null;
}
// EXPORTS //
module.exports = reFromString;
},{"@stdlib/assert/is-string":162,"@stdlib/regexp/regexp":392}],503:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Create a regular expression from a regular expression string.
*
* @module @stdlib/utils/regexp-from-string
*
* @example
* var reFromString = require( '@stdlib/utils/regexp-from-string' );
*
* var re = reFromString( '/beep/' );
* // returns /beep/
*/
// MODULES //
var reFromString = require( './from_string.js' );
// EXPORTS //
module.exports = reFromString;
},{"./from_string.js":502}],504:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var RE = require( './fixtures/re.js' );
var nodeList = require( './fixtures/nodelist.js' );
var typedarray = require( './fixtures/typedarray.js' );
// MAIN //
/**
* Checks whether a polyfill is needed when using the `typeof` operator.
*
* @private
* @returns {boolean} boolean indicating whether a polyfill is needed
*/
function check() {
if (
// Chrome 1-12 returns 'function' for regular expression instances (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof):
typeof RE === 'function' ||
// Safari 8 returns 'object' for typed array and weak map constructors (underscore #1929):
typeof typedarray === 'object' ||
// PhantomJS 1.9 returns 'function' for `NodeList` instances (underscore #2236):
typeof nodeList === 'function'
) {
return true;
}
return false;
}
// EXPORTS //
module.exports = check;
},{"./fixtures/nodelist.js":505,"./fixtures/re.js":506,"./fixtures/typedarray.js":507}],505:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var getGlobal = require( '@stdlib/utils/global' );
// MAIN //
var root = getGlobal();
var nodeList = root.document && root.document.childNodes;
// EXPORTS //
module.exports = nodeList;
},{"@stdlib/utils/global":453}],506:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
var RE = /./;
// EXPORTS //
module.exports = RE;
},{}],507:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
var typedarray = Int8Array; // eslint-disable-line stdlib/require-globals
// EXPORTS //
module.exports = typedarray;
},{}],508:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Determine a value's type.
*
* @module @stdlib/utils/type-of
*
* @example
* var typeOf = require( '@stdlib/utils/type-of' );
*
* var str = typeOf( 'a' );
* // returns 'string'
*
* str = typeOf( 5 );
* // returns 'number'
*/
// MODULES //
var usePolyfill = require( './check.js' );
var typeOf = require( './typeof.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var main = ( usePolyfill() ) ? polyfill : typeOf;
// EXPORTS //
module.exports = main;
},{"./check.js":504,"./polyfill.js":509,"./typeof.js":510}],509:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var ctorName = require( '@stdlib/utils/constructor-name' );
// MAIN //
/**
* Determines a value's type.
*
* @param {*} v - input value
* @returns {string} string indicating the value's type
*/
function typeOf( v ) {
return ctorName( v ).toLowerCase();
}
// EXPORTS //
module.exports = typeOf;
},{"@stdlib/utils/constructor-name":418}],510:[function(require,module,exports){
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var ctorName = require( '@stdlib/utils/constructor-name' );
// NOTES //
/*
* Built-in `typeof` operator behavior:
*
* ```text
* typeof null => 'object'
* typeof undefined => 'undefined'
* typeof 'a' => 'string'
* typeof 5 => 'number'
* typeof NaN => 'number'
* typeof true => 'boolean'
* typeof false => 'boolean'
* typeof {} => 'object'
* typeof [] => 'object'
* typeof function foo(){} => 'function'
* typeof function* foo(){} => 'object'
* typeof Symbol() => 'symbol'
* ```
*
*/
// MAIN //
/**
* Determines a value's type.
*
* @param {*} v - input value
* @returns {string} string indicating the value's type
*/
function typeOf( v ) {
var type;
// Address `typeof null` => `object` (see http://wiki.ecmascript.org/doku.php?id=harmony:typeof_null):
if ( v === null ) {
return 'null';
}
type = typeof v;
// If the `typeof` operator returned something other than `object`, we are done. Otherwise, we need to check for an internal class name or search for a constructor.
if ( type === 'object' ) {
return ctorName( v ).toLowerCase();
}
return type;
}
// EXPORTS //
module.exports = typeOf;
},{"@stdlib/utils/constructor-name":418}],511:[function(require,module,exports){
'use strict'
exports.byteLength = byteLength
exports.toByteArray = toByteArray
exports.fromByteArray = fromByteArray
var lookup = []
var revLookup = []
var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
for (var i = 0, len = code.length; i < len; ++i) {
lookup[i] = code[i]
revLookup[code.charCodeAt(i)] = i
}
// Support decoding URL-safe base64 strings, as Node.js does.
// See: https://en.wikipedia.org/wiki/Base64#URL_applications
revLookup['-'.charCodeAt(0)] = 62
revLookup['_'.charCodeAt(0)] = 63
function getLens (b64) {
var len = b64.length
if (len % 4 > 0) {
throw new Error('Invalid string. Length must be a multiple of 4')
}
// Trim off extra bytes after placeholder bytes are found
// See: https://github.com/beatgammit/base64-js/issues/42
var validLen = b64.indexOf('=')
if (validLen === -1) validLen = len
var placeHoldersLen = validLen === len
? 0
: 4 - (validLen % 4)
return [validLen, placeHoldersLen]
}
// base64 is 4/3 + up to two characters of the original data
function byteLength (b64) {
var lens = getLens(b64)
var validLen = lens[0]
var placeHoldersLen = lens[1]
return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
}
function _byteLength (b64, validLen, placeHoldersLen) {
return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
}
function toByteArray (b64) {
var tmp
var lens = getLens(b64)
var validLen = lens[0]
var placeHoldersLen = lens[1]
var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
var curByte = 0
// if there are placeholders, only get up to the last complete 4 chars
var len = placeHoldersLen > 0
? validLen - 4
: validLen
var i
for (i = 0; i < len; i += 4) {
tmp =
(revLookup[b64.charCodeAt(i)] << 18) |
(revLookup[b64.charCodeAt(i + 1)] << 12) |
(revLookup[b64.charCodeAt(i + 2)] << 6) |
revLookup[b64.charCodeAt(i + 3)]
arr[curByte++] = (tmp >> 16) & 0xFF
arr[curByte++] = (tmp >> 8) & 0xFF
arr[curByte++] = tmp & 0xFF
}
if (placeHoldersLen === 2) {
tmp =
(revLookup[b64.charCodeAt(i)] << 2) |
(revLookup[b64.charCodeAt(i + 1)] >> 4)
arr[curByte++] = tmp & 0xFF
}
if (placeHoldersLen === 1) {
tmp =
(revLookup[b64.charCodeAt(i)] << 10) |
(revLookup[b64.charCodeAt(i + 1)] << 4) |
(revLookup[b64.charCodeAt(i + 2)] >> 2)
arr[curByte++] = (tmp >> 8) & 0xFF
arr[curByte++] = tmp & 0xFF
}
return arr
}
function tripletToBase64 (num) {
return lookup[num >> 18 & 0x3F] +
lookup[num >> 12 & 0x3F] +
lookup[num >> 6 & 0x3F] +
lookup[num & 0x3F]
}
function encodeChunk (uint8, start, end) {
var tmp
var output = []
for (var i = start; i < end; i += 3) {
tmp =
((uint8[i] << 16) & 0xFF0000) +
((uint8[i + 1] << 8) & 0xFF00) +
(uint8[i + 2] & 0xFF)
output.push(tripletToBase64(tmp))
}
return output.join('')
}
function fromByteArray (uint8) {
var tmp
var len = uint8.length
var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
var parts = []
var maxChunkLength = 16383 // must be multiple of 3
// go through the array every three bytes, we'll deal with trailing stuff later
for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
}
// pad the end with zeros, but make sure to not forget the extra bytes
if (extraBytes === 1) {
tmp = uint8[len - 1]
parts.push(
lookup[tmp >> 2] +
lookup[(tmp << 4) & 0x3F] +
'=='
)
} else if (extraBytes === 2) {
tmp = (uint8[len - 2] << 8) + uint8[len - 1]
parts.push(
lookup[tmp >> 10] +
lookup[(tmp >> 4) & 0x3F] +
lookup[(tmp << 2) & 0x3F] +
'='
)
}
return parts.join('')
}
},{}],512:[function(require,module,exports){
},{}],513:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
'use strict';
var R = typeof Reflect === 'object' ? Reflect : null
var ReflectApply = R && typeof R.apply === 'function'
? R.apply
: function ReflectApply(target, receiver, args) {
return Function.prototype.apply.call(target, receiver, args);
}
var ReflectOwnKeys
if (R && typeof R.ownKeys === 'function') {
ReflectOwnKeys = R.ownKeys
} else if (Object.getOwnPropertySymbols) {
ReflectOwnKeys = function ReflectOwnKeys(target) {
return Object.getOwnPropertyNames(target)
.concat(Object.getOwnPropertySymbols(target));
};
} else {
ReflectOwnKeys = function ReflectOwnKeys(target) {
return Object.getOwnPropertyNames(target);
};
}
function ProcessEmitWarning(warning) {
if (console && console.warn) console.warn(warning);
}
var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {
return value !== value;
}
function EventEmitter() {
EventEmitter.init.call(this);
}
module.exports = EventEmitter;
module.exports.once = once;
// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._eventsCount = 0;
EventEmitter.prototype._maxListeners = undefined;
// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
var defaultMaxListeners = 10;
function checkListener(listener) {
if (typeof listener !== 'function') {
throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
}
}
Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
enumerable: true,
get: function() {
return defaultMaxListeners;
},
set: function(arg) {
if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {
throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.');
}
defaultMaxListeners = arg;
}
});
EventEmitter.init = function() {
if (this._events === undefined ||
this._events === Object.getPrototypeOf(this)._events) {
this._events = Object.create(null);
this._eventsCount = 0;
}
this._maxListeners = this._maxListeners || undefined;
};
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {
throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.');
}
this._maxListeners = n;
return this;
};
function _getMaxListeners(that) {
if (that._maxListeners === undefined)
return EventEmitter.defaultMaxListeners;
return that._maxListeners;
}
EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
return _getMaxListeners(this);
};
EventEmitter.prototype.emit = function emit(type) {
var args = [];
for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);
var doError = (type === 'error');
var events = this._events;
if (events !== undefined)
doError = (doError && events.error === undefined);
else if (!doError)
return false;
// If there is no 'error' event listener then throw.
if (doError) {
var er;
if (args.length > 0)
er = args[0];
if (er instanceof Error) {
// Note: The comments on the `throw` lines are intentional, they show
// up in Node's output if this results in an unhandled exception.
throw er; // Unhandled 'error' event
}
// At least give some kind of context to the user
var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));
err.context = er;
throw err; // Unhandled 'error' event
}
var handler = events[type];
if (handler === undefined)
return false;
if (typeof handler === 'function') {
ReflectApply(handler, this, args);
} else {
var len = handler.length;
var listeners = arrayClone(handler, len);
for (var i = 0; i < len; ++i)
ReflectApply(listeners[i], this, args);
}
return true;
};
function _addListener(target, type, listener, prepend) {
var m;
var events;
var existing;
checkListener(listener);
events = target._events;
if (events === undefined) {
events = target._events = Object.create(null);
target._eventsCount = 0;
} else {
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (events.newListener !== undefined) {
target.emit('newListener', type,
listener.listener ? listener.listener : listener);
// Re-assign `events` because a newListener handler could have caused the
// this._events to be assigned to a new object
events = target._events;
}
existing = events[type];
}
if (existing === undefined) {
// Optimize the case of one listener. Don't need the extra array object.
existing = events[type] = listener;
++target._eventsCount;
} else {
if (typeof existing === 'function') {
// Adding the second element, need to change to array.
existing = events[type] =
prepend ? [listener, existing] : [existing, listener];
// If we've already got an array, just append.
} else if (prepend) {
existing.unshift(listener);
} else {
existing.push(listener);
}
// Check for listener leak
m = _getMaxListeners(target);
if (m > 0 && existing.length > m && !existing.warned) {
existing.warned = true;
// No error code for this since it is a Warning
// eslint-disable-next-line no-restricted-syntax
var w = new Error('Possible EventEmitter memory leak detected. ' +
existing.length + ' ' + String(type) + ' listeners ' +
'added. Use emitter.setMaxListeners() to ' +
'increase limit');
w.name = 'MaxListenersExceededWarning';
w.emitter = target;
w.type = type;
w.count = existing.length;
ProcessEmitWarning(w);
}
}
return target;
}
EventEmitter.prototype.addListener = function addListener(type, listener) {
return _addListener(this, type, listener, false);
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.prependListener =
function prependListener(type, listener) {
return _addListener(this, type, listener, true);
};
function onceWrapper() {
if (!this.fired) {
this.target.removeListener(this.type, this.wrapFn);
this.fired = true;
if (arguments.length === 0)
return this.listener.call(this.target);
return this.listener.apply(this.target, arguments);
}
}
function _onceWrap(target, type, listener) {
var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
var wrapped = onceWrapper.bind(state);
wrapped.listener = listener;
state.wrapFn = wrapped;
return wrapped;
}
EventEmitter.prototype.once = function once(type, listener) {
checkListener(listener);
this.on(type, _onceWrap(this, type, listener));
return this;
};
EventEmitter.prototype.prependOnceListener =
function prependOnceListener(type, listener) {
checkListener(listener);
this.prependListener(type, _onceWrap(this, type, listener));
return this;
};
// Emits a 'removeListener' event if and only if the listener was removed.
EventEmitter.prototype.removeListener =
function removeListener(type, listener) {
var list, events, position, i, originalListener;
checkListener(listener);
events = this._events;
if (events === undefined)
return this;
list = events[type];
if (list === undefined)
return this;
if (list === listener || list.listener === listener) {
if (--this._eventsCount === 0)
this._events = Object.create(null);
else {
delete events[type];
if (events.removeListener)
this.emit('removeListener', type, list.listener || listener);
}
} else if (typeof list !== 'function') {
position = -1;
for (i = list.length - 1; i >= 0; i--) {
if (list[i] === listener || list[i].listener === listener) {
originalListener = list[i].listener;
position = i;
break;
}
}
if (position < 0)
return this;
if (position === 0)
list.shift();
else {
spliceOne(list, position);
}
if (list.length === 1)
events[type] = list[0];
if (events.removeListener !== undefined)
this.emit('removeListener', type, originalListener || listener);
}
return this;
};
EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
EventEmitter.prototype.removeAllListeners =
function removeAllListeners(type) {
var listeners, events, i;
events = this._events;
if (events === undefined)
return this;
// not listening for removeListener, no need to emit
if (events.removeListener === undefined) {
if (arguments.length === 0) {
this._events = Object.create(null);
this._eventsCount = 0;
} else if (events[type] !== undefined) {
if (--this._eventsCount === 0)
this._events = Object.create(null);
else
delete events[type];
}
return this;
}
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
var keys = Object.keys(events);
var key;
for (i = 0; i < keys.length; ++i) {
key = keys[i];
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = Object.create(null);
this._eventsCount = 0;
return this;
}
listeners = events[type];
if (typeof listeners === 'function') {
this.removeListener(type, listeners);
} else if (listeners !== undefined) {
// LIFO order
for (i = listeners.length - 1; i >= 0; i--) {
this.removeListener(type, listeners[i]);
}
}
return this;
};
function _listeners(target, type, unwrap) {
var events = target._events;
if (events === undefined)
return [];
var evlistener = events[type];
if (evlistener === undefined)
return [];
if (typeof evlistener === 'function')
return unwrap ? [evlistener.listener || evlistener] : [evlistener];
return unwrap ?
unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
}
EventEmitter.prototype.listeners = function listeners(type) {
return _listeners(this, type, true);
};
EventEmitter.prototype.rawListeners = function rawListeners(type) {
return _listeners(this, type, false);
};
EventEmitter.listenerCount = function(emitter, type) {
if (typeof emitter.listenerCount === 'function') {
return emitter.listenerCount(type);
} else {
return listenerCount.call(emitter, type);
}
};
EventEmitter.prototype.listenerCount = listenerCount;
function listenerCount(type) {
var events = this._events;
if (events !== undefined) {
var evlistener = events[type];
if (typeof evlistener === 'function') {
return 1;
} else if (evlistener !== undefined) {
return evlistener.length;
}
}
return 0;
}
EventEmitter.prototype.eventNames = function eventNames() {
return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];
};
function arrayClone(arr, n) {
var copy = new Array(n);
for (var i = 0; i < n; ++i)
copy[i] = arr[i];
return copy;
}
function spliceOne(list, index) {
for (; index + 1 < list.length; index++)
list[index] = list[index + 1];
list.pop();
}
function unwrapListeners(arr) {
var ret = new Array(arr.length);
for (var i = 0; i < ret.length; ++i) {
ret[i] = arr[i].listener || arr[i];
}
return ret;
}
function once(emitter, name) {
return new Promise(function (resolve, reject) {
function errorListener(err) {
emitter.removeListener(name, resolver);
reject(err);
}
function resolver() {
if (typeof emitter.removeListener === 'function') {
emitter.removeListener('error', errorListener);
}
resolve([].slice.call(arguments));
};
eventTargetAgnosticAddListener(emitter, name, resolver, { once: true });
if (name !== 'error') {
addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true });
}
});
}
function addErrorHandlerIfEventEmitter(emitter, handler, flags) {
if (typeof emitter.on === 'function') {
eventTargetAgnosticAddListener(emitter, 'error', handler, flags);
}
}
function eventTargetAgnosticAddListener(emitter, name, listener, flags) {
if (typeof emitter.on === 'function') {
if (flags.once) {
emitter.once(name, listener);
} else {
emitter.on(name, listener);
}
} else if (typeof emitter.addEventListener === 'function') {
// EventTarget does not have `error` event semantics like Node
// EventEmitters, we do not listen for `error` events here.
emitter.addEventListener(name, function wrapListener(arg) {
// IE does not have builtin `{ once: true }` support so we
// have to do it manually.
if (flags.once) {
emitter.removeEventListener(name, wrapListener);
}
listener(arg);
});
} else {
throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter);
}
}
},{}],514:[function(require,module,exports){
(function (Buffer){(function (){
/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <https://feross.org>
* @license MIT
*/
/* eslint-disable no-proto */
'use strict'
var base64 = require('base64-js')
var ieee754 = require('ieee754')
exports.Buffer = Buffer
exports.SlowBuffer = SlowBuffer
exports.INSPECT_MAX_BYTES = 50
var K_MAX_LENGTH = 0x7fffffff
exports.kMaxLength = K_MAX_LENGTH
/**
* If `Buffer.TYPED_ARRAY_SUPPORT`:
* === true Use Uint8Array implementation (fastest)
* === false Print warning and recommend using `buffer` v4.x which has an Object
* implementation (most compatible, even IE6)
*
* Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
* Opera 11.6+, iOS 4.2+.
*
* We report that the browser does not support typed arrays if the are not subclassable
* using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
* (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
* for __proto__ and has a buggy typed array implementation.
*/
Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
typeof console.error === 'function') {
console.error(
'This browser lacks typed array (Uint8Array) support which is required by ' +
'`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
)
}
function typedArraySupport () {
// Can typed array instances can be augmented?
try {
var arr = new Uint8Array(1)
arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } }
return arr.foo() === 42
} catch (e) {
return false
}
}
Object.defineProperty(Buffer.prototype, 'parent', {
enumerable: true,
get: function () {
if (!Buffer.isBuffer(this)) return undefined
return this.buffer
}
})
Object.defineProperty(Buffer.prototype, 'offset', {
enumerable: true,
get: function () {
if (!Buffer.isBuffer(this)) return undefined
return this.byteOffset
}
})
function createBuffer (length) {
if (length > K_MAX_LENGTH) {
throw new RangeError('The value "' + length + '" is invalid for option "size"')
}
// Return an augmented `Uint8Array` instance
var buf = new Uint8Array(length)
buf.__proto__ = Buffer.prototype
return buf
}
/**
* The Buffer constructor returns instances of `Uint8Array` that have their
* prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
* `Uint8Array`, so the returned instances will have all the node `Buffer` methods
* and the `Uint8Array` methods. Square bracket notation works as expected -- it
* returns a single octet.
*
* The `Uint8Array` prototype remains unmodified.
*/
function Buffer (arg, encodingOrOffset, length) {
// Common case.
if (typeof arg === 'number') {
if (typeof encodingOrOffset === 'string') {
throw new TypeError(
'The "string" argument must be of type string. Received type number'
)
}
return allocUnsafe(arg)
}
return from(arg, encodingOrOffset, length)
}
// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
if (typeof Symbol !== 'undefined' && Symbol.species != null &&
Buffer[Symbol.species] === Buffer) {
Object.defineProperty(Buffer, Symbol.species, {
value: null,
configurable: true,
enumerable: false,
writable: false
})
}
Buffer.poolSize = 8192 // not used by this implementation
function from (value, encodingOrOffset, length) {
if (typeof value === 'string') {
return fromString(value, encodingOrOffset)
}
if (ArrayBuffer.isView(value)) {
return fromArrayLike(value)
}
if (value == null) {
throw TypeError(
'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
'or Array-like Object. Received type ' + (typeof value)
)
}
if (isInstance(value, ArrayBuffer) ||
(value && isInstance(value.buffer, ArrayBuffer))) {
return fromArrayBuffer(value, encodingOrOffset, length)
}
if (typeof value === 'number') {
throw new TypeError(
'The "value" argument must not be of type number. Received type number'
)
}
var valueOf = value.valueOf && value.valueOf()
if (valueOf != null && valueOf !== value) {
return Buffer.from(valueOf, encodingOrOffset, length)
}
var b = fromObject(value)
if (b) return b
if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
typeof value[Symbol.toPrimitive] === 'function') {
return Buffer.from(
value[Symbol.toPrimitive]('string'), encodingOrOffset, length
)
}
throw new TypeError(
'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
'or Array-like Object. Received type ' + (typeof value)
)
}
/**
* Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
* if value is a number.
* Buffer.from(str[, encoding])
* Buffer.from(array)
* Buffer.from(buffer)
* Buffer.from(arrayBuffer[, byteOffset[, length]])
**/
Buffer.from = function (value, encodingOrOffset, length) {
return from(value, encodingOrOffset, length)
}
// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
// https://github.com/feross/buffer/pull/148
Buffer.prototype.__proto__ = Uint8Array.prototype
Buffer.__proto__ = Uint8Array
function assertSize (size) {
if (typeof size !== 'number') {
throw new TypeError('"size" argument must be of type number')
} else if (size < 0) {
throw new RangeError('The value "' + size + '" is invalid for option "size"')
}
}
function alloc (size, fill, encoding) {
assertSize(size)
if (size <= 0) {
return createBuffer(size)
}
if (fill !== undefined) {
// Only pay attention to encoding if it's a string. This
// prevents accidentally sending in a number that would
// be interpretted as a start offset.
return typeof encoding === 'string'
? createBuffer(size).fill(fill, encoding)
: createBuffer(size).fill(fill)
}
return createBuffer(size)
}
/**
* Creates a new filled Buffer instance.
* alloc(size[, fill[, encoding]])
**/
Buffer.alloc = function (size, fill, encoding) {
return alloc(size, fill, encoding)
}
function allocUnsafe (size) {
assertSize(size)
return createBuffer(size < 0 ? 0 : checked(size) | 0)
}
/**
* Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
* */
Buffer.allocUnsafe = function (size) {
return allocUnsafe(size)
}
/**
* Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
*/
Buffer.allocUnsafeSlow = function (size) {
return allocUnsafe(size)
}
function fromString (string, encoding) {
if (typeof encoding !== 'string' || encoding === '') {
encoding = 'utf8'
}
if (!Buffer.isEncoding(encoding)) {
throw new TypeError('Unknown encoding: ' + encoding)
}
var length = byteLength(string, encoding) | 0
var buf = createBuffer(length)
var actual = buf.write(string, encoding)
if (actual !== length) {
// Writing a hex string, for example, that contains invalid characters will
// cause everything after the first invalid character to be ignored. (e.g.
// 'abxxcd' will be treated as 'ab')
buf = buf.slice(0, actual)
}
return buf
}
function fromArrayLike (array) {
var length = array.length < 0 ? 0 : checked(array.length) | 0
var buf = createBuffer(length)
for (var i = 0; i < length; i += 1) {
buf[i] = array[i] & 255
}
return buf
}
function fromArrayBuffer (array, byteOffset, length) {
if (byteOffset < 0 || array.byteLength < byteOffset) {
throw new RangeError('"offset" is outside of buffer bounds')
}
if (array.byteLength < byteOffset + (length || 0)) {
throw new RangeError('"length" is outside of buffer bounds')
}
var buf
if (byteOffset === undefined && length === undefined) {
buf = new Uint8Array(array)
} else if (length === undefined) {
buf = new Uint8Array(array, byteOffset)
} else {
buf = new Uint8Array(array, byteOffset, length)
}
// Return an augmented `Uint8Array` instance
buf.__proto__ = Buffer.prototype
return buf
}
function fromObject (obj) {
if (Buffer.isBuffer(obj)) {
var len = checked(obj.length) | 0
var buf = createBuffer(len)
if (buf.length === 0) {
return buf
}
obj.copy(buf, 0, 0, len)
return buf
}
if (obj.length !== undefined) {
if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
return createBuffer(0)
}
return fromArrayLike(obj)
}
if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
return fromArrayLike(obj.data)
}
}
function checked (length) {
// Note: cannot use `length < K_MAX_LENGTH` here because that fails when
// length is NaN (which is otherwise coerced to zero.)
if (length >= K_MAX_LENGTH) {
throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
}
return length | 0
}
function SlowBuffer (length) {
if (+length != length) { // eslint-disable-line eqeqeq
length = 0
}
return Buffer.alloc(+length)
}
Buffer.isBuffer = function isBuffer (b) {
return b != null && b._isBuffer === true &&
b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
}
Buffer.compare = function compare (a, b) {
if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)
if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)
if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
throw new TypeError(
'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
)
}
if (a === b) return 0
var x = a.length
var y = b.length
for (var i = 0, len = Math.min(x, y); i < len; ++i) {
if (a[i] !== b[i]) {
x = a[i]
y = b[i]
break
}
}
if (x < y) return -1
if (y < x) return 1
return 0
}
Buffer.isEncoding = function isEncoding (encoding) {
switch (String(encoding).toLowerCase()) {
case 'hex':
case 'utf8':
case 'utf-8':
case 'ascii':
case 'latin1':
case 'binary':
case 'base64':
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return true
default:
return false
}
}
Buffer.concat = function concat (list, length) {
if (!Array.isArray(list)) {
throw new TypeError('"list" argument must be an Array of Buffers')
}
if (list.length === 0) {
return Buffer.alloc(0)
}
var i
if (length === undefined) {
length = 0
for (i = 0; i < list.length; ++i) {
length += list[i].length
}
}
var buffer = Buffer.allocUnsafe(length)
var pos = 0
for (i = 0; i < list.length; ++i) {
var buf = list[i]
if (isInstance(buf, Uint8Array)) {
buf = Buffer.from(buf)
}
if (!Buffer.isBuffer(buf)) {
throw new TypeError('"list" argument must be an Array of Buffers')
}
buf.copy(buffer, pos)
pos += buf.length
}
return buffer
}
function byteLength (string, encoding) {
if (Buffer.isBuffer(string)) {
return string.length
}
if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
return string.byteLength
}
if (typeof string !== 'string') {
throw new TypeError(
'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
'Received type ' + typeof string
)
}
var len = string.length
var mustMatch = (arguments.length > 2 && arguments[2] === true)
if (!mustMatch && len === 0) return 0
// Use a for loop to avoid recursion
var loweredCase = false
for (;;) {
switch (encoding) {
case 'ascii':
case 'latin1':
case 'binary':
return len
case 'utf8':
case 'utf-8':
return utf8ToBytes(string).length
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return len * 2
case 'hex':
return len >>> 1
case 'base64':
return base64ToBytes(string).length
default:
if (loweredCase) {
return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
}
encoding = ('' + encoding).toLowerCase()
loweredCase = true
}
}
}
Buffer.byteLength = byteLength
function slowToString (encoding, start, end) {
var loweredCase = false
// No need to verify that "this.length <= MAX_UINT32" since it's a read-only
// property of a typed array.
// This behaves neither like String nor Uint8Array in that we set start/end
// to their upper/lower bounds if the value passed is out of range.
// undefined is handled specially as per ECMA-262 6th Edition,
// Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
if (start === undefined || start < 0) {
start = 0
}
// Return early if start > this.length. Done here to prevent potential uint32
// coercion fail below.
if (start > this.length) {
return ''
}
if (end === undefined || end > this.length) {
end = this.length
}
if (end <= 0) {
return ''
}
// Force coersion to uint32. This will also coerce falsey/NaN values to 0.
end >>>= 0
start >>>= 0
if (end <= start) {
return ''
}
if (!encoding) encoding = 'utf8'
while (true) {
switch (encoding) {
case 'hex':
return hexSlice(this, start, end)
case 'utf8':
case 'utf-8':
return utf8Slice(this, start, end)
case 'ascii':
return asciiSlice(this, start, end)
case 'latin1':
case 'binary':
return latin1Slice(this, start, end)
case 'base64':
return base64Slice(this, start, end)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return utf16leSlice(this, start, end)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = (encoding + '').toLowerCase()
loweredCase = true
}
}
}
// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
// reliably in a browserify context because there could be multiple different
// copies of the 'buffer' package in use. This method works even for Buffer
// instances that were created from another copy of the `buffer` package.
// See: https://github.com/feross/buffer/issues/154
Buffer.prototype._isBuffer = true
function swap (b, n, m) {
var i = b[n]
b[n] = b[m]
b[m] = i
}
Buffer.prototype.swap16 = function swap16 () {
var len = this.length
if (len % 2 !== 0) {
throw new RangeError('Buffer size must be a multiple of 16-bits')
}
for (var i = 0; i < len; i += 2) {
swap(this, i, i + 1)
}
return this
}
Buffer.prototype.swap32 = function swap32 () {
var len = this.length
if (len % 4 !== 0) {
throw new RangeError('Buffer size must be a multiple of 32-bits')
}
for (var i = 0; i < len; i += 4) {
swap(this, i, i + 3)
swap(this, i + 1, i + 2)
}
return this
}
Buffer.prototype.swap64 = function swap64 () {
var len = this.length
if (len % 8 !== 0) {
throw new RangeError('Buffer size must be a multiple of 64-bits')
}
for (var i = 0; i < len; i += 8) {
swap(this, i, i + 7)
swap(this, i + 1, i + 6)
swap(this, i + 2, i + 5)
swap(this, i + 3, i + 4)
}
return this
}
Buffer.prototype.toString = function toString () {
var length = this.length
if (length === 0) return ''
if (arguments.length === 0) return utf8Slice(this, 0, length)
return slowToString.apply(this, arguments)
}
Buffer.prototype.toLocaleString = Buffer.prototype.toString
Buffer.prototype.equals = function equals (b) {
if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
if (this === b) return true
return Buffer.compare(this, b) === 0
}
Buffer.prototype.inspect = function inspect () {
var str = ''
var max = exports.INSPECT_MAX_BYTES
str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()
if (this.length > max) str += ' ... '
return '<Buffer ' + str + '>'
}
Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
if (isInstance(target, Uint8Array)) {
target = Buffer.from(target, target.offset, target.byteLength)
}
if (!Buffer.isBuffer(target)) {
throw new TypeError(
'The "target" argument must be one of type Buffer or Uint8Array. ' +
'Received type ' + (typeof target)
)
}
if (start === undefined) {
start = 0
}
if (end === undefined) {
end = target ? target.length : 0
}
if (thisStart === undefined) {
thisStart = 0
}
if (thisEnd === undefined) {
thisEnd = this.length
}
if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
throw new RangeError('out of range index')
}
if (thisStart >= thisEnd && start >= end) {
return 0
}
if (thisStart >= thisEnd) {
return -1
}
if (start >= end) {
return 1
}
start >>>= 0
end >>>= 0
thisStart >>>= 0
thisEnd >>>= 0
if (this === target) return 0
var x = thisEnd - thisStart
var y = end - start
var len = Math.min(x, y)
var thisCopy = this.slice(thisStart, thisEnd)
var targetCopy = target.slice(start, end)
for (var i = 0; i < len; ++i) {
if (thisCopy[i] !== targetCopy[i]) {
x = thisCopy[i]
y = targetCopy[i]
break
}
}
if (x < y) return -1
if (y < x) return 1
return 0
}
// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
//
// Arguments:
// - buffer - a Buffer to search
// - val - a string, Buffer, or number
// - byteOffset - an index into `buffer`; will be clamped to an int32
// - encoding - an optional encoding, relevant is val is a string
// - dir - true for indexOf, false for lastIndexOf
function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
// Empty buffer means no match
if (buffer.length === 0) return -1
// Normalize byteOffset
if (typeof byteOffset === 'string') {
encoding = byteOffset
byteOffset = 0
} else if (byteOffset > 0x7fffffff) {
byteOffset = 0x7fffffff
} else if (byteOffset < -0x80000000) {
byteOffset = -0x80000000
}
byteOffset = +byteOffset // Coerce to Number.
if (numberIsNaN(byteOffset)) {
// byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
byteOffset = dir ? 0 : (buffer.length - 1)
}
// Normalize byteOffset: negative offsets start from the end of the buffer
if (byteOffset < 0) byteOffset = buffer.length + byteOffset
if (byteOffset >= buffer.length) {
if (dir) return -1
else byteOffset = buffer.length - 1
} else if (byteOffset < 0) {
if (dir) byteOffset = 0
else return -1
}
// Normalize val
if (typeof val === 'string') {
val = Buffer.from(val, encoding)
}
// Finally, search either indexOf (if dir is true) or lastIndexOf
if (Buffer.isBuffer(val)) {
// Special case: looking for empty string/buffer always fails
if (val.length === 0) {
return -1
}
return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
} else if (typeof val === 'number') {
val = val & 0xFF // Search for a byte value [0-255]
if (typeof Uint8Array.prototype.indexOf === 'function') {
if (dir) {
return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
} else {
return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
}
}
return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
}
throw new TypeError('val must be string, number or Buffer')
}
function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
var indexSize = 1
var arrLength = arr.length
var valLength = val.length
if (encoding !== undefined) {
encoding = String(encoding).toLowerCase()
if (encoding === 'ucs2' || encoding === 'ucs-2' ||
encoding === 'utf16le' || encoding === 'utf-16le') {
if (arr.length < 2 || val.length < 2) {
return -1
}
indexSize = 2
arrLength /= 2
valLength /= 2
byteOffset /= 2
}
}
function read (buf, i) {
if (indexSize === 1) {
return buf[i]
} else {
return buf.readUInt16BE(i * indexSize)
}
}
var i
if (dir) {
var foundIndex = -1
for (i = byteOffset; i < arrLength; i++) {
if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
if (foundIndex === -1) foundIndex = i
if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
} else {
if (foundIndex !== -1) i -= i - foundIndex
foundIndex = -1
}
}
} else {
if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
for (i = byteOffset; i >= 0; i--) {
var found = true
for (var j = 0; j < valLength; j++) {
if (read(arr, i + j) !== read(val, j)) {
found = false
break
}
}
if (found) return i
}
}
return -1
}
Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
return this.indexOf(val, byteOffset, encoding) !== -1
}
Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
}
Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
}
function hexWrite (buf, string, offset, length) {
offset = Number(offset) || 0
var remaining = buf.length - offset
if (!length) {
length = remaining
} else {
length = Number(length)
if (length > remaining) {
length = remaining
}
}
var strLen = string.length
if (length > strLen / 2) {
length = strLen / 2
}
for (var i = 0; i < length; ++i) {
var parsed = parseInt(string.substr(i * 2, 2), 16)
if (numberIsNaN(parsed)) return i
buf[offset + i] = parsed
}
return i
}
function utf8Write (buf, string, offset, length) {
return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
}
function asciiWrite (buf, string, offset, length) {
return blitBuffer(asciiToBytes(string), buf, offset, length)
}
function latin1Write (buf, string, offset, length) {
return asciiWrite(buf, string, offset, length)
}
function base64Write (buf, string, offset, length) {
return blitBuffer(base64ToBytes(string), buf, offset, length)
}
function ucs2Write (buf, string, offset, length) {
return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
}
Buffer.prototype.write = function write (string, offset, length, encoding) {
// Buffer#write(string)
if (offset === undefined) {
encoding = 'utf8'
length = this.length
offset = 0
// Buffer#write(string, encoding)
} else if (length === undefined && typeof offset === 'string') {
encoding = offset
length = this.length
offset = 0
// Buffer#write(string, offset[, length][, encoding])
} else if (isFinite(offset)) {
offset = offset >>> 0
if (isFinite(length)) {
length = length >>> 0
if (encoding === undefined) encoding = 'utf8'
} else {
encoding = length
length = undefined
}
} else {
throw new Error(
'Buffer.write(string, encoding, offset[, length]) is no longer supported'
)
}
var remaining = this.length - offset
if (length === undefined || length > remaining) length = remaining
if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
throw new RangeError('Attempt to write outside buffer bounds')
}
if (!encoding) encoding = 'utf8'
var loweredCase = false
for (;;) {
switch (encoding) {
case 'hex':
return hexWrite(this, string, offset, length)
case 'utf8':
case 'utf-8':
return utf8Write(this, string, offset, length)
case 'ascii':
return asciiWrite(this, string, offset, length)
case 'latin1':
case 'binary':
return latin1Write(this, string, offset, length)
case 'base64':
// Warning: maxLength not taken into account in base64Write
return base64Write(this, string, offset, length)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return ucs2Write(this, string, offset, length)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = ('' + encoding).toLowerCase()
loweredCase = true
}
}
}
Buffer.prototype.toJSON = function toJSON () {
return {
type: 'Buffer',
data: Array.prototype.slice.call(this._arr || this, 0)
}
}
function base64Slice (buf, start, end) {
if (start === 0 && end === buf.length) {
return base64.fromByteArray(buf)
} else {
return base64.fromByteArray(buf.slice(start, end))
}
}
function utf8Slice (buf, start, end) {
end = Math.min(buf.length, end)
var res = []
var i = start
while (i < end) {
var firstByte = buf[i]
var codePoint = null
var bytesPerSequence = (firstByte > 0xEF) ? 4
: (firstByte > 0xDF) ? 3
: (firstByte > 0xBF) ? 2
: 1
if (i + bytesPerSequence <= end) {
var secondByte, thirdByte, fourthByte, tempCodePoint
switch (bytesPerSequence) {
case 1:
if (firstByte < 0x80) {
codePoint = firstByte
}
break
case 2:
secondByte = buf[i + 1]
if ((secondByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
if (tempCodePoint > 0x7F) {
codePoint = tempCodePoint
}
}
break
case 3:
secondByte = buf[i + 1]
thirdByte = buf[i + 2]
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
codePoint = tempCodePoint
}
}
break
case 4:
secondByte = buf[i + 1]
thirdByte = buf[i + 2]
fourthByte = buf[i + 3]
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
codePoint = tempCodePoint
}
}
}
}
if (codePoint === null) {
// we did not generate a valid codePoint so insert a
// replacement char (U+FFFD) and advance only 1 byte
codePoint = 0xFFFD
bytesPerSequence = 1
} else if (codePoint > 0xFFFF) {
// encode to utf16 (surrogate pair dance)
codePoint -= 0x10000
res.push(codePoint >>> 10 & 0x3FF | 0xD800)
codePoint = 0xDC00 | codePoint & 0x3FF
}
res.push(codePoint)
i += bytesPerSequence
}
return decodeCodePointsArray(res)
}
// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
var MAX_ARGUMENTS_LENGTH = 0x1000
function decodeCodePointsArray (codePoints) {
var len = codePoints.length
if (len <= MAX_ARGUMENTS_LENGTH) {
return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
}
// Decode in chunks to avoid "call stack size exceeded".
var res = ''
var i = 0
while (i < len) {
res += String.fromCharCode.apply(
String,
codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
)
}
return res
}
function asciiSlice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i] & 0x7F)
}
return ret
}
function latin1Slice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i])
}
return ret
}
function hexSlice (buf, start, end) {
var len = buf.length
if (!start || start < 0) start = 0
if (!end || end < 0 || end > len) end = len
var out = ''
for (var i = start; i < end; ++i) {
out += toHex(buf[i])
}
return out
}
function utf16leSlice (buf, start, end) {
var bytes = buf.slice(start, end)
var res = ''
for (var i = 0; i < bytes.length; i += 2) {
res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
}
return res
}
Buffer.prototype.slice = function slice (start, end) {
var len = this.length
start = ~~start
end = end === undefined ? len : ~~end
if (start < 0) {
start += len
if (start < 0) start = 0
} else if (start > len) {
start = len
}
if (end < 0) {
end += len
if (end < 0) end = 0
} else if (end > len) {
end = len
}
if (end < start) end = start
var newBuf = this.subarray(start, end)
// Return an augmented `Uint8Array` instance
newBuf.__proto__ = Buffer.prototype
return newBuf
}
/*
* Need to make sure that buffer isn't trying to write out of bounds.
*/
function checkOffset (offset, ext, length) {
if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
}
Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var val = this[offset]
var mul = 1
var i = 0
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul
}
return val
}
Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) {
checkOffset(offset, byteLength, this.length)
}
var val = this[offset + --byteLength]
var mul = 1
while (byteLength > 0 && (mul *= 0x100)) {
val += this[offset + --byteLength] * mul
}
return val
}
Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 1, this.length)
return this[offset]
}
Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
return this[offset] | (this[offset + 1] << 8)
}
Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
return (this[offset] << 8) | this[offset + 1]
}
Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return ((this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16)) +
(this[offset + 3] * 0x1000000)
}
Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] * 0x1000000) +
((this[offset + 1] << 16) |
(this[offset + 2] << 8) |
this[offset + 3])
}
Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var val = this[offset]
var mul = 1
var i = 0
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul
}
mul *= 0x80
if (val >= mul) val -= Math.pow(2, 8 * byteLength)
return val
}
Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var i = byteLength
var mul = 1
var val = this[offset + --i]
while (i > 0 && (mul *= 0x100)) {
val += this[offset + --i] * mul
}
mul *= 0x80
if (val >= mul) val -= Math.pow(2, 8 * byteLength)
return val
}
Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 1, this.length)
if (!(this[offset] & 0x80)) return (this[offset])
return ((0xff - this[offset] + 1) * -1)
}
Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset] | (this[offset + 1] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset + 1] | (this[offset] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16) |
(this[offset + 3] << 24)
}
Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] << 24) |
(this[offset + 1] << 16) |
(this[offset + 2] << 8) |
(this[offset + 3])
}
Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, true, 23, 4)
}
Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, false, 23, 4)
}
Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, true, 52, 8)
}
Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, false, 52, 8)
}
function checkInt (buf, value, offset, ext, max, min) {
if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
if (offset + ext > buf.length) throw new RangeError('Index out of range')
}
Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) {
var maxBytes = Math.pow(2, 8 * byteLength) - 1
checkInt(this, value, offset, byteLength, maxBytes, 0)
}
var mul = 1
var i = 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
this[offset + i] = (value / mul) & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) {
var maxBytes = Math.pow(2, 8 * byteLength) - 1
checkInt(this, value, offset, byteLength, maxBytes, 0)
}
var i = byteLength - 1
var mul = 1
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
this[offset + i] = (value / mul) & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
this[offset] = (value & 0xff)
return offset + 1
}
Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
return offset + 2
}
Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
this[offset] = (value >>> 8)
this[offset + 1] = (value & 0xff)
return offset + 2
}
Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
this[offset + 3] = (value >>> 24)
this[offset + 2] = (value >>> 16)
this[offset + 1] = (value >>> 8)
this[offset] = (value & 0xff)
return offset + 4
}
Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = (value & 0xff)
return offset + 4
}
Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
var limit = Math.pow(2, (8 * byteLength) - 1)
checkInt(this, value, offset, byteLength, limit - 1, -limit)
}
var i = 0
var mul = 1
var sub = 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
sub = 1
}
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
var limit = Math.pow(2, (8 * byteLength) - 1)
checkInt(this, value, offset, byteLength, limit - 1, -limit)
}
var i = byteLength - 1
var mul = 1
var sub = 0
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
sub = 1
}
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
if (value < 0) value = 0xff + value + 1
this[offset] = (value & 0xff)
return offset + 1
}
Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
return offset + 2
}
Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
this[offset] = (value >>> 8)
this[offset + 1] = (value & 0xff)
return offset + 2
}
Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
this[offset + 2] = (value >>> 16)
this[offset + 3] = (value >>> 24)
return offset + 4
}
Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
if (value < 0) value = 0xffffffff + value + 1
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = (value & 0xff)
return offset + 4
}
function checkIEEE754 (buf, value, offset, ext, max, min) {
if (offset + ext > buf.length) throw new RangeError('Index out of range')
if (offset < 0) throw new RangeError('Index out of range')
}
function writeFloat (buf, value, offset, littleEndian, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
}
ieee754.write(buf, value, offset, littleEndian, 23, 4)
return offset + 4
}
Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
return writeFloat(this, value, offset, true, noAssert)
}
Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
return writeFloat(this, value, offset, false, noAssert)
}
function writeDouble (buf, value, offset, littleEndian, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
}
ieee754.write(buf, value, offset, littleEndian, 52, 8)
return offset + 8
}
Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
return writeDouble(this, value, offset, true, noAssert)
}
Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
return writeDouble(this, value, offset, false, noAssert)
}
// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
Buffer.prototype.copy = function copy (target, targetStart, start, end) {
if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
if (!start) start = 0
if (!end && end !== 0) end = this.length
if (targetStart >= target.length) targetStart = target.length
if (!targetStart) targetStart = 0
if (end > 0 && end < start) end = start
// Copy 0 bytes; we're done
if (end === start) return 0
if (target.length === 0 || this.length === 0) return 0
// Fatal error conditions
if (targetStart < 0) {
throw new RangeError('targetStart out of bounds')
}
if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
if (end < 0) throw new RangeError('sourceEnd out of bounds')
// Are we oob?
if (end > this.length) end = this.length
if (target.length - targetStart < end - start) {
end = target.length - targetStart + start
}
var len = end - start
if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
// Use built-in when available, missing from IE11
this.copyWithin(targetStart, start, end)
} else if (this === target && start < targetStart && targetStart < end) {
// descending copy from end
for (var i = len - 1; i >= 0; --i) {
target[i + targetStart] = this[i + start]
}
} else {
Uint8Array.prototype.set.call(
target,
this.subarray(start, end),
targetStart
)
}
return len
}
// Usage:
// buffer.fill(number[, offset[, end]])
// buffer.fill(buffer[, offset[, end]])
// buffer.fill(string[, offset[, end]][, encoding])
Buffer.prototype.fill = function fill (val, start, end, encoding) {
// Handle string cases:
if (typeof val === 'string') {
if (typeof start === 'string') {
encoding = start
start = 0
end = this.length
} else if (typeof end === 'string') {
encoding = end
end = this.length
}
if (encoding !== undefined && typeof encoding !== 'string') {
throw new TypeError('encoding must be a string')
}
if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
throw new TypeError('Unknown encoding: ' + encoding)
}
if (val.length === 1) {
var code = val.charCodeAt(0)
if ((encoding === 'utf8' && code < 128) ||
encoding === 'latin1') {
// Fast path: If `val` fits into a single byte, use that numeric value.
val = code
}
}
} else if (typeof val === 'number') {
val = val & 255
}
// Invalid ranges are not set to a default, so can range check early.
if (start < 0 || this.length < start || this.length < end) {
throw new RangeError('Out of range index')
}
if (end <= start) {
return this
}
start = start >>> 0
end = end === undefined ? this.length : end >>> 0
if (!val) val = 0
var i
if (typeof val === 'number') {
for (i = start; i < end; ++i) {
this[i] = val
}
} else {
var bytes = Buffer.isBuffer(val)
? val
: Buffer.from(val, encoding)
var len = bytes.length
if (len === 0) {
throw new TypeError('The value "' + val +
'" is invalid for argument "value"')
}
for (i = 0; i < end - start; ++i) {
this[i + start] = bytes[i % len]
}
}
return this
}
// HELPER FUNCTIONS
// ================
var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
function base64clean (str) {
// Node takes equal signs as end of the Base64 encoding
str = str.split('=')[0]
// Node strips out invalid characters like \n and \t from the string, base64-js does not
str = str.trim().replace(INVALID_BASE64_RE, '')
// Node converts strings with length < 2 to ''
if (str.length < 2) return ''
// Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
while (str.length % 4 !== 0) {
str = str + '='
}
return str
}
function toHex (n) {
if (n < 16) return '0' + n.toString(16)
return n.toString(16)
}
function utf8ToBytes (string, units) {
units = units || Infinity
var codePoint
var length = string.length
var leadSurrogate = null
var bytes = []
for (var i = 0; i < length; ++i) {
codePoint = string.charCodeAt(i)
// is surrogate component
if (codePoint > 0xD7FF && codePoint < 0xE000) {
// last char was a lead
if (!leadSurrogate) {
// no lead yet
if (codePoint > 0xDBFF) {
// unexpected trail
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
} else if (i + 1 === length) {
// unpaired lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
}
// valid lead
leadSurrogate = codePoint
continue
}
// 2 leads in a row
if (codePoint < 0xDC00) {
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
leadSurrogate = codePoint
continue
}
// valid surrogate pair
codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
} else if (leadSurrogate) {
// valid bmp char, but last char was a lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
}
leadSurrogate = null
// encode utf8
if (codePoint < 0x80) {
if ((units -= 1) < 0) break
bytes.push(codePoint)
} else if (codePoint < 0x800) {
if ((units -= 2) < 0) break
bytes.push(
codePoint >> 0x6 | 0xC0,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x10000) {
if ((units -= 3) < 0) break
bytes.push(
codePoint >> 0xC | 0xE0,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x110000) {
if ((units -= 4) < 0) break
bytes.push(
codePoint >> 0x12 | 0xF0,
codePoint >> 0xC & 0x3F | 0x80,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else {
throw new Error('Invalid code point')
}
}
return bytes
}
function asciiToBytes (str) {
var byteArray = []
for (var i = 0; i < str.length; ++i) {
// Node's code seems to be doing this and not & 0x7F..
byteArray.push(str.charCodeAt(i) & 0xFF)
}
return byteArray
}
function utf16leToBytes (str, units) {
var c, hi, lo
var byteArray = []
for (var i = 0; i < str.length; ++i) {
if ((units -= 2) < 0) break
c = str.charCodeAt(i)
hi = c >> 8
lo = c % 256
byteArray.push(lo)
byteArray.push(hi)
}
return byteArray
}
function base64ToBytes (str) {
return base64.toByteArray(base64clean(str))
}
function blitBuffer (src, dst, offset, length) {
for (var i = 0; i < length; ++i) {
if ((i + offset >= dst.length) || (i >= src.length)) break
dst[i + offset] = src[i]
}
return i
}
// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
// the `instanceof` check but they should be treated as of that type.
// See: https://github.com/feross/buffer/issues/166
function isInstance (obj, type) {
return obj instanceof type ||
(obj != null && obj.constructor != null && obj.constructor.name != null &&
obj.constructor.name === type.name)
}
function numberIsNaN (obj) {
// For IE11 support
return obj !== obj // eslint-disable-line no-self-compare
}
}).call(this)}).call(this,require("buffer").Buffer)
},{"base64-js":511,"buffer":514,"ieee754":518}],515:[function(require,module,exports){
(function (Buffer){(function (){
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(arg) {
if (Array.isArray) {
return Array.isArray(arg);
}
return objectToString(arg) === '[object Array]';
}
exports.isArray = isArray;
function isBoolean(arg) {
return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;
function isNull(arg) {
return arg === null;
}
exports.isNull = isNull;
function isNullOrUndefined(arg) {
return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;
function isNumber(arg) {
return typeof arg === 'number';
}
exports.isNumber = isNumber;
function isString(arg) {
return typeof arg === 'string';
}
exports.isString = isString;
function isSymbol(arg) {
return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;
function isUndefined(arg) {
return arg === void 0;
}
exports.isUndefined = isUndefined;
function isRegExp(re) {
return objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;
function isDate(d) {
return objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
function isError(e) {
return (objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;
function isFunction(arg) {
return typeof arg === 'function';
}
exports.isFunction = isFunction;
function isPrimitive(arg) {
return arg === null ||
typeof arg === 'boolean' ||
typeof arg === 'number' ||
typeof arg === 'string' ||
typeof arg === 'symbol' || // ES6 symbol
typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;
exports.isBuffer = Buffer.isBuffer;
function objectToString(o) {
return Object.prototype.toString.call(o);
}
}).call(this)}).call(this,{"isBuffer":require("../../is-buffer/index.js")})
},{"../../is-buffer/index.js":520}],516:[function(require,module,exports){
(function (process){(function (){
/**
* This is the web browser implementation of `debug()`.
*
* Expose `debug()` as the module.
*/
exports = module.exports = require('./debug');
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.storage = 'undefined' != typeof chrome
&& 'undefined' != typeof chrome.storage
? chrome.storage.local
: localstorage();
/**
* Colors.
*/
exports.colors = [
'lightseagreen',
'forestgreen',
'goldenrod',
'dodgerblue',
'darkorchid',
'crimson'
];
/**
* Currently only WebKit-based Web Inspectors, Firefox >= v31,
* and the Firebug extension (any Firefox version) are known
* to support "%c" CSS customizations.
*
* TODO: add a `localStorage` variable to explicitly enable/disable colors
*/
function useColors() {
// NB: In an Electron preload script, document will be defined but not fully
// initialized. Since we know we're in Chrome, we'll just detect this case
// explicitly
if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') {
return true;
}
// is webkit? http://stackoverflow.com/a/16459606/376773
// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
// is firebug? http://stackoverflow.com/a/398120/376773
(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
// is firefox >= v31?
// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
// double check webkit in userAgent just in case we are in a worker
(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
}
/**
* Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
*/
exports.formatters.j = function(v) {
try {
return JSON.stringify(v);
} catch (err) {
return '[UnexpectedJSONParseError]: ' + err.message;
}
};
/**
* Colorize log arguments if enabled.
*
* @api public
*/
function formatArgs(args) {
var useColors = this.useColors;
args[0] = (useColors ? '%c' : '')
+ this.namespace
+ (useColors ? ' %c' : ' ')
+ args[0]
+ (useColors ? '%c ' : ' ')
+ '+' + exports.humanize(this.diff);
if (!useColors) return;
var c = 'color: ' + this.color;
args.splice(1, 0, c, 'color: inherit')
// the final "%c" is somewhat tricky, because there could be other
// arguments passed either before or after the %c, so we need to
// figure out the correct index to insert the CSS into
var index = 0;
var lastC = 0;
args[0].replace(/%[a-zA-Z%]/g, function(match) {
if ('%%' === match) return;
index++;
if ('%c' === match) {
// we only are interested in the *last* %c
// (the user may have provided their own)
lastC = index;
}
});
args.splice(lastC, 0, c);
}
/**
* Invokes `console.log()` when available.
* No-op when `console.log` is not a "function".
*
* @api public
*/
function log() {
// this hackery is required for IE8/9, where
// the `console.log` function doesn't have 'apply'
return 'object' === typeof console
&& console.log
&& Function.prototype.apply.call(console.log, console, arguments);
}
/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
try {
if (null == namespaces) {
exports.storage.removeItem('debug');
} else {
exports.storage.debug = namespaces;
}
} catch(e) {}
}
/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/
function load() {
var r;
try {
r = exports.storage.debug;
} catch(e) {}
// If debug isn't set in LS, and we're in Electron, try to load $DEBUG
if (!r && typeof process !== 'undefined' && 'env' in process) {
r = process.env.DEBUG;
}
return r;
}
/**
* Enable namespaces listed in `localStorage.debug` initially.
*/
exports.enable(load());
/**
* Localstorage attempts to return the localstorage.
*
* This is necessary because safari throws
* when a user disables cookies/localstorage
* and you attempt to access it.
*
* @return {LocalStorage}
* @api private
*/
function localstorage() {
try {
return window.localStorage;
} catch (e) {}
}
}).call(this)}).call(this,require('_process'))
},{"./debug":517,"_process":524}],517:[function(require,module,exports){
/**
* This is the common logic for both the Node.js and web browser
* implementations of `debug()`.
*
* Expose `debug()` as the module.
*/
exports = module.exports = createDebug.debug = createDebug['default'] = createDebug;
exports.coerce = coerce;
exports.disable = disable;
exports.enable = enable;
exports.enabled = enabled;
exports.humanize = require('ms');
/**
* The currently active debug mode names, and names to skip.
*/
exports.names = [];
exports.skips = [];
/**
* Map of special "%n" handling functions, for the debug "format" argument.
*
* Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
*/
exports.formatters = {};
/**
* Previous log timestamp.
*/
var prevTime;
/**
* Select a color.
* @param {String} namespace
* @return {Number}
* @api private
*/
function selectColor(namespace) {
var hash = 0, i;
for (i in namespace) {
hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
hash |= 0; // Convert to 32bit integer
}
return exports.colors[Math.abs(hash) % exports.colors.length];
}
/**
* Create a debugger with the given `namespace`.
*
* @param {String} namespace
* @return {Function}
* @api public
*/
function createDebug(namespace) {
function debug() {
// disabled?
if (!debug.enabled) return;
var self = debug;
// set `diff` timestamp
var curr = +new Date();
var ms = curr - (prevTime || curr);
self.diff = ms;
self.prev = prevTime;
self.curr = curr;
prevTime = curr;
// turn the `arguments` into a proper Array
var args = new Array(arguments.length);
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i];
}
args[0] = exports.coerce(args[0]);
if ('string' !== typeof args[0]) {
// anything else let's inspect with %O
args.unshift('%O');
}
// apply any `formatters` transformations
var index = 0;
args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) {
// if we encounter an escaped % then don't increase the array index
if (match === '%%') return match;
index++;
var formatter = exports.formatters[format];
if ('function' === typeof formatter) {
var val = args[index];
match = formatter.call(self, val);
// now we need to remove `args[index]` since it's inlined in the `format`
args.splice(index, 1);
index--;
}
return match;
});
// apply env-specific formatting (colors, etc.)
exports.formatArgs.call(self, args);
var logFn = debug.log || exports.log || console.log.bind(console);
logFn.apply(self, args);
}
debug.namespace = namespace;
debug.enabled = exports.enabled(namespace);
debug.useColors = exports.useColors();
debug.color = selectColor(namespace);
// env-specific initialization logic for debug instances
if ('function' === typeof exports.init) {
exports.init(debug);
}
return debug;
}
/**
* Enables a debug mode by namespaces. This can include modes
* separated by a colon and wildcards.
*
* @param {String} namespaces
* @api public
*/
function enable(namespaces) {
exports.save(namespaces);
exports.names = [];
exports.skips = [];
var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
var len = split.length;
for (var i = 0; i < len; i++) {
if (!split[i]) continue; // ignore empty strings
namespaces = split[i].replace(/\*/g, '.*?');
if (namespaces[0] === '-') {
exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
} else {
exports.names.push(new RegExp('^' + namespaces + '$'));
}
}
}
/**
* Disable debug output.
*
* @api public
*/
function disable() {
exports.enable('');
}
/**
* Returns true if the given mode name is enabled, false otherwise.
*
* @param {String} name
* @return {Boolean}
* @api public
*/
function enabled(name) {
var i, len;
for (i = 0, len = exports.skips.length; i < len; i++) {
if (exports.skips[i].test(name)) {
return false;
}
}
for (i = 0, len = exports.names.length; i < len; i++) {
if (exports.names[i].test(name)) {
return true;
}
}
return false;
}
/**
* Coerce `val`.
*
* @param {Mixed} val
* @return {Mixed}
* @api private
*/
function coerce(val) {
if (val instanceof Error) return val.stack || val.message;
return val;
}
},{"ms":522}],518:[function(require,module,exports){
/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
exports.read = function (buffer, offset, isLE, mLen, nBytes) {
var e, m
var eLen = (nBytes * 8) - mLen - 1
var eMax = (1 << eLen) - 1
var eBias = eMax >> 1
var nBits = -7
var i = isLE ? (nBytes - 1) : 0
var d = isLE ? -1 : 1
var s = buffer[offset + i]
i += d
e = s & ((1 << (-nBits)) - 1)
s >>= (-nBits)
nBits += eLen
for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
m = e & ((1 << (-nBits)) - 1)
e >>= (-nBits)
nBits += mLen
for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
if (e === 0) {
e = 1 - eBias
} else if (e === eMax) {
return m ? NaN : ((s ? -1 : 1) * Infinity)
} else {
m = m + Math.pow(2, mLen)
e = e - eBias
}
return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
}
exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
var e, m, c
var eLen = (nBytes * 8) - mLen - 1
var eMax = (1 << eLen) - 1
var eBias = eMax >> 1
var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
var i = isLE ? 0 : (nBytes - 1)
var d = isLE ? 1 : -1
var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
value = Math.abs(value)
if (isNaN(value) || value === Infinity) {
m = isNaN(value) ? 1 : 0
e = eMax
} else {
e = Math.floor(Math.log(value) / Math.LN2)
if (value * (c = Math.pow(2, -e)) < 1) {
e--
c *= 2
}
if (e + eBias >= 1) {
value += rt / c
} else {
value += rt * Math.pow(2, 1 - eBias)
}
if (value * c >= 2) {
e++
c /= 2
}
if (e + eBias >= eMax) {
m = 0
e = eMax
} else if (e + eBias >= 1) {
m = ((value * c) - 1) * Math.pow(2, mLen)
e = e + eBias
} else {
m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
e = 0
}
}
for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
e = (e << mLen) | m
eLen += mLen
for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
buffer[offset + i - d] |= s * 128
}
},{}],519:[function(require,module,exports){
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
if (superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
})
}
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
if (superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
}
},{}],520:[function(require,module,exports){
/*!
* Determine if an object is a Buffer
*
* @author Feross Aboukhadijeh <https://feross.org>
* @license MIT
*/
// The _isBuffer check is for Safari 5-7 support, because it's missing
// Object.prototype.constructor. Remove this eventually
module.exports = function (obj) {
return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
}
function isBuffer (obj) {
return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
}
// For Node v0.10 support. Remove this eventually.
function isSlowBuffer (obj) {
return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
}
},{}],521:[function(require,module,exports){
var toString = {}.toString;
module.exports = Array.isArray || function (arr) {
return toString.call(arr) == '[object Array]';
};
},{}],522:[function(require,module,exports){
/**
* Helpers.
*/
var s = 1000;
var m = s * 60;
var h = m * 60;
var d = h * 24;
var y = d * 365.25;
/**
* Parse or format the given `val`.
*
* Options:
*
* - `long` verbose formatting [false]
*
* @param {String|Number} val
* @param {Object} [options]
* @throws {Error} throw an error if val is not a non-empty string or a number
* @return {String|Number}
* @api public
*/
module.exports = function(val, options) {
options = options || {};
var type = typeof val;
if (type === 'string' && val.length > 0) {
return parse(val);
} else if (type === 'number' && isNaN(val) === false) {
return options.long ? fmtLong(val) : fmtShort(val);
}
throw new Error(
'val is not a non-empty string or a valid number. val=' +
JSON.stringify(val)
);
};
/**
* Parse the given `str` and return milliseconds.
*
* @param {String} str
* @return {Number}
* @api private
*/
function parse(str) {
str = String(str);
if (str.length > 100) {
return;
}
var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(
str
);
if (!match) {
return;
}
var n = parseFloat(match[1]);
var type = (match[2] || 'ms').toLowerCase();
switch (type) {
case 'years':
case 'year':
case 'yrs':
case 'yr':
case 'y':
return n * y;
case 'days':
case 'day':
case 'd':
return n * d;
case 'hours':
case 'hour':
case 'hrs':
case 'hr':
case 'h':
return n * h;
case 'minutes':
case 'minute':
case 'mins':
case 'min':
case 'm':
return n * m;
case 'seconds':
case 'second':
case 'secs':
case 'sec':
case 's':
return n * s;
case 'milliseconds':
case 'millisecond':
case 'msecs':
case 'msec':
case 'ms':
return n;
default:
return undefined;
}
}
/**
* Short format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtShort(ms) {
if (ms >= d) {
return Math.round(ms / d) + 'd';
}
if (ms >= h) {
return Math.round(ms / h) + 'h';
}
if (ms >= m) {
return Math.round(ms / m) + 'm';
}
if (ms >= s) {
return Math.round(ms / s) + 's';
}
return ms + 'ms';
}
/**
* Long format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtLong(ms) {
return plural(ms, d, 'day') ||
plural(ms, h, 'hour') ||
plural(ms, m, 'minute') ||
plural(ms, s, 'second') ||
ms + ' ms';
}
/**
* Pluralization helper.
*/
function plural(ms, n, name) {
if (ms < n) {
return;
}
if (ms < n * 1.5) {
return Math.floor(ms / n) + ' ' + name;
}
return Math.ceil(ms / n) + ' ' + name + 's';
}
},{}],523:[function(require,module,exports){
(function (process){(function (){
'use strict';
if (typeof process === 'undefined' ||
!process.version ||
process.version.indexOf('v0.') === 0 ||
process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
module.exports = { nextTick: nextTick };
} else {
module.exports = process
}
function nextTick(fn, arg1, arg2, arg3) {
if (typeof fn !== 'function') {
throw new TypeError('"callback" argument must be a function');
}
var len = arguments.length;
var args, i;
switch (len) {
case 0:
case 1:
return process.nextTick(fn);
case 2:
return process.nextTick(function afterTickOne() {
fn.call(null, arg1);
});
case 3:
return process.nextTick(function afterTickTwo() {
fn.call(null, arg1, arg2);
});
case 4:
return process.nextTick(function afterTickThree() {
fn.call(null, arg1, arg2, arg3);
});
default:
args = new Array(len - 1);
i = 0;
while (i < args.length) {
args[i++] = arguments[i];
}
return process.nextTick(function afterTick() {
fn.apply(null, args);
});
}
}
}).call(this)}).call(this,require('_process'))
},{"_process":524}],524:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
function defaultSetTimout() {
throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
throw new Error('clearTimeout has not been defined');
}
(function () {
try {
if (typeof setTimeout === 'function') {
cachedSetTimeout = setTimeout;
} else {
cachedSetTimeout = defaultSetTimout;
}
} catch (e) {
cachedSetTimeout = defaultSetTimout;
}
try {
if (typeof clearTimeout === 'function') {
cachedClearTimeout = clearTimeout;
} else {
cachedClearTimeout = defaultClearTimeout;
}
} catch (e) {
cachedClearTimeout = defaultClearTimeout;
}
} ())
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
}
// if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch(e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch(e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
}
// if clearTimeout wasn't available but was latter defined
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
runTimeout(drainQueue);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.prependListener = noop;
process.prependOnceListener = noop;
process.listeners = function (name) { return [] }
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
},{}],525:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
// a duplex stream is just a stream that is both readable and writable.
// Since JS doesn't have multiple prototypal inheritance, this class
// prototypally inherits from Readable, and then parasitically from
// Writable.
'use strict';
/*<replacement>*/
var pna = require('process-nextick-args');
/*</replacement>*/
/*<replacement>*/
var objectKeys = Object.keys || function (obj) {
var keys = [];
for (var key in obj) {
keys.push(key);
}return keys;
};
/*</replacement>*/
module.exports = Duplex;
/*<replacement>*/
var util = Object.create(require('core-util-is'));
util.inherits = require('inherits');
/*</replacement>*/
var Readable = require('./_stream_readable');
var Writable = require('./_stream_writable');
util.inherits(Duplex, Readable);
{
// avoid scope creep, the keys array can then be collected
var keys = objectKeys(Writable.prototype);
for (var v = 0; v < keys.length; v++) {
var method = keys[v];
if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
}
}
function Duplex(options) {
if (!(this instanceof Duplex)) return new Duplex(options);
Readable.call(this, options);
Writable.call(this, options);
if (options && options.readable === false) this.readable = false;
if (options && options.writable === false) this.writable = false;
this.allowHalfOpen = true;
if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
this.once('end', onend);
}
Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
// making it explicit this property is not enumerable
// because otherwise some prototype manipulation in
// userland will fail
enumerable: false,
get: function () {
return this._writableState.highWaterMark;
}
});
// the no-half-open enforcer
function onend() {
// if we allow half-open state, or if the writable side ended,
// then we're ok.
if (this.allowHalfOpen || this._writableState.ended) return;
// no more data can be written.
// But allow more writes to happen in this tick.
pna.nextTick(onEndNT, this);
}
function onEndNT(self) {
self.end();
}
Object.defineProperty(Duplex.prototype, 'destroyed', {
get: function () {
if (this._readableState === undefined || this._writableState === undefined) {
return false;
}
return this._readableState.destroyed && this._writableState.destroyed;
},
set: function (value) {
// we ignore the value if the stream
// has not been initialized yet
if (this._readableState === undefined || this._writableState === undefined) {
return;
}
// backward compatibility, the user is explicitly
// managing destroyed
this._readableState.destroyed = value;
this._writableState.destroyed = value;
}
});
Duplex.prototype._destroy = function (err, cb) {
this.push(null);
this.end();
pna.nextTick(cb, err);
};
},{"./_stream_readable":527,"./_stream_writable":529,"core-util-is":515,"inherits":519,"process-nextick-args":523}],526:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
// a passthrough stream.
// basically just the most minimal sort of Transform stream.
// Every written chunk gets output as-is.
'use strict';
module.exports = PassThrough;
var Transform = require('./_stream_transform');
/*<replacement>*/
var util = Object.create(require('core-util-is'));
util.inherits = require('inherits');
/*</replacement>*/
util.inherits(PassThrough, Transform);
function PassThrough(options) {
if (!(this instanceof PassThrough)) return new PassThrough(options);
Transform.call(this, options);
}
PassThrough.prototype._transform = function (chunk, encoding, cb) {
cb(null, chunk);
};
},{"./_stream_transform":528,"core-util-is":515,"inherits":519}],527:[function(require,module,exports){
(function (process,global){(function (){
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
'use strict';
/*<replacement>*/
var pna = require('process-nextick-args');
/*</replacement>*/
module.exports = Readable;
/*<replacement>*/
var isArray = require('isarray');
/*</replacement>*/
/*<replacement>*/
var Duplex;
/*</replacement>*/
Readable.ReadableState = ReadableState;
/*<replacement>*/
var EE = require('events').EventEmitter;
var EElistenerCount = function (emitter, type) {
return emitter.listeners(type).length;
};
/*</replacement>*/
/*<replacement>*/
var Stream = require('./internal/streams/stream');
/*</replacement>*/
/*<replacement>*/
var Buffer = require('safe-buffer').Buffer;
var OurUint8Array = global.Uint8Array || function () {};
function _uint8ArrayToBuffer(chunk) {
return Buffer.from(chunk);
}
function _isUint8Array(obj) {
return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
}
/*</replacement>*/
/*<replacement>*/
var util = Object.create(require('core-util-is'));
util.inherits = require('inherits');
/*</replacement>*/
/*<replacement>*/
var debugUtil = require('util');
var debug = void 0;
if (debugUtil && debugUtil.debuglog) {
debug = debugUtil.debuglog('stream');
} else {
debug = function () {};
}
/*</replacement>*/
var BufferList = require('./internal/streams/BufferList');
var destroyImpl = require('./internal/streams/destroy');
var StringDecoder;
util.inherits(Readable, Stream);
var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
function prependListener(emitter, event, fn) {
// Sadly this is not cacheable as some libraries bundle their own
// event emitter implementation with them.
if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);
// This is a hack to make sure that our error handler is attached before any
// userland ones. NEVER DO THIS. This is here only because this code needs
// to continue to work with older versions of Node.js that do not include
// the prependListener() method. The goal is to eventually remove this hack.
if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
}
function ReadableState(options, stream) {
Duplex = Duplex || require('./_stream_duplex');
options = options || {};
// Duplex streams are both readable and writable, but share
// the same options object.
// However, some cases require setting options to different
// values for the readable and the writable sides of the duplex stream.
// These options can be provided separately as readableXXX and writableXXX.
var isDuplex = stream instanceof Duplex;
// object stream flag. Used to make read(n) ignore n and to
// make all the buffer merging and length checks go away
this.objectMode = !!options.objectMode;
if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
// the point at which it stops calling _read() to fill the buffer
// Note: 0 is a valid value, means "don't call _read preemptively ever"
var hwm = options.highWaterMark;
var readableHwm = options.readableHighWaterMark;
var defaultHwm = this.objectMode ? 16 : 16 * 1024;
if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm;
// cast to ints.
this.highWaterMark = Math.floor(this.highWaterMark);
// A linked list is used to store data chunks instead of an array because the
// linked list can remove elements from the beginning faster than
// array.shift()
this.buffer = new BufferList();
this.length = 0;
this.pipes = null;
this.pipesCount = 0;
this.flowing = null;
this.ended = false;
this.endEmitted = false;
this.reading = false;
// a flag to be able to tell if the event 'readable'/'data' is emitted
// immediately, or on a later tick. We set this to true at first, because
// any actions that shouldn't happen until "later" should generally also
// not happen before the first read call.
this.sync = true;
// whenever we return null, then we set a flag to say
// that we're awaiting a 'readable' event emission.
this.needReadable = false;
this.emittedReadable = false;
this.readableListening = false;
this.resumeScheduled = false;
// has it been destroyed
this.destroyed = false;
// Crypto is kind of old and crusty. Historically, its default string
// encoding is 'binary' so we have to make this configurable.
// Everything else in the universe uses 'utf8', though.
this.defaultEncoding = options.defaultEncoding || 'utf8';
// the number of writers that are awaiting a drain event in .pipe()s
this.awaitDrain = 0;
// if true, a maybeReadMore has been scheduled
this.readingMore = false;
this.decoder = null;
this.encoding = null;
if (options.encoding) {
if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
this.decoder = new StringDecoder(options.encoding);
this.encoding = options.encoding;
}
}
function Readable(options) {
Duplex = Duplex || require('./_stream_duplex');
if (!(this instanceof Readable)) return new Readable(options);
this._readableState = new ReadableState(options, this);
// legacy
this.readable = true;
if (options) {
if (typeof options.read === 'function') this._read = options.read;
if (typeof options.destroy === 'function') this._destroy = options.destroy;
}
Stream.call(this);
}
Object.defineProperty(Readable.prototype, 'destroyed', {
get: function () {
if (this._readableState === undefined) {
return false;
}
return this._readableState.destroyed;
},
set: function (value) {
// we ignore the value if the stream
// has not been initialized yet
if (!this._readableState) {
return;
}
// backward compatibility, the user is explicitly
// managing destroyed
this._readableState.destroyed = value;
}
});
Readable.prototype.destroy = destroyImpl.destroy;
Readable.prototype._undestroy = destroyImpl.undestroy;
Readable.prototype._destroy = function (err, cb) {
this.push(null);
cb(err);
};
// Manually shove something into the read() buffer.
// This returns true if the highWaterMark has not been hit yet,
// similar to how Writable.write() returns true if you should
// write() some more.
Readable.prototype.push = function (chunk, encoding) {
var state = this._readableState;
var skipChunkCheck;
if (!state.objectMode) {
if (typeof chunk === 'string') {
encoding = encoding || state.defaultEncoding;
if (encoding !== state.encoding) {
chunk = Buffer.from(chunk, encoding);
encoding = '';
}
skipChunkCheck = true;
}
} else {
skipChunkCheck = true;
}
return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
};
// Unshift should *always* be something directly out of read()
Readable.prototype.unshift = function (chunk) {
return readableAddChunk(this, chunk, null, true, false);
};
function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
var state = stream._readableState;
if (chunk === null) {
state.reading = false;
onEofChunk(stream, state);
} else {
var er;
if (!skipChunkCheck) er = chunkInvalid(state, chunk);
if (er) {
stream.emit('error', er);
} else if (state.objectMode || chunk && chunk.length > 0) {
if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
chunk = _uint8ArrayToBuffer(chunk);
}
if (addToFront) {
if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);
} else if (state.ended) {
stream.emit('error', new Error('stream.push() after EOF'));
} else {
state.reading = false;
if (state.decoder && !encoding) {
chunk = state.decoder.write(chunk);
if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
} else {
addChunk(stream, state, chunk, false);
}
}
} else if (!addToFront) {
state.reading = false;
}
}
return needMoreData(state);
}
function addChunk(stream, state, chunk, addToFront) {
if (state.flowing && state.length === 0 && !state.sync) {
stream.emit('data', chunk);
stream.read(0);
} else {
// update the buffer info.
state.length += state.objectMode ? 1 : chunk.length;
if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
if (state.needReadable) emitReadable(stream);
}
maybeReadMore(stream, state);
}
function chunkInvalid(state, chunk) {
var er;
if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
er = new TypeError('Invalid non-string/buffer chunk');
}
return er;
}
// if it's past the high water mark, we can push in some more.
// Also, if we have no data yet, we can stand some
// more bytes. This is to work around cases where hwm=0,
// such as the repl. Also, if the push() triggered a
// readable event, and the user called read(largeNumber) such that
// needReadable was set, then we ought to push more, so that another
// 'readable' event will be triggered.
function needMoreData(state) {
return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
}
Readable.prototype.isPaused = function () {
return this._readableState.flowing === false;
};
// backwards compatibility.
Readable.prototype.setEncoding = function (enc) {
if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
this._readableState.decoder = new StringDecoder(enc);
this._readableState.encoding = enc;
return this;
};
// Don't raise the hwm > 8MB
var MAX_HWM = 0x800000;
function computeNewHighWaterMark(n) {
if (n >= MAX_HWM) {
n = MAX_HWM;
} else {
// Get the next highest power of 2 to prevent increasing hwm excessively in
// tiny amounts
n--;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
n++;
}
return n;
}
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function howMuchToRead(n, state) {
if (n <= 0 || state.length === 0 && state.ended) return 0;
if (state.objectMode) return 1;
if (n !== n) {
// Only flow one buffer at a time
if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
}
// If we're asking for more than the current hwm, then raise the hwm.
if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
if (n <= state.length) return n;
// Don't have enough
if (!state.ended) {
state.needReadable = true;
return 0;
}
return state.length;
}
// you can override either this method, or the async _read(n) below.
Readable.prototype.read = function (n) {
debug('read', n);
n = parseInt(n, 10);
var state = this._readableState;
var nOrig = n;
if (n !== 0) state.emittedReadable = false;
// if we're doing read(0) to trigger a readable event, but we
// already have a bunch of data in the buffer, then just trigger
// the 'readable' event and move on.
if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
debug('read: emitReadable', state.length, state.ended);
if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
return null;
}
n = howMuchToRead(n, state);
// if we've ended, and we're now clear, then finish it up.
if (n === 0 && state.ended) {
if (state.length === 0) endReadable(this);
return null;
}
// All the actual chunk generation logic needs to be
// *below* the call to _read. The reason is that in certain
// synthetic stream cases, such as passthrough streams, _read
// may be a completely synchronous operation which may change
// the state of the read buffer, providing enough data when
// before there was *not* enough.
//
// So, the steps are:
// 1. Figure out what the state of things will be after we do
// a read from the buffer.
//
// 2. If that resulting state will trigger a _read, then call _read.
// Note that this may be asynchronous, or synchronous. Yes, it is
// deeply ugly to write APIs this way, but that still doesn't mean
// that the Readable class should behave improperly, as streams are
// designed to be sync/async agnostic.
// Take note if the _read call is sync or async (ie, if the read call
// has returned yet), so that we know whether or not it's safe to emit
// 'readable' etc.
//
// 3. Actually pull the requested chunks out of the buffer and return.
// if we need a readable event, then we need to do some reading.
var doRead = state.needReadable;
debug('need readable', doRead);
// if we currently have less than the highWaterMark, then also read some
if (state.length === 0 || state.length - n < state.highWaterMark) {
doRead = true;
debug('length less than watermark', doRead);
}
// however, if we've ended, then there's no point, and if we're already
// reading, then it's unnecessary.
if (state.ended || state.reading) {
doRead = false;
debug('reading or ended', doRead);
} else if (doRead) {
debug('do read');
state.reading = true;
state.sync = true;
// if the length is currently zero, then we *need* a readable event.
if (state.length === 0) state.needReadable = true;
// call internal read method
this._read(state.highWaterMark);
state.sync = false;
// If _read pushed data synchronously, then `reading` will be false,
// and we need to re-evaluate how much data we can return to the user.
if (!state.reading) n = howMuchToRead(nOrig, state);
}
var ret;
if (n > 0) ret = fromList(n, state);else ret = null;
if (ret === null) {
state.needReadable = true;
n = 0;
} else {
state.length -= n;
}
if (state.length === 0) {
// If we have nothing in the buffer, then we want to know
// as soon as we *do* get something into the buffer.
if (!state.ended) state.needReadable = true;
// If we tried to read() past the EOF, then emit end on the next tick.
if (nOrig !== n && state.ended) endReadable(this);
}
if (ret !== null) this.emit('data', ret);
return ret;
};
function onEofChunk(stream, state) {
if (state.ended) return;
if (state.decoder) {
var chunk = state.decoder.end();
if (chunk && chunk.length) {
state.buffer.push(chunk);
state.length += state.objectMode ? 1 : chunk.length;
}
}
state.ended = true;
// emit 'readable' now to make sure it gets picked up.
emitReadable(stream);
}
// Don't emit readable right away in sync mode, because this can trigger
// another read() call => stack overflow. This way, it might trigger
// a nextTick recursion warning, but that's not so bad.
function emitReadable(stream) {
var state = stream._readableState;
state.needReadable = false;
if (!state.emittedReadable) {
debug('emitReadable', state.flowing);
state.emittedReadable = true;
if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream);
}
}
function emitReadable_(stream) {
debug('emit readable');
stream.emit('readable');
flow(stream);
}
// at this point, the user has presumably seen the 'readable' event,
// and called read() to consume some data. that may have triggered
// in turn another _read(n) call, in which case reading = true if
// it's in progress.
// However, if we're not ended, or reading, and the length < hwm,
// then go ahead and try to read some more preemptively.
function maybeReadMore(stream, state) {
if (!state.readingMore) {
state.readingMore = true;
pna.nextTick(maybeReadMore_, stream, state);
}
}
function maybeReadMore_(stream, state) {
var len = state.length;
while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
debug('maybeReadMore read 0');
stream.read(0);
if (len === state.length)
// didn't get any data, stop spinning.
break;else len = state.length;
}
state.readingMore = false;
}
// abstract method. to be overridden in specific implementation classes.
// call cb(er, data) where data is <= n in length.
// for virtual (non-string, non-buffer) streams, "length" is somewhat
// arbitrary, and perhaps not very meaningful.
Readable.prototype._read = function (n) {
this.emit('error', new Error('_read() is not implemented'));
};
Readable.prototype.pipe = function (dest, pipeOpts) {
var src = this;
var state = this._readableState;
switch (state.pipesCount) {
case 0:
state.pipes = dest;
break;
case 1:
state.pipes = [state.pipes, dest];
break;
default:
state.pipes.push(dest);
break;
}
state.pipesCount += 1;
debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
var endFn = doEnd ? onend : unpipe;
if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn);
dest.on('unpipe', onunpipe);
function onunpipe(readable, unpipeInfo) {
debug('onunpipe');
if (readable === src) {
if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
unpipeInfo.hasUnpiped = true;
cleanup();
}
}
}
function onend() {
debug('onend');
dest.end();
}
// when the dest drains, it reduces the awaitDrain counter
// on the source. This would be more elegant with a .once()
// handler in flow(), but adding and removing repeatedly is
// too slow.
var ondrain = pipeOnDrain(src);
dest.on('drain', ondrain);
var cleanedUp = false;
function cleanup() {
debug('cleanup');
// cleanup event handlers once the pipe is broken
dest.removeListener('close', onclose);
dest.removeListener('finish', onfinish);
dest.removeListener('drain', ondrain);
dest.removeListener('error', onerror);
dest.removeListener('unpipe', onunpipe);
src.removeListener('end', onend);
src.removeListener('end', unpipe);
src.removeListener('data', ondata);
cleanedUp = true;
// if the reader is waiting for a drain event from this
// specific writer, then it would cause it to never start
// flowing again.
// So, if this is awaiting a drain, then we just call it now.
// If we don't know, then assume that we are waiting for one.
if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
}
// If the user pushes more data while we're writing to dest then we'll end up
// in ondata again. However, we only want to increase awaitDrain once because
// dest will only emit one 'drain' event for the multiple writes.
// => Introduce a guard on increasing awaitDrain.
var increasedAwaitDrain = false;
src.on('data', ondata);
function ondata(chunk) {
debug('ondata');
increasedAwaitDrain = false;
var ret = dest.write(chunk);
if (false === ret && !increasedAwaitDrain) {
// If the user unpiped during `dest.write()`, it is possible
// to get stuck in a permanently paused state if that write
// also returned false.
// => Check whether `dest` is still a piping destination.
if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
debug('false write response, pause', src._readableState.awaitDrain);
src._readableState.awaitDrain++;
increasedAwaitDrain = true;
}
src.pause();
}
}
// if the dest has an error, then stop piping into it.
// however, don't suppress the throwing behavior for this.
function onerror(er) {
debug('onerror', er);
unpipe();
dest.removeListener('error', onerror);
if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
}
// Make sure our error handler is attached before userland ones.
prependListener(dest, 'error', onerror);
// Both close and finish should trigger unpipe, but only once.
function onclose() {
dest.removeListener('finish', onfinish);
unpipe();
}
dest.once('close', onclose);
function onfinish() {
debug('onfinish');
dest.removeListener('close', onclose);
unpipe();
}
dest.once('finish', onfinish);
function unpipe() {
debug('unpipe');
src.unpipe(dest);
}
// tell the dest that it's being piped to
dest.emit('pipe', src);
// start the flow if it hasn't been started already.
if (!state.flowing) {
debug('pipe resume');
src.resume();
}
return dest;
};
function pipeOnDrain(src) {
return function () {
var state = src._readableState;
debug('pipeOnDrain', state.awaitDrain);
if (state.awaitDrain) state.awaitDrain--;
if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
state.flowing = true;
flow(src);
}
};
}
Readable.prototype.unpipe = function (dest) {
var state = this._readableState;
var unpipeInfo = { hasUnpiped: false };
// if we're not piping anywhere, then do nothing.
if (state.pipesCount === 0) return this;
// just one destination. most common case.
if (state.pipesCount === 1) {
// passed in one, but it's not the right one.
if (dest && dest !== state.pipes) return this;
if (!dest) dest = state.pipes;
// got a match.
state.pipes = null;
state.pipesCount = 0;
state.flowing = false;
if (dest) dest.emit('unpipe', this, unpipeInfo);
return this;
}
// slow case. multiple pipe destinations.
if (!dest) {
// remove all.
var dests = state.pipes;
var len = state.pipesCount;
state.pipes = null;
state.pipesCount = 0;
state.flowing = false;
for (var i = 0; i < len; i++) {
dests[i].emit('unpipe', this, unpipeInfo);
}return this;
}
// try to find the right one.
var index = indexOf(state.pipes, dest);
if (index === -1) return this;
state.pipes.splice(index, 1);
state.pipesCount -= 1;
if (state.pipesCount === 1) state.pipes = state.pipes[0];
dest.emit('unpipe', this, unpipeInfo);
return this;
};
// set up data events if they are asked for
// Ensure readable listeners eventually get something
Readable.prototype.on = function (ev, fn) {
var res = Stream.prototype.on.call(this, ev, fn);
if (ev === 'data') {
// Start flowing on next tick if stream isn't explicitly paused
if (this._readableState.flowing !== false) this.resume();
} else if (ev === 'readable') {
var state = this._readableState;
if (!state.endEmitted && !state.readableListening) {
state.readableListening = state.needReadable = true;
state.emittedReadable = false;
if (!state.reading) {
pna.nextTick(nReadingNextTick, this);
} else if (state.length) {
emitReadable(this);
}
}
}
return res;
};
Readable.prototype.addListener = Readable.prototype.on;
function nReadingNextTick(self) {
debug('readable nexttick read 0');
self.read(0);
}
// pause() and resume() are remnants of the legacy readable stream API
// If the user uses them, then switch into old mode.
Readable.prototype.resume = function () {
var state = this._readableState;
if (!state.flowing) {
debug('resume');
state.flowing = true;
resume(this, state);
}
return this;
};
function resume(stream, state) {
if (!state.resumeScheduled) {
state.resumeScheduled = true;
pna.nextTick(resume_, stream, state);
}
}
function resume_(stream, state) {
if (!state.reading) {
debug('resume read 0');
stream.read(0);
}
state.resumeScheduled = false;
state.awaitDrain = 0;
stream.emit('resume');
flow(stream);
if (state.flowing && !state.reading) stream.read(0);
}
Readable.prototype.pause = function () {
debug('call pause flowing=%j', this._readableState.flowing);
if (false !== this._readableState.flowing) {
debug('pause');
this._readableState.flowing = false;
this.emit('pause');
}
return this;
};
function flow(stream) {
var state = stream._readableState;
debug('flow', state.flowing);
while (state.flowing && stream.read() !== null) {}
}
// wrap an old-style stream as the async data source.
// This is *not* part of the readable stream interface.
// It is an ugly unfortunate mess of history.
Readable.prototype.wrap = function (stream) {
var _this = this;
var state = this._readableState;
var paused = false;
stream.on('end', function () {
debug('wrapped end');
if (state.decoder && !state.ended) {
var chunk = state.decoder.end();
if (chunk && chunk.length) _this.push(chunk);
}
_this.push(null);
});
stream.on('data', function (chunk) {
debug('wrapped data');
if (state.decoder) chunk = state.decoder.write(chunk);
// don't skip over falsy values in objectMode
if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
var ret = _this.push(chunk);
if (!ret) {
paused = true;
stream.pause();
}
});
// proxy all the other methods.
// important when wrapping filters and duplexes.
for (var i in stream) {
if (this[i] === undefined && typeof stream[i] === 'function') {
this[i] = function (method) {
return function () {
return stream[method].apply(stream, arguments);
};
}(i);
}
}
// proxy certain important events.
for (var n = 0; n < kProxyEvents.length; n++) {
stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
}
// when we try to consume some more bytes, simply unpause the
// underlying stream.
this._read = function (n) {
debug('wrapped _read', n);
if (paused) {
paused = false;
stream.resume();
}
};
return this;
};
Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
// making it explicit this property is not enumerable
// because otherwise some prototype manipulation in
// userland will fail
enumerable: false,
get: function () {
return this._readableState.highWaterMark;
}
});
// exposed for testing purposes only.
Readable._fromList = fromList;
// Pluck off n bytes from an array of buffers.
// Length is the combined lengths of all the buffers in the list.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function fromList(n, state) {
// nothing buffered
if (state.length === 0) return null;
var ret;
if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
// read it all, truncate the list
if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length);
state.buffer.clear();
} else {
// read part of list
ret = fromListPartial(n, state.buffer, state.decoder);
}
return ret;
}
// Extracts only enough buffered data to satisfy the amount requested.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function fromListPartial(n, list, hasStrings) {
var ret;
if (n < list.head.data.length) {
// slice is the same for buffers and strings
ret = list.head.data.slice(0, n);
list.head.data = list.head.data.slice(n);
} else if (n === list.head.data.length) {
// first chunk is a perfect match
ret = list.shift();
} else {
// result spans more than one buffer
ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
}
return ret;
}
// Copies a specified amount of characters from the list of buffered data
// chunks.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function copyFromBufferString(n, list) {
var p = list.head;
var c = 1;
var ret = p.data;
n -= ret.length;
while (p = p.next) {
var str = p.data;
var nb = n > str.length ? str.length : n;
if (nb === str.length) ret += str;else ret += str.slice(0, n);
n -= nb;
if (n === 0) {
if (nb === str.length) {
++c;
if (p.next) list.head = p.next;else list.head = list.tail = null;
} else {
list.head = p;
p.data = str.slice(nb);
}
break;
}
++c;
}
list.length -= c;
return ret;
}
// Copies a specified amount of bytes from the list of buffered data chunks.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function copyFromBuffer(n, list) {
var ret = Buffer.allocUnsafe(n);
var p = list.head;
var c = 1;
p.data.copy(ret);
n -= p.data.length;
while (p = p.next) {
var buf = p.data;
var nb = n > buf.length ? buf.length : n;
buf.copy(ret, ret.length - n, 0, nb);
n -= nb;
if (n === 0) {
if (nb === buf.length) {
++c;
if (p.next) list.head = p.next;else list.head = list.tail = null;
} else {
list.head = p;
p.data = buf.slice(nb);
}
break;
}
++c;
}
list.length -= c;
return ret;
}
function endReadable(stream) {
var state = stream._readableState;
// If we get here before consuming all the bytes, then that is a
// bug in node. Should never happen.
if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
if (!state.endEmitted) {
state.ended = true;
pna.nextTick(endReadableNT, state, stream);
}
}
function endReadableNT(state, stream) {
// Check that we didn't get one last unshift.
if (!state.endEmitted && state.length === 0) {
state.endEmitted = true;
stream.readable = false;
stream.emit('end');
}
}
function indexOf(xs, x) {
for (var i = 0, l = xs.length; i < l; i++) {
if (xs[i] === x) return i;
}
return -1;
}
}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./_stream_duplex":525,"./internal/streams/BufferList":530,"./internal/streams/destroy":531,"./internal/streams/stream":532,"_process":524,"core-util-is":515,"events":513,"inherits":519,"isarray":521,"process-nextick-args":523,"safe-buffer":534,"string_decoder/":535,"util":512}],528:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
// a transform stream is a readable/writable stream where you do
// something with the data. Sometimes it's called a "filter",
// but that's not a great name for it, since that implies a thing where
// some bits pass through, and others are simply ignored. (That would
// be a valid example of a transform, of course.)
//
// While the output is causally related to the input, it's not a
// necessarily symmetric or synchronous transformation. For example,
// a zlib stream might take multiple plain-text writes(), and then
// emit a single compressed chunk some time in the future.
//
// Here's how this works:
//
// The Transform stream has all the aspects of the readable and writable
// stream classes. When you write(chunk), that calls _write(chunk,cb)
// internally, and returns false if there's a lot of pending writes
// buffered up. When you call read(), that calls _read(n) until
// there's enough pending readable data buffered up.
//
// In a transform stream, the written data is placed in a buffer. When
// _read(n) is called, it transforms the queued up data, calling the
// buffered _write cb's as it consumes chunks. If consuming a single
// written chunk would result in multiple output chunks, then the first
// outputted bit calls the readcb, and subsequent chunks just go into
// the read buffer, and will cause it to emit 'readable' if necessary.
//
// This way, back-pressure is actually determined by the reading side,
// since _read has to be called to start processing a new chunk. However,
// a pathological inflate type of transform can cause excessive buffering
// here. For example, imagine a stream where every byte of input is
// interpreted as an integer from 0-255, and then results in that many
// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
// 1kb of data being output. In this case, you could write a very small
// amount of input, and end up with a very large amount of output. In
// such a pathological inflating mechanism, there'd be no way to tell
// the system to stop doing the transform. A single 4MB write could
// cause the system to run out of memory.
//
// However, even in such a pathological case, only a single written chunk
// would be consumed, and then the rest would wait (un-transformed) until
// the results of the previous transformed chunk were consumed.
'use strict';
module.exports = Transform;
var Duplex = require('./_stream_duplex');
/*<replacement>*/
var util = Object.create(require('core-util-is'));
util.inherits = require('inherits');
/*</replacement>*/
util.inherits(Transform, Duplex);
function afterTransform(er, data) {
var ts = this._transformState;
ts.transforming = false;
var cb = ts.writecb;
if (!cb) {
return this.emit('error', new Error('write callback called multiple times'));
}
ts.writechunk = null;
ts.writecb = null;
if (data != null) // single equals check for both `null` and `undefined`
this.push(data);
cb(er);
var rs = this._readableState;
rs.reading = false;
if (rs.needReadable || rs.length < rs.highWaterMark) {
this._read(rs.highWaterMark);
}
}
function Transform(options) {
if (!(this instanceof Transform)) return new Transform(options);
Duplex.call(this, options);
this._transformState = {
afterTransform: afterTransform.bind(this),
needTransform: false,
transforming: false,
writecb: null,
writechunk: null,
writeencoding: null
};
// start out asking for a readable event once data is transformed.
this._readableState.needReadable = true;
// we have implemented the _read method, and done the other things
// that Readable wants before the first _read call, so unset the
// sync guard flag.
this._readableState.sync = false;
if (options) {
if (typeof options.transform === 'function') this._transform = options.transform;
if (typeof options.flush === 'function') this._flush = options.flush;
}
// When the writable side finishes, then flush out anything remaining.
this.on('prefinish', prefinish);
}
function prefinish() {
var _this = this;
if (typeof this._flush === 'function') {
this._flush(function (er, data) {
done(_this, er, data);
});
} else {
done(this, null, null);
}
}
Transform.prototype.push = function (chunk, encoding) {
this._transformState.needTransform = false;
return Duplex.prototype.push.call(this, chunk, encoding);
};
// This is the part where you do stuff!
// override this function in implementation classes.
// 'chunk' is an input chunk.
//
// Call `push(newChunk)` to pass along transformed output
// to the readable side. You may call 'push' zero or more times.
//
// Call `cb(err)` when you are done with this chunk. If you pass
// an error, then that'll put the hurt on the whole operation. If you
// never call cb(), then you'll never get another chunk.
Transform.prototype._transform = function (chunk, encoding, cb) {
throw new Error('_transform() is not implemented');
};
Transform.prototype._write = function (chunk, encoding, cb) {
var ts = this._transformState;
ts.writecb = cb;
ts.writechunk = chunk;
ts.writeencoding = encoding;
if (!ts.transforming) {
var rs = this._readableState;
if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
}
};
// Doesn't matter what the args are here.
// _transform does all the work.
// That we got here means that the readable side wants more data.
Transform.prototype._read = function (n) {
var ts = this._transformState;
if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
ts.transforming = true;
this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
} else {
// mark that we need a transform, so that any data that comes in
// will get processed, now that we've asked for it.
ts.needTransform = true;
}
};
Transform.prototype._destroy = function (err, cb) {
var _this2 = this;
Duplex.prototype._destroy.call(this, err, function (err2) {
cb(err2);
_this2.emit('close');
});
};
function done(stream, er, data) {
if (er) return stream.emit('error', er);
if (data != null) // single equals check for both `null` and `undefined`
stream.push(data);
// if there's nothing in the write buffer, then that means
// that nothing more will ever be provided
if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0');
if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming');
return stream.push(null);
}
},{"./_stream_duplex":525,"core-util-is":515,"inherits":519}],529:[function(require,module,exports){
(function (process,global,setImmediate){(function (){
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
// A bit simpler than readable streams.
// Implement an async ._write(chunk, encoding, cb), and it'll handle all
// the drain event emission and buffering.
'use strict';
/*<replacement>*/
var pna = require('process-nextick-args');
/*</replacement>*/
module.exports = Writable;
/* <replacement> */
function WriteReq(chunk, encoding, cb) {
this.chunk = chunk;
this.encoding = encoding;
this.callback = cb;
this.next = null;
}
// It seems a linked list but it is not
// there will be only 2 of these for each stream
function CorkedRequest(state) {
var _this = this;
this.next = null;
this.entry = null;
this.finish = function () {
onCorkedFinish(_this, state);
};
}
/* </replacement> */
/*<replacement>*/
var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick;
/*</replacement>*/
/*<replacement>*/
var Duplex;
/*</replacement>*/
Writable.WritableState = WritableState;
/*<replacement>*/
var util = Object.create(require('core-util-is'));
util.inherits = require('inherits');
/*</replacement>*/
/*<replacement>*/
var internalUtil = {
deprecate: require('util-deprecate')
};
/*</replacement>*/
/*<replacement>*/
var Stream = require('./internal/streams/stream');
/*</replacement>*/
/*<replacement>*/
var Buffer = require('safe-buffer').Buffer;
var OurUint8Array = global.Uint8Array || function () {};
function _uint8ArrayToBuffer(chunk) {
return Buffer.from(chunk);
}
function _isUint8Array(obj) {
return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
}
/*</replacement>*/
var destroyImpl = require('./internal/streams/destroy');
util.inherits(Writable, Stream);
function nop() {}
function WritableState(options, stream) {
Duplex = Duplex || require('./_stream_duplex');
options = options || {};
// Duplex streams are both readable and writable, but share
// the same options object.
// However, some cases require setting options to different
// values for the readable and the writable sides of the duplex stream.
// These options can be provided separately as readableXXX and writableXXX.
var isDuplex = stream instanceof Duplex;
// object stream flag to indicate whether or not this stream
// contains buffers or objects.
this.objectMode = !!options.objectMode;
if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
// the point at which write() starts returning false
// Note: 0 is a valid value, means that we always return false if
// the entire buffer is not flushed immediately on write()
var hwm = options.highWaterMark;
var writableHwm = options.writableHighWaterMark;
var defaultHwm = this.objectMode ? 16 : 16 * 1024;
if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm;
// cast to ints.
this.highWaterMark = Math.floor(this.highWaterMark);
// if _final has been called
this.finalCalled = false;
// drain event flag.
this.needDrain = false;
// at the start of calling end()
this.ending = false;
// when end() has been called, and returned
this.ended = false;
// when 'finish' is emitted
this.finished = false;
// has it been destroyed
this.destroyed = false;
// should we decode strings into buffers before passing to _write?
// this is here so that some node-core streams can optimize string
// handling at a lower level.
var noDecode = options.decodeStrings === false;
this.decodeStrings = !noDecode;
// Crypto is kind of old and crusty. Historically, its default string
// encoding is 'binary' so we have to make this configurable.
// Everything else in the universe uses 'utf8', though.
this.defaultEncoding = options.defaultEncoding || 'utf8';
// not an actual buffer we keep track of, but a measurement
// of how much we're waiting to get pushed to some underlying
// socket or file.
this.length = 0;
// a flag to see when we're in the middle of a write.
this.writing = false;
// when true all writes will be buffered until .uncork() call
this.corked = 0;
// a flag to be able to tell if the onwrite cb is called immediately,
// or on a later tick. We set this to true at first, because any
// actions that shouldn't happen until "later" should generally also
// not happen before the first write call.
this.sync = true;
// a flag to know if we're processing previously buffered items, which
// may call the _write() callback in the same tick, so that we don't
// end up in an overlapped onwrite situation.
this.bufferProcessing = false;
// the callback that's passed to _write(chunk,cb)
this.onwrite = function (er) {
onwrite(stream, er);
};
// the callback that the user supplies to write(chunk,encoding,cb)
this.writecb = null;
// the amount that is being written when _write is called.
this.writelen = 0;
this.bufferedRequest = null;
this.lastBufferedRequest = null;
// number of pending user-supplied write callbacks
// this must be 0 before 'finish' can be emitted
this.pendingcb = 0;
// emit prefinish if the only thing we're waiting for is _write cbs
// This is relevant for synchronous Transform streams
this.prefinished = false;
// True if the error was already emitted and should not be thrown again
this.errorEmitted = false;
// count buffered requests
this.bufferedRequestCount = 0;
// allocate the first CorkedRequest, there is always
// one allocated and free to use, and we maintain at most two
this.corkedRequestsFree = new CorkedRequest(this);
}
WritableState.prototype.getBuffer = function getBuffer() {
var current = this.bufferedRequest;
var out = [];
while (current) {
out.push(current);
current = current.next;
}
return out;
};
(function () {
try {
Object.defineProperty(WritableState.prototype, 'buffer', {
get: internalUtil.deprecate(function () {
return this.getBuffer();
}, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
});
} catch (_) {}
})();
// Test _writableState for inheritance to account for Duplex streams,
// whose prototype chain only points to Readable.
var realHasInstance;
if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
realHasInstance = Function.prototype[Symbol.hasInstance];
Object.defineProperty(Writable, Symbol.hasInstance, {
value: function (object) {
if (realHasInstance.call(this, object)) return true;
if (this !== Writable) return false;
return object && object._writableState instanceof WritableState;
}
});
} else {
realHasInstance = function (object) {
return object instanceof this;
};
}
function Writable(options) {
Duplex = Duplex || require('./_stream_duplex');
// Writable ctor is applied to Duplexes, too.
// `realHasInstance` is necessary because using plain `instanceof`
// would return false, as no `_writableState` property is attached.
// Trying to use the custom `instanceof` for Writable here will also break the
// Node.js LazyTransform implementation, which has a non-trivial getter for
// `_writableState` that would lead to infinite recursion.
if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
return new Writable(options);
}
this._writableState = new WritableState(options, this);
// legacy.
this.writable = true;
if (options) {
if (typeof options.write === 'function') this._write = options.write;
if (typeof options.writev === 'function') this._writev = options.writev;
if (typeof options.destroy === 'function') this._destroy = options.destroy;
if (typeof options.final === 'function') this._final = options.final;
}
Stream.call(this);
}
// Otherwise people can pipe Writable streams, which is just wrong.
Writable.prototype.pipe = function () {
this.emit('error', new Error('Cannot pipe, not readable'));
};
function writeAfterEnd(stream, cb) {
var er = new Error('write after end');
// TODO: defer error events consistently everywhere, not just the cb
stream.emit('error', er);
pna.nextTick(cb, er);
}
// Checks that a user-supplied chunk is valid, especially for the particular
// mode the stream is in. Currently this means that `null` is never accepted
// and undefined/non-string values are only allowed in object mode.
function validChunk(stream, state, chunk, cb) {
var valid = true;
var er = false;
if (chunk === null) {
er = new TypeError('May not write null values to stream');
} else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
er = new TypeError('Invalid non-string/buffer chunk');
}
if (er) {
stream.emit('error', er);
pna.nextTick(cb, er);
valid = false;
}
return valid;
}
Writable.prototype.write = function (chunk, encoding, cb) {
var state = this._writableState;
var ret = false;
var isBuf = !state.objectMode && _isUint8Array(chunk);
if (isBuf && !Buffer.isBuffer(chunk)) {
chunk = _uint8ArrayToBuffer(chunk);
}
if (typeof encoding === 'function') {
cb = encoding;
encoding = null;
}
if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
if (typeof cb !== 'function') cb = nop;
if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
state.pendingcb++;
ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
}
return ret;
};
Writable.prototype.cork = function () {
var state = this._writableState;
state.corked++;
};
Writable.prototype.uncork = function () {
var state = this._writableState;
if (state.corked) {
state.corked--;
if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
}
};
Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
// node::ParseEncoding() requires lower case.
if (typeof encoding === 'string') encoding = encoding.toLowerCase();
if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding);
this._writableState.defaultEncoding = encoding;
return this;
};
function decodeChunk(state, chunk, encoding) {
if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
chunk = Buffer.from(chunk, encoding);
}
return chunk;
}
Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
// making it explicit this property is not enumerable
// because otherwise some prototype manipulation in
// userland will fail
enumerable: false,
get: function () {
return this._writableState.highWaterMark;
}
});
// if we're already writing something, then just put this
// in the queue, and wait our turn. Otherwise, call _write
// If we return false, then we need a drain event, so set that flag.
function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
if (!isBuf) {
var newChunk = decodeChunk(state, chunk, encoding);
if (chunk !== newChunk) {
isBuf = true;
encoding = 'buffer';
chunk = newChunk;
}
}
var len = state.objectMode ? 1 : chunk.length;
state.length += len;
var ret = state.length < state.highWaterMark;
// we must ensure that previous needDrain will not be reset to false.
if (!ret) state.needDrain = true;
if (state.writing || state.corked) {
var last = state.lastBufferedRequest;
state.lastBufferedRequest = {
chunk: chunk,
encoding: encoding,
isBuf: isBuf,
callback: cb,
next: null
};
if (last) {
last.next = state.lastBufferedRequest;
} else {
state.bufferedRequest = state.lastBufferedRequest;
}
state.bufferedRequestCount += 1;
} else {
doWrite(stream, state, false, len, chunk, encoding, cb);
}
return ret;
}
function doWrite(stream, state, writev, len, chunk, encoding, cb) {
state.writelen = len;
state.writecb = cb;
state.writing = true;
state.sync = true;
if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
state.sync = false;
}
function onwriteError(stream, state, sync, er, cb) {
--state.pendingcb;
if (sync) {
// defer the callback if we are being called synchronously
// to avoid piling up things on the stack
pna.nextTick(cb, er);
// this can emit finish, and it will always happen
// after error
pna.nextTick(finishMaybe, stream, state);
stream._writableState.errorEmitted = true;
stream.emit('error', er);
} else {
// the caller expect this to happen before if
// it is async
cb(er);
stream._writableState.errorEmitted = true;
stream.emit('error', er);
// this can emit finish, but finish must
// always follow error
finishMaybe(stream, state);
}
}
function onwriteStateUpdate(state) {
state.writing = false;
state.writecb = null;
state.length -= state.writelen;
state.writelen = 0;
}
function onwrite(stream, er) {
var state = stream._writableState;
var sync = state.sync;
var cb = state.writecb;
onwriteStateUpdate(state);
if (er) onwriteError(stream, state, sync, er, cb);else {
// Check if we're actually ready to finish, but don't emit yet
var finished = needFinish(state);
if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
clearBuffer(stream, state);
}
if (sync) {
/*<replacement>*/
asyncWrite(afterWrite, stream, state, finished, cb);
/*</replacement>*/
} else {
afterWrite(stream, state, finished, cb);
}
}
}
function afterWrite(stream, state, finished, cb) {
if (!finished) onwriteDrain(stream, state);
state.pendingcb--;
cb();
finishMaybe(stream, state);
}
// Must force callback to be called on nextTick, so that we don't
// emit 'drain' before the write() consumer gets the 'false' return
// value, and has a chance to attach a 'drain' listener.
function onwriteDrain(stream, state) {
if (state.length === 0 && state.needDrain) {
state.needDrain = false;
stream.emit('drain');
}
}
// if there's something in the buffer waiting, then process it
function clearBuffer(stream, state) {
state.bufferProcessing = true;
var entry = state.bufferedRequest;
if (stream._writev && entry && entry.next) {
// Fast case, write everything using _writev()
var l = state.bufferedRequestCount;
var buffer = new Array(l);
var holder = state.corkedRequestsFree;
holder.entry = entry;
var count = 0;
var allBuffers = true;
while (entry) {
buffer[count] = entry;
if (!entry.isBuf) allBuffers = false;
entry = entry.next;
count += 1;
}
buffer.allBuffers = allBuffers;
doWrite(stream, state, true, state.length, buffer, '', holder.finish);
// doWrite is almost always async, defer these to save a bit of time
// as the hot path ends with doWrite
state.pendingcb++;
state.lastBufferedRequest = null;
if (holder.next) {
state.corkedRequestsFree = holder.next;
holder.next = null;
} else {
state.corkedRequestsFree = new CorkedRequest(state);
}
state.bufferedRequestCount = 0;
} else {
// Slow case, write chunks one-by-one
while (entry) {
var chunk = entry.chunk;
var encoding = entry.encoding;
var cb = entry.callback;
var len = state.objectMode ? 1 : chunk.length;
doWrite(stream, state, false, len, chunk, encoding, cb);
entry = entry.next;
state.bufferedRequestCount--;
// if we didn't call the onwrite immediately, then
// it means that we need to wait until it does.
// also, that means that the chunk and cb are currently
// being processed, so move the buffer counter past them.
if (state.writing) {
break;
}
}
if (entry === null) state.lastBufferedRequest = null;
}
state.bufferedRequest = entry;
state.bufferProcessing = false;
}
Writable.prototype._write = function (chunk, encoding, cb) {
cb(new Error('_write() is not implemented'));
};
Writable.prototype._writev = null;
Writable.prototype.end = function (chunk, encoding, cb) {
var state = this._writableState;
if (typeof chunk === 'function') {
cb = chunk;
chunk = null;
encoding = null;
} else if (typeof encoding === 'function') {
cb = encoding;
encoding = null;
}
if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
// .end() fully uncorks
if (state.corked) {
state.corked = 1;
this.uncork();
}
// ignore unnecessary end() calls.
if (!state.ending && !state.finished) endWritable(this, state, cb);
};
function needFinish(state) {
return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
}
function callFinal(stream, state) {
stream._final(function (err) {
state.pendingcb--;
if (err) {
stream.emit('error', err);
}
state.prefinished = true;
stream.emit('prefinish');
finishMaybe(stream, state);
});
}
function prefinish(stream, state) {
if (!state.prefinished && !state.finalCalled) {
if (typeof stream._final === 'function') {
state.pendingcb++;
state.finalCalled = true;
pna.nextTick(callFinal, stream, state);
} else {
state.prefinished = true;
stream.emit('prefinish');
}
}
}
function finishMaybe(stream, state) {
var need = needFinish(state);
if (need) {
prefinish(stream, state);
if (state.pendingcb === 0) {
state.finished = true;
stream.emit('finish');
}
}
return need;
}
function endWritable(stream, state, cb) {
state.ending = true;
finishMaybe(stream, state);
if (cb) {
if (state.finished) pna.nextTick(cb);else stream.once('finish', cb);
}
state.ended = true;
stream.writable = false;
}
function onCorkedFinish(corkReq, state, err) {
var entry = corkReq.entry;
corkReq.entry = null;
while (entry) {
var cb = entry.callback;
state.pendingcb--;
cb(err);
entry = entry.next;
}
if (state.corkedRequestsFree) {
state.corkedRequestsFree.next = corkReq;
} else {
state.corkedRequestsFree = corkReq;
}
}
Object.defineProperty(Writable.prototype, 'destroyed', {
get: function () {
if (this._writableState === undefined) {
return false;
}
return this._writableState.destroyed;
},
set: function (value) {
// we ignore the value if the stream
// has not been initialized yet
if (!this._writableState) {
return;
}
// backward compatibility, the user is explicitly
// managing destroyed
this._writableState.destroyed = value;
}
});
Writable.prototype.destroy = destroyImpl.destroy;
Writable.prototype._undestroy = destroyImpl.undestroy;
Writable.prototype._destroy = function (err, cb) {
this.end();
cb(err);
};
}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("timers").setImmediate)
},{"./_stream_duplex":525,"./internal/streams/destroy":531,"./internal/streams/stream":532,"_process":524,"core-util-is":515,"inherits":519,"process-nextick-args":523,"safe-buffer":534,"timers":536,"util-deprecate":537}],530:[function(require,module,exports){
'use strict';
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Buffer = require('safe-buffer').Buffer;
var util = require('util');
function copyBuffer(src, target, offset) {
src.copy(target, offset);
}
module.exports = function () {
function BufferList() {
_classCallCheck(this, BufferList);
this.head = null;
this.tail = null;
this.length = 0;
}
BufferList.prototype.push = function push(v) {
var entry = { data: v, next: null };
if (this.length > 0) this.tail.next = entry;else this.head = entry;
this.tail = entry;
++this.length;
};
BufferList.prototype.unshift = function unshift(v) {
var entry = { data: v, next: this.head };
if (this.length === 0) this.tail = entry;
this.head = entry;
++this.length;
};
BufferList.prototype.shift = function shift() {
if (this.length === 0) return;
var ret = this.head.data;
if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
--this.length;
return ret;
};
BufferList.prototype.clear = function clear() {
this.head = this.tail = null;
this.length = 0;
};
BufferList.prototype.join = function join(s) {
if (this.length === 0) return '';
var p = this.head;
var ret = '' + p.data;
while (p = p.next) {
ret += s + p.data;
}return ret;
};
BufferList.prototype.concat = function concat(n) {
if (this.length === 0) return Buffer.alloc(0);
if (this.length === 1) return this.head.data;
var ret = Buffer.allocUnsafe(n >>> 0);
var p = this.head;
var i = 0;
while (p) {
copyBuffer(p.data, ret, i);
i += p.data.length;
p = p.next;
}
return ret;
};
return BufferList;
}();
if (util && util.inspect && util.inspect.custom) {
module.exports.prototype[util.inspect.custom] = function () {
var obj = util.inspect({ length: this.length });
return this.constructor.name + ' ' + obj;
};
}
},{"safe-buffer":534,"util":512}],531:[function(require,module,exports){
'use strict';
/*<replacement>*/
var pna = require('process-nextick-args');
/*</replacement>*/
// undocumented cb() API, needed for core, not for public API
function destroy(err, cb) {
var _this = this;
var readableDestroyed = this._readableState && this._readableState.destroyed;
var writableDestroyed = this._writableState && this._writableState.destroyed;
if (readableDestroyed || writableDestroyed) {
if (cb) {
cb(err);
} else if (err && (!this._writableState || !this._writableState.errorEmitted)) {
pna.nextTick(emitErrorNT, this, err);
}
return this;
}
// we set destroyed to true before firing error callbacks in order
// to make it re-entrance safe in case destroy() is called within callbacks
if (this._readableState) {
this._readableState.destroyed = true;
}
// if this is a duplex stream mark the writable part as destroyed as well
if (this._writableState) {
this._writableState.destroyed = true;
}
this._destroy(err || null, function (err) {
if (!cb && err) {
pna.nextTick(emitErrorNT, _this, err);
if (_this._writableState) {
_this._writableState.errorEmitted = true;
}
} else if (cb) {
cb(err);
}
});
return this;
}
function undestroy() {
if (this._readableState) {
this._readableState.destroyed = false;
this._readableState.reading = false;
this._readableState.ended = false;
this._readableState.endEmitted = false;
}
if (this._writableState) {
this._writableState.destroyed = false;
this._writableState.ended = false;
this._writableState.ending = false;
this._writableState.finished = false;
this._writableState.errorEmitted = false;
}
}
function emitErrorNT(self, err) {
self.emit('error', err);
}
module.exports = {
destroy: destroy,
undestroy: undestroy
};
},{"process-nextick-args":523}],532:[function(require,module,exports){
module.exports = require('events').EventEmitter;
},{"events":513}],533:[function(require,module,exports){
exports = module.exports = require('./lib/_stream_readable.js');
exports.Stream = exports;
exports.Readable = exports;
exports.Writable = require('./lib/_stream_writable.js');
exports.Duplex = require('./lib/_stream_duplex.js');
exports.Transform = require('./lib/_stream_transform.js');
exports.PassThrough = require('./lib/_stream_passthrough.js');
},{"./lib/_stream_duplex.js":525,"./lib/_stream_passthrough.js":526,"./lib/_stream_readable.js":527,"./lib/_stream_transform.js":528,"./lib/_stream_writable.js":529}],534:[function(require,module,exports){
/* eslint-disable node/no-deprecated-api */
var buffer = require('buffer')
var Buffer = buffer.Buffer
// alternative to using Object.keys for old browsers
function copyProps (src, dst) {
for (var key in src) {
dst[key] = src[key]
}
}
if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
module.exports = buffer
} else {
// Copy properties from require('buffer')
copyProps(buffer, exports)
exports.Buffer = SafeBuffer
}
function SafeBuffer (arg, encodingOrOffset, length) {
return Buffer(arg, encodingOrOffset, length)
}
// Copy static methods from Buffer
copyProps(Buffer, SafeBuffer)
SafeBuffer.from = function (arg, encodingOrOffset, length) {
if (typeof arg === 'number') {
throw new TypeError('Argument must not be a number')
}
return Buffer(arg, encodingOrOffset, length)
}
SafeBuffer.alloc = function (size, fill, encoding) {
if (typeof size !== 'number') {
throw new TypeError('Argument must be a number')
}
var buf = Buffer(size)
if (fill !== undefined) {
if (typeof encoding === 'string') {
buf.fill(fill, encoding)
} else {
buf.fill(fill)
}
} else {
buf.fill(0)
}
return buf
}
SafeBuffer.allocUnsafe = function (size) {
if (typeof size !== 'number') {
throw new TypeError('Argument must be a number')
}
return Buffer(size)
}
SafeBuffer.allocUnsafeSlow = function (size) {
if (typeof size !== 'number') {
throw new TypeError('Argument must be a number')
}
return buffer.SlowBuffer(size)
}
},{"buffer":514}],535:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
'use strict';
/*<replacement>*/
var Buffer = require('safe-buffer').Buffer;
/*</replacement>*/
var isEncoding = Buffer.isEncoding || function (encoding) {
encoding = '' + encoding;
switch (encoding && encoding.toLowerCase()) {
case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw':
return true;
default:
return false;
}
};
function _normalizeEncoding(enc) {
if (!enc) return 'utf8';
var retried;
while (true) {
switch (enc) {
case 'utf8':
case 'utf-8':
return 'utf8';
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return 'utf16le';
case 'latin1':
case 'binary':
return 'latin1';
case 'base64':
case 'ascii':
case 'hex':
return enc;
default:
if (retried) return; // undefined
enc = ('' + enc).toLowerCase();
retried = true;
}
}
};
// Do not cache `Buffer.isEncoding` when checking encoding names as some
// modules monkey-patch it to support additional encodings
function normalizeEncoding(enc) {
var nenc = _normalizeEncoding(enc);
if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
return nenc || enc;
}
// StringDecoder provides an interface for efficiently splitting a series of
// buffers into a series of JS strings without breaking apart multi-byte
// characters.
exports.StringDecoder = StringDecoder;
function StringDecoder(encoding) {
this.encoding = normalizeEncoding(encoding);
var nb;
switch (this.encoding) {
case 'utf16le':
this.text = utf16Text;
this.end = utf16End;
nb = 4;
break;
case 'utf8':
this.fillLast = utf8FillLast;
nb = 4;
break;
case 'base64':
this.text = base64Text;
this.end = base64End;
nb = 3;
break;
default:
this.write = simpleWrite;
this.end = simpleEnd;
return;
}
this.lastNeed = 0;
this.lastTotal = 0;
this.lastChar = Buffer.allocUnsafe(nb);
}
StringDecoder.prototype.write = function (buf) {
if (buf.length === 0) return '';
var r;
var i;
if (this.lastNeed) {
r = this.fillLast(buf);
if (r === undefined) return '';
i = this.lastNeed;
this.lastNeed = 0;
} else {
i = 0;
}
if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
return r || '';
};
StringDecoder.prototype.end = utf8End;
// Returns only complete characters in a Buffer
StringDecoder.prototype.text = utf8Text;
// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
StringDecoder.prototype.fillLast = function (buf) {
if (this.lastNeed <= buf.length) {
buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
return this.lastChar.toString(this.encoding, 0, this.lastTotal);
}
buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
this.lastNeed -= buf.length;
};
// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
// continuation byte. If an invalid byte is detected, -2 is returned.
function utf8CheckByte(byte) {
if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;
return byte >> 6 === 0x02 ? -1 : -2;
}
// Checks at most 3 bytes at the end of a Buffer in order to detect an
// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
// needed to complete the UTF-8 character (if applicable) are returned.
function utf8CheckIncomplete(self, buf, i) {
var j = buf.length - 1;
if (j < i) return 0;
var nb = utf8CheckByte(buf[j]);
if (nb >= 0) {
if (nb > 0) self.lastNeed = nb - 1;
return nb;
}
if (--j < i || nb === -2) return 0;
nb = utf8CheckByte(buf[j]);
if (nb >= 0) {
if (nb > 0) self.lastNeed = nb - 2;
return nb;
}
if (--j < i || nb === -2) return 0;
nb = utf8CheckByte(buf[j]);
if (nb >= 0) {
if (nb > 0) {
if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
}
return nb;
}
return 0;
}
// Validates as many continuation bytes for a multi-byte UTF-8 character as
// needed or are available. If we see a non-continuation byte where we expect
// one, we "replace" the validated continuation bytes we've seen so far with
// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding
// behavior. The continuation byte check is included three times in the case
// where all of the continuation bytes for a character exist in the same buffer.
// It is also done this way as a slight performance increase instead of using a
// loop.
function utf8CheckExtraBytes(self, buf, p) {
if ((buf[0] & 0xC0) !== 0x80) {
self.lastNeed = 0;
return '\ufffd';
}
if (self.lastNeed > 1 && buf.length > 1) {
if ((buf[1] & 0xC0) !== 0x80) {
self.lastNeed = 1;
return '\ufffd';
}
if (self.lastNeed > 2 && buf.length > 2) {
if ((buf[2] & 0xC0) !== 0x80) {
self.lastNeed = 2;
return '\ufffd';
}
}
}
}
// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
function utf8FillLast(buf) {
var p = this.lastTotal - this.lastNeed;
var r = utf8CheckExtraBytes(this, buf, p);
if (r !== undefined) return r;
if (this.lastNeed <= buf.length) {
buf.copy(this.lastChar, p, 0, this.lastNeed);
return this.lastChar.toString(this.encoding, 0, this.lastTotal);
}
buf.copy(this.lastChar, p, 0, buf.length);
this.lastNeed -= buf.length;
}
// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
// partial character, the character's bytes are buffered until the required
// number of bytes are available.
function utf8Text(buf, i) {
var total = utf8CheckIncomplete(this, buf, i);
if (!this.lastNeed) return buf.toString('utf8', i);
this.lastTotal = total;
var end = buf.length - (total - this.lastNeed);
buf.copy(this.lastChar, 0, end);
return buf.toString('utf8', i, end);
}
// For UTF-8, a replacement character is added when ending on a partial
// character.
function utf8End(buf) {
var r = buf && buf.length ? this.write(buf) : '';
if (this.lastNeed) return r + '\ufffd';
return r;
}
// UTF-16LE typically needs two bytes per character, but even if we have an even
// number of bytes available, we need to check if we end on a leading/high
// surrogate. In that case, we need to wait for the next two bytes in order to
// decode the last character properly.
function utf16Text(buf, i) {
if ((buf.length - i) % 2 === 0) {
var r = buf.toString('utf16le', i);
if (r) {
var c = r.charCodeAt(r.length - 1);
if (c >= 0xD800 && c <= 0xDBFF) {
this.lastNeed = 2;
this.lastTotal = 4;
this.lastChar[0] = buf[buf.length - 2];
this.lastChar[1] = buf[buf.length - 1];
return r.slice(0, -1);
}
}
return r;
}
this.lastNeed = 1;
this.lastTotal = 2;
this.lastChar[0] = buf[buf.length - 1];
return buf.toString('utf16le', i, buf.length - 1);
}
// For UTF-16LE we do not explicitly append special replacement characters if we
// end on a partial character, we simply let v8 handle that.
function utf16End(buf) {
var r = buf && buf.length ? this.write(buf) : '';
if (this.lastNeed) {
var end = this.lastTotal - this.lastNeed;
return r + this.lastChar.toString('utf16le', 0, end);
}
return r;
}
function base64Text(buf, i) {
var n = (buf.length - i) % 3;
if (n === 0) return buf.toString('base64', i);
this.lastNeed = 3 - n;
this.lastTotal = 3;
if (n === 1) {
this.lastChar[0] = buf[buf.length - 1];
} else {
this.lastChar[0] = buf[buf.length - 2];
this.lastChar[1] = buf[buf.length - 1];
}
return buf.toString('base64', i, buf.length - n);
}
function base64End(buf) {
var r = buf && buf.length ? this.write(buf) : '';
if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
return r;
}
// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
function simpleWrite(buf) {
return buf.toString(this.encoding);
}
function simpleEnd(buf) {
return buf && buf.length ? this.write(buf) : '';
}
},{"safe-buffer":534}],536:[function(require,module,exports){
(function (setImmediate,clearImmediate){(function (){
var nextTick = require('process/browser.js').nextTick;
var apply = Function.prototype.apply;
var slice = Array.prototype.slice;
var immediateIds = {};
var nextImmediateId = 0;
// DOM APIs, for completeness
exports.setTimeout = function() {
return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
};
exports.setInterval = function() {
return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
};
exports.clearTimeout =
exports.clearInterval = function(timeout) { timeout.close(); };
function Timeout(id, clearFn) {
this._id = id;
this._clearFn = clearFn;
}
Timeout.prototype.unref = Timeout.prototype.ref = function() {};
Timeout.prototype.close = function() {
this._clearFn.call(window, this._id);
};
// Does not start the time, just sets up the members needed.
exports.enroll = function(item, msecs) {
clearTimeout(item._idleTimeoutId);
item._idleTimeout = msecs;
};
exports.unenroll = function(item) {
clearTimeout(item._idleTimeoutId);
item._idleTimeout = -1;
};
exports._unrefActive = exports.active = function(item) {
clearTimeout(item._idleTimeoutId);
var msecs = item._idleTimeout;
if (msecs >= 0) {
item._idleTimeoutId = setTimeout(function onTimeout() {
if (item._onTimeout)
item._onTimeout();
}, msecs);
}
};
// That's not how node.js implements it but the exposed api is the same.
exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) {
var id = nextImmediateId++;
var args = arguments.length < 2 ? false : slice.call(arguments, 1);
immediateIds[id] = true;
nextTick(function onNextTick() {
if (immediateIds[id]) {
// fn.call() is faster so we optimize for the common use-case
// @see http://jsperf.com/call-apply-segu
if (args) {
fn.apply(null, args);
} else {
fn.call(null);
}
// Prevent ids from leaking
exports.clearImmediate(id);
}
});
return id;
};
exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) {
delete immediateIds[id];
};
}).call(this)}).call(this,require("timers").setImmediate,require("timers").clearImmediate)
},{"process/browser.js":524,"timers":536}],537:[function(require,module,exports){
(function (global){(function (){
/**
* Module exports.
*/
module.exports = deprecate;
/**
* Mark that a method should not be used.
* Returns a modified function which warns once by default.
*
* If `localStorage.noDeprecation = true` is set, then it is a no-op.
*
* If `localStorage.throwDeprecation = true` is set, then deprecated functions
* will throw an Error when invoked.
*
* If `localStorage.traceDeprecation = true` is set, then deprecated functions
* will invoke `console.trace()` instead of `console.error()`.
*
* @param {Function} fn - the function to deprecate
* @param {String} msg - the string to print to the console when `fn` is invoked
* @returns {Function} a new "deprecated" version of `fn`
* @api public
*/
function deprecate (fn, msg) {
if (config('noDeprecation')) {
return fn;
}
var warned = false;
function deprecated() {
if (!warned) {
if (config('throwDeprecation')) {
throw new Error(msg);
} else if (config('traceDeprecation')) {
console.trace(msg);
} else {
console.warn(msg);
}
warned = true;
}
return fn.apply(this, arguments);
}
return deprecated;
}
/**
* Checks `localStorage` for boolean values for the given `name`.
*
* @param {String} name
* @returns {Boolean}
* @api private
*/
function config (name) {
// accessing global.localStorage can trigger a DOMException in sandboxed iframes
try {
if (!global.localStorage) return false;
} catch (_) {
return false;
}
var val = global.localStorage[name];
if (null == val) return false;
return String(val).toLowerCase() === 'true';
}
}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}]},{},[374,375]);
| stdlib-js/www | public/docs/api/latest/@stdlib/random/streams/poisson/benchmark_bundle.js | JavaScript | apache-2.0 | 1,047,804 |
/*global define*/
define([
'./Check',
'./Cartesian2',
'./defaultValue',
'./defined',
'./defineProperties',
'./Ellipsoid',
'./GeographicProjection',
'./Math',
'./Rectangle'
], function(
Check,
Cartesian2,
defaultValue,
defined,
defineProperties,
Ellipsoid,
GeographicProjection,
CesiumMath,
Rectangle) {
'use strict';
/**
* A tiling scheme for geometry referenced to a simple {@link GeographicProjection} where
* longitude and latitude are directly mapped to X and Y. This projection is commonly
* known as geographic, equirectangular, equidistant cylindrical, or plate carrée.
*
* @alias GeographicTilingScheme
* @constructor
*
* @param {Object} [options] Object with the following properties:
* @param {Ellipsoid} [options.ellipsoid=Ellipsoid.WGS84] The ellipsoid whose surface is being tiled. Defaults to
* the WGS84 ellipsoid.
* @param {Rectangle} [options.rectangle=Rectangle.MAX_VALUE] The rectangle, in radians, covered by the tiling scheme.
* @param {Number} [options.numberOfLevelZeroTilesX=2] The number of tiles in the X direction at level zero of
* the tile tree.
* @param {Number} [options.numberOfLevelZeroTilesY=1] The number of tiles in the Y direction at level zero of
* the tile tree.
*/
function GeographicTilingScheme(options) {
options = defaultValue(options, {});
this._ellipsoid = defaultValue(options.ellipsoid, Ellipsoid.WGS84);
this._rectangle = defaultValue(options.rectangle, Rectangle.MAX_VALUE);
this._projection = new GeographicProjection(this._ellipsoid);
this._numberOfLevelZeroTilesX = defaultValue(options.numberOfLevelZeroTilesX, 2);
this._numberOfLevelZeroTilesY = defaultValue(options.numberOfLevelZeroTilesY, 1);
}
defineProperties(GeographicTilingScheme.prototype, {
/**
* Gets the ellipsoid that is tiled by this tiling scheme.
* @memberof GeographicTilingScheme.prototype
* @type {Ellipsoid}
*/
ellipsoid : {
get : function() {
return this._ellipsoid;
}
},
/**
* Gets the rectangle, in radians, covered by this tiling scheme.
* @memberof GeographicTilingScheme.prototype
* @type {Rectangle}
*/
rectangle : {
get : function() {
return this._rectangle;
}
},
/**
* Gets the map projection used by this tiling scheme.
* @memberof GeographicTilingScheme.prototype
* @type {MapProjection}
*/
projection : {
get : function() {
return this._projection;
}
}
});
/**
* Gets the total number of tiles in the X direction at a specified level-of-detail.
*
* @param {Number} level The level-of-detail.
* @returns {Number} The number of tiles in the X direction at the given level.
*/
GeographicTilingScheme.prototype.getNumberOfXTilesAtLevel = function(level) {
return this._numberOfLevelZeroTilesX << level;
};
/**
* Gets the total number of tiles in the Y direction at a specified level-of-detail.
*
* @param {Number} level The level-of-detail.
* @returns {Number} The number of tiles in the Y direction at the given level.
*/
GeographicTilingScheme.prototype.getNumberOfYTilesAtLevel = function(level) {
return this._numberOfLevelZeroTilesY << level;
};
/**
* Transforms a rectangle specified in geodetic radians to the native coordinate system
* of this tiling scheme.
*
* @param {Rectangle} rectangle The rectangle to transform.
* @param {Rectangle} [result] The instance to which to copy the result, or undefined if a new instance
* should be created.
* @returns {Rectangle} The specified 'result', or a new object containing the native rectangle if 'result'
* is undefined.
*/
GeographicTilingScheme.prototype.rectangleToNativeRectangle = function(rectangle, result) {
//>>includeStart('debug', pragmas.debug);
Check.defined('rectangle', rectangle);
//>>includeEnd('debug');
var west = CesiumMath.toDegrees(rectangle.west);
var south = CesiumMath.toDegrees(rectangle.south);
var east = CesiumMath.toDegrees(rectangle.east);
var north = CesiumMath.toDegrees(rectangle.north);
if (!defined(result)) {
return new Rectangle(west, south, east, north);
}
result.west = west;
result.south = south;
result.east = east;
result.north = north;
return result;
};
/**
* Converts tile x, y coordinates and level to a rectangle expressed in the native coordinates
* of the tiling scheme.
*
* @param {Number} x The integer x coordinate of the tile.
* @param {Number} y The integer y coordinate of the tile.
* @param {Number} level The tile level-of-detail. Zero is the least detailed.
* @param {Object} [result] The instance to which to copy the result, or undefined if a new instance
* should be created.
* @returns {Rectangle} The specified 'result', or a new object containing the rectangle
* if 'result' is undefined.
*/
GeographicTilingScheme.prototype.tileXYToNativeRectangle = function(x, y, level, result) {
var rectangleRadians = this.tileXYToRectangle(x, y, level, result);
rectangleRadians.west = CesiumMath.toDegrees(rectangleRadians.west);
rectangleRadians.south = CesiumMath.toDegrees(rectangleRadians.south);
rectangleRadians.east = CesiumMath.toDegrees(rectangleRadians.east);
rectangleRadians.north = CesiumMath.toDegrees(rectangleRadians.north);
return rectangleRadians;
};
/**
* Converts tile x, y coordinates and level to a cartographic rectangle in radians.
*
* @param {Number} x The integer x coordinate of the tile.
* @param {Number} y The integer y coordinate of the tile.
* @param {Number} level The tile level-of-detail. Zero is the least detailed.
* @param {Object} [result] The instance to which to copy the result, or undefined if a new instance
* should be created.
* @returns {Rectangle} The specified 'result', or a new object containing the rectangle
* if 'result' is undefined.
*/
GeographicTilingScheme.prototype.tileXYToRectangle = function(x, y, level, result) {
var rectangle = this._rectangle;
var xTiles = this.getNumberOfXTilesAtLevel(level);
var yTiles = this.getNumberOfYTilesAtLevel(level);
var xTileWidth = rectangle.width / xTiles;
var west = x * xTileWidth + rectangle.west;
var east = (x + 1) * xTileWidth + rectangle.west;
var yTileHeight = rectangle.height / yTiles;
var north = rectangle.north - y * yTileHeight;
var south = rectangle.north - (y + 1) * yTileHeight;
if (!defined(result)) {
result = new Rectangle(west, south, east, north);
}
result.west = west;
result.south = south;
result.east = east;
result.north = north;
return result;
};
/**
* Calculates the tile x, y coordinates of the tile containing
* a given cartographic position.
*
* @param {Cartographic} position The position.
* @param {Number} level The tile level-of-detail. Zero is the least detailed.
* @param {Cartesian2} [result] The instance to which to copy the result, or undefined if a new instance
* should be created.
* @returns {Cartesian2} The specified 'result', or a new object containing the tile x, y coordinates
* if 'result' is undefined.
*/
GeographicTilingScheme.prototype.positionToTileXY = function(position, level, result) {
var rectangle = this._rectangle;
if (!Rectangle.contains(rectangle, position)) {
// outside the bounds of the tiling scheme
return undefined;
}
var xTiles = this.getNumberOfXTilesAtLevel(level);
var yTiles = this.getNumberOfYTilesAtLevel(level);
var xTileWidth = rectangle.width / xTiles;
var yTileHeight = rectangle.height / yTiles;
var longitude = position.longitude;
if (rectangle.east < rectangle.west) {
longitude += CesiumMath.TWO_PI;
}
var xTileCoordinate = (longitude - rectangle.west) / xTileWidth | 0;
if (xTileCoordinate >= xTiles) {
xTileCoordinate = xTiles - 1;
}
var yTileCoordinate = (rectangle.north - position.latitude) / yTileHeight | 0;
if (yTileCoordinate >= yTiles) {
yTileCoordinate = yTiles - 1;
}
if (!defined(result)) {
return new Cartesian2(xTileCoordinate, yTileCoordinate);
}
result.x = xTileCoordinate;
result.y = yTileCoordinate;
return result;
};
return GeographicTilingScheme;
});
| omh1280/cesium | Source/Core/GeographicTilingScheme.js | JavaScript | apache-2.0 | 9,287 |
/**
* Copyright 2017 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.
*/
'use strict';
class EmptyCreateResponse extends Error {
constructor () {
super([
'The service returned an empty response when creating the entry.'
, 'The status and message-id of the entry are unknown; the entry,'
, 'therefore, cannot be updated.'
].join('\n'));
}
}
class BadMessageIdCreateResponse extends Error {
constructor () {
super([
'The service returned a response with an empty or invalid message-id.',
'The entry cannot be updated.'
].join('\n'));
}
}
class BadStatusCreateResponse extends Error {
constructor (status) {
super('The service returned a create response with an empty or bad status: '
+ status);
}
}
class MessageHasAlreadyBeenUpdated extends Error {
constructor () {
super('This message has already been updated');
}
}
class MessageHasAlreadyBeenSent extends Error {
constructor () {
super('This message has already been sent');
}
}
class MessageCannotBeUpdated extends Error {
constructor () {
super('This message cannot be updated due to a prior error in creation');
}
}
class EmptyUpdateResponse extends Error {
constructor () {
super([
'The service returned an empty response when creating the entry.'
, 'The status of the update is therefore unknown.'
].join('\n'))
}
}
class BadStatusUpdateResponse extends Error {
constructor (status) {
super(
'The service returned an update response with an empty or bad status: '
+ status);
}
}
class FieldsFailedToUpdate extends Error {
constructor (fields) {
super('The service reported that specific fields failed to update: \n\t'
+ fields.join('\n\t'));
}
}
class GenericUpdateError extends Error {
constructor (serviceError) {
super('The service returned an error on update: ' + serviceError);
}
}
class UpdateResponseDidNotHaveUpdatedList extends Error {
constructor () {
super([
'The service responded without providing an "updated" field in the'
, 'response. Certain fields may not have actually updated.'
].join('\n'));
}
}
class MessageMustBeSentBeforeBeingUpdated extends Error {
constructor () {
super([
'The message cannot be updated before it is first sent to the service.'
, 'Please try calling send first.'
].join('\n'));
}
}
module.exports = {
EmptyCreateResponse: EmptyCreateResponse
, BadMessageIdCreateResponse: BadMessageIdCreateResponse
, BadStatusCreateResponse: BadStatusCreateResponse
, MessageHasAlreadyBeenUpdated: MessageHasAlreadyBeenUpdated
, MessageHasAlreadyBeenSent: MessageHasAlreadyBeenSent
, MessageCannotBeUpdated: MessageCannotBeUpdated
, EmptyUpdateResponse: EmptyUpdateResponse
, BadStatusUpdateResponse: BadStatusUpdateResponse
, FieldsFailedToUpdate: FieldsFailedToUpdate
, GenericUpdateError: GenericUpdateError
, UpdateResponseDidNotHaveUpdatedList: UpdateResponseDidNotHaveUpdatedList
, MessageMustBeSentBeforeBeingUpdated: MessageMustBeSentBeforeBeingUpdated
};
| google/chatbase-node | lib/MessageStateWrapper/errors.js | JavaScript | apache-2.0 | 3,638 |
/*
* Copyright 2019 ThoughtWorks, Inc.
*
* 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.
*/
const $ = require('jquery');
const m = require('mithril');
const Stream = require('mithril/stream');
const DashboardVM = require('views/dashboard/models/dashboard_view_model');
const Dashboard = require('models/dashboard/dashboard');
const DashboardWidget = require('views/dashboard/dashboard_widget');
const PluginInfos = require('models/shared/plugin_infos');
const AjaxPoller = require('helpers/ajax_poller').AjaxPoller;
const PageLoadError = require('views/shared/page_load_error');
const PersonalizeVM = require('views/dashboard/models/personalization_vm');
$(() => {
const dashboardElem = $('#dashboard');
const showEmptyPipelineGroups = JSON.parse(dashboardElem.attr('data-show-empty-pipeline-groups'));
const shouldShowAnalyticsIcon = JSON.parse(dashboardElem.attr('data-should-show-analytics-icon'));
const useNewAddPipelineFlow = JSON.parse(dashboardElem.attr('data-use-new-add-pipeline-flow'));
const addPipelineButtonStyling = JSON.parse(dashboardElem.attr('data-add-pipeline-button-styling'));
const pluginsSupportingAnalytics = {};
const dashboard = new Dashboard();
const dashboardVM = new DashboardVM(dashboard);
const personalizeVM = new PersonalizeVM(currentView);
function queryObject() {
return m.parseQueryString(window.location.search);
}
/**
* A Stream-like function that manages the viewName state in the URL via the history API
* in order to facilitate tab switches without a full page load.
*
* Called with no arguments, this method returns the current view name; called with 1
* argument, it sets the new value as the current view (and forces the page to reflect
* that change).
*
* This API is built so that callers of this function need no knowledge of the current
* mithril route. The current route is preserved, and viewName can be independently set
* to make bookmarkable, stateful URLs.
*
* The differences from Stream are that 1) this really only works with String values
* and 2) one cannot use this in Stream.combine/merge/map because it cannot be registered
* as a dependency to another Stream.
*
* That said, it's worth noting that this *could* be equivalently implemented as a genuine
* Stream that is dependent on a vanilla Stream instance (by way of Sream.map or
* Stream.combine), but there's no practical benefit to this.
*
* Here's how it would look anyway:
*
* ```
* const viewName = Stream(queryObject().viewName);
* const currentView = viewName.map(function onUpdateValue(val) {
* // logic to build new URL and handle history, routing, etc
* // goes here.
* });
* ```
*/
function currentView(viewName, replace=false) {
const current = queryObject();
if (!arguments.length) { return current.viewName || personalizeVM.names()[0]; }
const route = window.location.hash.replace(/^#!/, "");
if (current.viewName !== viewName) {
const path = [
window.location.pathname,
viewName ? `?${m.buildQueryString($.extend({}, current, { viewName }))}` : "",
route ? `#!${route}` : ""
].join("");
history[replace ? "replaceState" : "pushState"](null, "", path);
if (route) {
m.route.set(route, null, {replace: true}); // force m.route() evaluation
}
}
personalizeVM.loadingView(true);
// Explicit set always refreshes; even if the viewName didn't change,
// we should refresh because the filter definition may have changed as
// currentView() is called after every personalization save operation.
repeater().restart();
}
$(document.body).on("click", () => {
dashboardVM.dropdown.hide();
personalizeVM.hideAllDropdowns();
/**
* The reason we need to do the redraw asynchronously is for checkboxes. When you click
* a checkbox the click event propogates to the body. But the model backing the checkboxes
* has not had time to update to the new value (so the redraw overrides the value with the
* original state). Using setTimeout() to make m.redraw() asynchronous allows mithril to
* flush the new checkbox state to the DOM beforehand.
*/
setTimeout(m.redraw, 0);
});
$(window).on("popstate", () => {
personalizeVM.activate(currentView());
});
function onResponse(dashboardData, message = undefined) {
personalizeVM.etag(dashboardData['_personalization']);
dashboard.initialize(dashboardData, showEmptyPipelineGroups);
dashboard.message(message);
}
function parseEtag(req) { return (req.getResponseHeader("ETag") || "").replace(/"/g, "").replace(/--(gzip|deflate)$/, ""); }
function createRepeater() {
const onsuccess = (data, _textStatus, jqXHR) => {
const etag = parseEtag(jqXHR);
if (jqXHR.status === 304) { return; }
if (jqXHR.status === 202) {
const message = {
type: "info",
content: data.message
};
onResponse({}, message);
return;
}
if (etag) {
dashboardVM.etag(etag);
}
onResponse(data);
};
const onerror = (jqXHR, textStatus, errorThrown) => {
// fix for issue #5391
//forcefully remove the ETag if server backup is in progress,
//so that on next dashboard request, the server will send a 200 and re-render the page
if (jqXHR.status === 503) {
dashboardVM.etag(null);
}
if (textStatus === 'parsererror') {
const message = {
type: "alert",
content: "Error occurred while parsing dashboard API response. Check server logs for more information."
};
onResponse({}, message);
console.error(errorThrown); // eslint-disable-line no-console
return;
}
if (jqXHR.responseJSON && jqXHR.responseJSON.message) {
const message = {
type: 'warning',
content: jqXHR.responseJSON.message,
};
onResponse({}, message);
return;
}
const message = {
type: 'warning',
content: 'There was an unknown error ',
};
onResponse({}, message);
};
return new AjaxPoller(() => Dashboard.get(currentView(), dashboardVM.etag(), true)
.then(onsuccess, onerror)
.always(() => {
personalizeVM.loadingView(false);
showSpinner(false);
}));
}
const repeater = Stream(createRepeater());
const showSpinner = Stream(true);
const renderView = () => {
const component = {
view() {
return m(DashboardWidget, {
personalizeVM,
showSpinner,
pluginsSupportingAnalytics,
shouldShowAnalyticsIcon,
useNewAddPipelineFlow,
addPipelineButtonStyling,
vm: dashboardVM,
doCancelPolling: () => repeater().stop(),
doRefreshImmediately: () => repeater().restart()
});
}
};
m.route(dashboardElem.get(0), '', {
'': component,
'/:searchedBy': component
});
dashboardVM.searchText(m.route.param('searchedBy') || '');
};
const onInitialAPIsResponse = (responses) => {
const pluginInfos = responses[1];
pluginInfos.eachPluginInfo((pluginInfo) => {
const supportedPipelineAnalytics = pluginInfo.extensions().analytics.capabilities().supportedPipelineAnalytics();
if (supportedPipelineAnalytics.length > 0) {
pluginsSupportingAnalytics[pluginInfo.id()] = supportedPipelineAnalytics[0].id;
}
});
renderView();
repeater().start();
};
const onInitialAPIsFailure = (response) => {
m.mount(dashboardElem.get(0), {
view() {
return (<PageLoadError message={response}/>);
}
});
};
Promise.all([personalizeVM.fetchPersonalization(), PluginInfos.all(null, {type: 'analytics'})]).then(onInitialAPIsResponse, onInitialAPIsFailure);
});
| naveenbhaskar/gocd | server/webapp/WEB-INF/rails/webpack/single_page_apps/new_dashboard.js | JavaScript | apache-2.0 | 8,583 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.