language
stringclasses
6 values
original_string
stringlengths
25
887k
text
stringlengths
25
887k
JavaScript
function deposit (amount, sign, { onOnChainTx, onOwnDepositLocked, onDepositLocked } = {}) { return new Promise((resolve, reject) => { enqueueAction( this, (channel, state) => state.handler === handlers.channelOpen, (channel, state) => { send(channel, { jsonrpc: '2.0', method: 'channels.deposit', params: { amount } }) return { handler: handlers.awaitingDepositTx, state: { sign, resolve, reject, onOnChainTx, onOwnDepositLocked, onDepositLocked } } } ) }) }
function deposit (amount, sign, { onOnChainTx, onOwnDepositLocked, onDepositLocked } = {}) { return new Promise((resolve, reject) => { enqueueAction( this, (channel, state) => state.handler === handlers.channelOpen, (channel, state) => { send(channel, { jsonrpc: '2.0', method: 'channels.deposit', params: { amount } }) return { handler: handlers.awaitingDepositTx, state: { sign, resolve, reject, onOnChainTx, onOwnDepositLocked, onDepositLocked } } } ) }) }
JavaScript
function createContract ({ code, callData, deposit, vmVersion, abiVersion }, sign) { return new Promise((resolve, reject) => { enqueueAction( this, (channel, state) => state.handler === handlers.channelOpen, (channel, state) => { send(channel, { jsonrpc: '2.0', method: 'channels.update.new_contract', params: { code, call_data: callData, deposit, vm_version: vmVersion, abi_version: abiVersion } }) return { handler: handlers.awaitingNewContractTx, state: { sign, resolve, reject } } } ) }) }
function createContract ({ code, callData, deposit, vmVersion, abiVersion }, sign) { return new Promise((resolve, reject) => { enqueueAction( this, (channel, state) => state.handler === handlers.channelOpen, (channel, state) => { send(channel, { jsonrpc: '2.0', method: 'channels.update.new_contract', params: { code, call_data: callData, deposit, vm_version: vmVersion, abi_version: abiVersion } }) return { handler: handlers.awaitingNewContractTx, state: { sign, resolve, reject } } } ) }) }
JavaScript
function callContract ({ amount, callData, contract, abiVersion }, sign) { return new Promise((resolve, reject) => { enqueueAction( this, (channel, state) => state.handler === handlers.channelOpen, (channel, state) => { send(channel, { jsonrpc: '2.0', method: 'channels.update.call_contract', params: { amount, call_data: callData, contract_id: contract, abi_version: abiVersion } }) return { handler: handlers.awaitingCallContractUpdateTx, state: { resolve, reject, sign } } } ) }) }
function callContract ({ amount, callData, contract, abiVersion }, sign) { return new Promise((resolve, reject) => { enqueueAction( this, (channel, state) => state.handler === handlers.channelOpen, (channel, state) => { send(channel, { jsonrpc: '2.0', method: 'channels.update.call_contract', params: { amount, call_data: callData, contract_id: contract, abi_version: abiVersion } }) return { handler: handlers.awaitingCallContractUpdateTx, state: { resolve, reject, sign } } } ) }) }
JavaScript
async function callContractStatic ({ amount, callData, contract, abiVersion }) { return snakeToPascalObjKeys(await call(this, 'channels.dry_run.call_contract', { amount, call_data: callData, contract_id: contract, abi_version: abiVersion })) }
async function callContractStatic ({ amount, callData, contract, abiVersion }) { return snakeToPascalObjKeys(await call(this, 'channels.dry_run.call_contract', { amount, call_data: callData, contract_id: contract, abi_version: abiVersion })) }
JavaScript
function cleanContractCalls () { return new Promise((resolve, reject) => { enqueueAction( this, (channel, state) => state.handler === handlers.channelOpen, (channel, state) => { send(channel, { jsonrpc: '2.0', method: 'channels.clean_contract_calls', params: {} }) return { handler: handlers.awaitingCallsPruned, state: { resolve, reject } } } ) }) }
function cleanContractCalls () { return new Promise((resolve, reject) => { enqueueAction( this, (channel, state) => state.handler === handlers.channelOpen, (channel, state) => { send(channel, { jsonrpc: '2.0', method: 'channels.clean_contract_calls', params: {} }) return { handler: handlers.awaitingCallsPruned, state: { resolve, reject } } } ) }) }
JavaScript
function sendMessage (message, recipient) { let info = message if (typeof message === 'object') { info = JSON.stringify(message) } const doSend = (channel) => send(channel, { jsonrpc: '2.0', method: 'channels.message', params: { info, to: recipient } }) if (this.status() === 'connecting') { const onStatusChanged = (status) => { if (status !== 'connecting') { // For some reason we can't immediately send a message when connection is // established. Thus we wait 500ms which seems to work. setTimeout(() => doSend(this), 500) this.off('statusChanged', onStatusChanged) } } this.on('statusChanged', onStatusChanged) } else { doSend(this) } }
function sendMessage (message, recipient) { let info = message if (typeof message === 'object') { info = JSON.stringify(message) } const doSend = (channel) => send(channel, { jsonrpc: '2.0', method: 'channels.message', params: { info, to: recipient } }) if (this.status() === 'connecting') { const onStatusChanged = (status) => { if (status !== 'connecting') { // For some reason we can't immediately send a message when connection is // established. Thus we wait 500ms which seems to work. setTimeout(() => doSend(this), 500) this.off('statusChanged', onStatusChanged) } } this.on('statusChanged', onStatusChanged) } else { doSend(this) } }
JavaScript
function uploadToS3(WaterDuration, key) { // super secret EXTREMELY insecure password to prevent spamming from open internet // this function by definition is not secure, it is a proof of concept // ----- CHANGE THIS before running ----- if(key == "examplekey"){ // -------------------------------------- // Create params for putObject call jsonData["frontend"]["duration"] = WaterDuration jsonData["frontend"]["willWater"] = "True" var objectParams = {Bucket: bucketName, Key: keyName, Body: JSON.stringify(jsonData), ContentType: "application/json"} // Create object upload promise var uploadPromise = new AWS.S3({apiVersion: '2006-03-01'}).putObject(objectParams).promise(); uploadPromise.then( function(data) { console.log("Successfully uploaded data: " + WaterDuration + " to " + bucketName + "/" + keyName); })}}
function uploadToS3(WaterDuration, key) { // super secret EXTREMELY insecure password to prevent spamming from open internet // this function by definition is not secure, it is a proof of concept // ----- CHANGE THIS before running ----- if(key == "examplekey"){ // -------------------------------------- // Create params for putObject call jsonData["frontend"]["duration"] = WaterDuration jsonData["frontend"]["willWater"] = "True" var objectParams = {Bucket: bucketName, Key: keyName, Body: JSON.stringify(jsonData), ContentType: "application/json"} // Create object upload promise var uploadPromise = new AWS.S3({apiVersion: '2006-03-01'}).putObject(objectParams).promise(); uploadPromise.then( function(data) { console.log("Successfully uploaded data: " + WaterDuration + " to " + bucketName + "/" + keyName); })}}
JavaScript
function shuffle(array, len) { for (let i = 0; i < len; i++) { const j = rani(0,i); const tmp = array[i]; array[i] = array[j]; array[j] = tmp; } }
function shuffle(array, len) { for (let i = 0; i < len; i++) { const j = rani(0,i); const tmp = array[i]; array[i] = array[j]; array[j] = tmp; } }
JavaScript
function generate_color(color) { color[0] = 0; color[1] = 255; color[2] = rani(0,255); shuffle(color, 3); }
function generate_color(color) { color[0] = 0; color[1] = 255; color[2] = rani(0,255); shuffle(color, 3); }
JavaScript
function reset_level() { generate_color(Level.previous_color); for (let i = 0; i < Settings.difficulty.carvers; i++) { Level.carvers[i] = rani(0, (Settings.game.sectors / Settings.game.ships) - 1); } Level.carvers_to_merge = 0; Level.difficulty.carvers = Settings.difficulty.carvers; Level.difficulty.uncarved_safe_chance = Settings.difficulty.uncarved_safe_chance; Level.difficulty.transition_length = Settings.difficulty.transition_length; for (let i = 0; i < Settings.game.sectors; i++) { Level.safe_path[i] = Level.difficulty.transition_length; } }
function reset_level() { generate_color(Level.previous_color); for (let i = 0; i < Settings.difficulty.carvers; i++) { Level.carvers[i] = rani(0, (Settings.game.sectors / Settings.game.ships) - 1); } Level.carvers_to_merge = 0; Level.difficulty.carvers = Settings.difficulty.carvers; Level.difficulty.uncarved_safe_chance = Settings.difficulty.uncarved_safe_chance; Level.difficulty.transition_length = Settings.difficulty.transition_length; for (let i = 0; i < Settings.game.sectors; i++) { Level.safe_path[i] = Level.difficulty.transition_length; } }
JavaScript
function increase_difficulty() { Level.difficulty.uncarved_safe_chance += Settings.difficulty.increase.uncarved_safe_chance; Level.difficulty.transition_length += Settings.difficulty.increase.transition_length; Level.carvers_to_merge -= Settings.difficulty.increase.carvers; }
function increase_difficulty() { Level.difficulty.uncarved_safe_chance += Settings.difficulty.increase.uncarved_safe_chance; Level.difficulty.transition_length += Settings.difficulty.increase.transition_length; Level.carvers_to_merge -= Settings.difficulty.increase.carvers; }
JavaScript
function generate_rings(colors, offset = 0) { const last_carver = Level.difficulty.carvers - 1; const sectors_per_ship = (Settings.game.sectors / Settings.game.ships); const length = rani(Settings.game.color_transitions.min, Settings.game.color_transitions.max); const color = Array.from(Level.previous_color); const next_color = []; generate_color(next_color); Level.previous_color = next_color; const rstep = (next_color[0] - color[0]) / length; const gstep = (next_color[1] - color[1]) / length; const bstep = (next_color[2] - color[2]) / length; //For each generated ring for (let r = 0; r < length; r++) { //For each active carver for (let c = 0; c < Level.difficulty.carvers; c++) { //Carve a safe path for (let s = 0; s < Settings.game.ships; s++) { const sector = Level.carvers[c] + s * sectors_per_ship; Level.safe_path[sector] = Level.difficulty.transition_length + 1; } //Move the carver randomly let sector = (Level.carvers[c] + rani(-1,1)) % sectors_per_ship; if (sector < 0) { sector += sectors_per_ship; } Level.carvers[c] = sector; //Merge the last carver into this one if requested (difficulty increase) and possible (same place) if (Level.carvers_to_merge && c != last_carver && Level.carvers[c] == Level.carvers[last_carver]) { Level.difficulty.carvers--; Level.carvers_to_merge--; } } color[0] += rstep; color[1] += gstep; color[2] += bstep; for (let s = 0; s < Settings.game.sectors; s++) { const pos = offset + (r * Settings.game.sectors + s) * 4; colors[pos + 0] = color[0]; colors[pos + 1] = color[1]; colors[pos + 2] = color[2]; colors[pos + 3] = rani(153,255); if (Level.safe_path[s]) { Level.safe_path[s]--; } else if (ranf() > Level.difficulty.uncarved_safe_chance) { colors[pos + 3] = 0; } } } return length; }
function generate_rings(colors, offset = 0) { const last_carver = Level.difficulty.carvers - 1; const sectors_per_ship = (Settings.game.sectors / Settings.game.ships); const length = rani(Settings.game.color_transitions.min, Settings.game.color_transitions.max); const color = Array.from(Level.previous_color); const next_color = []; generate_color(next_color); Level.previous_color = next_color; const rstep = (next_color[0] - color[0]) / length; const gstep = (next_color[1] - color[1]) / length; const bstep = (next_color[2] - color[2]) / length; //For each generated ring for (let r = 0; r < length; r++) { //For each active carver for (let c = 0; c < Level.difficulty.carvers; c++) { //Carve a safe path for (let s = 0; s < Settings.game.ships; s++) { const sector = Level.carvers[c] + s * sectors_per_ship; Level.safe_path[sector] = Level.difficulty.transition_length + 1; } //Move the carver randomly let sector = (Level.carvers[c] + rani(-1,1)) % sectors_per_ship; if (sector < 0) { sector += sectors_per_ship; } Level.carvers[c] = sector; //Merge the last carver into this one if requested (difficulty increase) and possible (same place) if (Level.carvers_to_merge && c != last_carver && Level.carvers[c] == Level.carvers[last_carver]) { Level.difficulty.carvers--; Level.carvers_to_merge--; } } color[0] += rstep; color[1] += gstep; color[2] += bstep; for (let s = 0; s < Settings.game.sectors; s++) { const pos = offset + (r * Settings.game.sectors + s) * 4; colors[pos + 0] = color[0]; colors[pos + 1] = color[1]; colors[pos + 2] = color[2]; colors[pos + 3] = rani(153,255); if (Level.safe_path[s]) { Level.safe_path[s]--; } else if (ranf() > Level.difficulty.uncarved_safe_chance) { colors[pos + 3] = 0; } } } return length; }
JavaScript
function reset_music() { AudioData.music.pause(); AudioData.music.currentTime = 0; }
function reset_music() { AudioData.music.pause(); AudioData.music.currentTime = 0; }
JavaScript
function UserAdd(name, lastname, phone, state, email, password, passwordTwo) { let nameValue = name.value; let lastValue = lastname.value; let phoneValue = phone.value; let stateValue = state.value; let emailValue = email.value; let pass1Value = password.value; let pass2Value = passwordTwo.value; // valida nombre let text = /^[a-zA-ZÀ-ÿ\s]{1,40}$/; let textName; let condition = true; if (nameValue === "" || !text.test(nameValue)) { textName = `<div class="alert alert-danger" role="alert">¡Nombre inválido!</div>`; condition = false; } else if (nameValue.length <= 3) { textName = `<div class="alert alert-danger" role="alert">¡Nombre menor a 4 caracteres!</div>`; condition = false; } else { textName = `<div class="alert alert-success" role="alert">¡Nombre válido!</div>`; } document.getElementById("nombreDemo").innerHTML = textName; // valida apellido if (lastValue === "" || !text.test(lastValue)) { textName = `<div class="alert alert-danger" role="alert">¡Apellido inválido!</div>`; condition = false; }else if (nameValue.length <= 3) { textName = `<div class="alert alert-danger" role="alert">¡Apellido menor a 4 caracteres!</div>`; condition = false; } else { textName = `<div class="alert alert-success" role="alert">¡Apellido válido!</div>`; } document.getElementById("apellidoDemo").innerHTML = textName; // Validar Telefono let num = /[^+\d]/g; if (phoneValue === "" || num.test(phoneValue)) { textName = `<div class="alert alert-danger" role="alert">¡Telefóno inválido!</div>`; condition = false; } else if (phoneValue.length <= 9) { textName = `<div class="alert alert-danger" role="alert">¡Telefóno menor a 10 dígitos!</div>`; condition = false; } else if (phoneValue.length >= 11) { textName = `<div class="alert alert-danger" role="alert">¡Telefóno mayor a 10 dígitos!</div>`; condition = false; } else { textName = `<div class="alert alert-success" role="alert">¡Teléfono válido!</div>`; } document.getElementById("telefonoDemo").innerHTML = textName; // Validar Estado if (stateValue === null || stateValue == 0) { textName = `<div class="alert alert-danger" role="alert">¡Estado no seleccionado!</div>`; condition = false; } else { textName = `<div class="alert alert-success" role="alert">¡Estado válido!</div>`; } document.getElementById("estadoDemo").innerHTML = textName; // Validar Correo let emailVal = /^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/; if (emailValue === "" || !emailVal.test(emailValue)) { textName = `<div class="alert alert-danger" role="alert">¡Correo inválido!</div>`; condition = false; } else { textName = `<div class="alert alert-success" role="alert">¡Correo válido!</div>`; } document.getElementById("correoDemo").innerHTML = textName; // Validar Contraseña //No haya espacios en blanco let spaces = false; let cont = 0; while (!spaces && (cont < pass1Value.length)) { if (pass1Value.charAt(cont) == " ") spaces = true; cont++; textName = `<div class="alert alert-success" role="alert">¡Contraseña válida!</div>`; } document.getElementById("contraseñaDemo").innerHTML = textName; if (spaces) { textName = `<div class="alert alert-danger" role="alert">¡No pueden existir campos vacíos!</div>`; condition = false; } //Que no haya dejado campos vacios if (pass1Value.length == 0 || pass2Value.length == 0) { textName = `<div class="alert alert-danger" role="alert">¡No pueden existir campos vacíos!</div>`; condition = false; } document.getElementById("contraseñaDemo").innerHTML = textName; document.getElementById("confirmacionDemo").innerHTML = textName; //Validar longitud de contraseña if (pass1Value.length <= 8) { textName = `<div class="alert alert-danger" role="alert">¡La contraseña debe ser mayor de 8 carácteres!</div>`; condition = false; } else { textName = `<div class="alert alert-success" role="alert">¡Todo correcto!</div>`; } document.getElementById("contraseñaDemo").innerHTML = textName; document.getElementById("confirmacionDemo").innerHTML = textName; //Que ambas contraseñas coincidan if (pass1Value != pass2Value) { textName = `<div class="alert alert-danger" role="alert">¡Las contraseñas no coinciden!</div>`; condition = false; } else if (pass1Value === pass2Value && pass2Value.length != 0 && pass2Value.charAt(cont) == " ") { textName = `<div class="alert alert-success" role="alert">¡Todo correcto!</div>`; } document.getElementById("contraseñaDemo").innerHTML = textName; document.getElementById("confirmacionDemo").innerHTML = textName; /* Agregar a Local Storage */ if (condition === true) { let newUser = { "_id": arrayUsers.length, "name": name.value, "lastname": lastname.value, "phone": phone.value, "state": state.value, "email": email.value, "password": password.value, }; arrayUsers.push(newUser); let jsonUsers = JSON.stringify(arrayUsers); localStorage.setItem("users", jsonUsers); name.value = ""; lastname.value = ""; phone.value = ""; state.value = ""; email.value = ""; password.value = ""; Swal.fire({ icon: 'success', title: '¡Éxito!', text: '¡Usuario registrado!', footer: '<a href="../index.html">Volver al inicio</a>' }) } else { Swal.fire({ icon: 'error', title: '¡Falló!', text: '¡Reintenta de nuevo!', }) } }
function UserAdd(name, lastname, phone, state, email, password, passwordTwo) { let nameValue = name.value; let lastValue = lastname.value; let phoneValue = phone.value; let stateValue = state.value; let emailValue = email.value; let pass1Value = password.value; let pass2Value = passwordTwo.value; // valida nombre let text = /^[a-zA-ZÀ-ÿ\s]{1,40}$/; let textName; let condition = true; if (nameValue === "" || !text.test(nameValue)) { textName = `<div class="alert alert-danger" role="alert">¡Nombre inválido!</div>`; condition = false; } else if (nameValue.length <= 3) { textName = `<div class="alert alert-danger" role="alert">¡Nombre menor a 4 caracteres!</div>`; condition = false; } else { textName = `<div class="alert alert-success" role="alert">¡Nombre válido!</div>`; } document.getElementById("nombreDemo").innerHTML = textName; // valida apellido if (lastValue === "" || !text.test(lastValue)) { textName = `<div class="alert alert-danger" role="alert">¡Apellido inválido!</div>`; condition = false; }else if (nameValue.length <= 3) { textName = `<div class="alert alert-danger" role="alert">¡Apellido menor a 4 caracteres!</div>`; condition = false; } else { textName = `<div class="alert alert-success" role="alert">¡Apellido válido!</div>`; } document.getElementById("apellidoDemo").innerHTML = textName; // Validar Telefono let num = /[^+\d]/g; if (phoneValue === "" || num.test(phoneValue)) { textName = `<div class="alert alert-danger" role="alert">¡Telefóno inválido!</div>`; condition = false; } else if (phoneValue.length <= 9) { textName = `<div class="alert alert-danger" role="alert">¡Telefóno menor a 10 dígitos!</div>`; condition = false; } else if (phoneValue.length >= 11) { textName = `<div class="alert alert-danger" role="alert">¡Telefóno mayor a 10 dígitos!</div>`; condition = false; } else { textName = `<div class="alert alert-success" role="alert">¡Teléfono válido!</div>`; } document.getElementById("telefonoDemo").innerHTML = textName; // Validar Estado if (stateValue === null || stateValue == 0) { textName = `<div class="alert alert-danger" role="alert">¡Estado no seleccionado!</div>`; condition = false; } else { textName = `<div class="alert alert-success" role="alert">¡Estado válido!</div>`; } document.getElementById("estadoDemo").innerHTML = textName; // Validar Correo let emailVal = /^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/; if (emailValue === "" || !emailVal.test(emailValue)) { textName = `<div class="alert alert-danger" role="alert">¡Correo inválido!</div>`; condition = false; } else { textName = `<div class="alert alert-success" role="alert">¡Correo válido!</div>`; } document.getElementById("correoDemo").innerHTML = textName; // Validar Contraseña //No haya espacios en blanco let spaces = false; let cont = 0; while (!spaces && (cont < pass1Value.length)) { if (pass1Value.charAt(cont) == " ") spaces = true; cont++; textName = `<div class="alert alert-success" role="alert">¡Contraseña válida!</div>`; } document.getElementById("contraseñaDemo").innerHTML = textName; if (spaces) { textName = `<div class="alert alert-danger" role="alert">¡No pueden existir campos vacíos!</div>`; condition = false; } //Que no haya dejado campos vacios if (pass1Value.length == 0 || pass2Value.length == 0) { textName = `<div class="alert alert-danger" role="alert">¡No pueden existir campos vacíos!</div>`; condition = false; } document.getElementById("contraseñaDemo").innerHTML = textName; document.getElementById("confirmacionDemo").innerHTML = textName; //Validar longitud de contraseña if (pass1Value.length <= 8) { textName = `<div class="alert alert-danger" role="alert">¡La contraseña debe ser mayor de 8 carácteres!</div>`; condition = false; } else { textName = `<div class="alert alert-success" role="alert">¡Todo correcto!</div>`; } document.getElementById("contraseñaDemo").innerHTML = textName; document.getElementById("confirmacionDemo").innerHTML = textName; //Que ambas contraseñas coincidan if (pass1Value != pass2Value) { textName = `<div class="alert alert-danger" role="alert">¡Las contraseñas no coinciden!</div>`; condition = false; } else if (pass1Value === pass2Value && pass2Value.length != 0 && pass2Value.charAt(cont) == " ") { textName = `<div class="alert alert-success" role="alert">¡Todo correcto!</div>`; } document.getElementById("contraseñaDemo").innerHTML = textName; document.getElementById("confirmacionDemo").innerHTML = textName; /* Agregar a Local Storage */ if (condition === true) { let newUser = { "_id": arrayUsers.length, "name": name.value, "lastname": lastname.value, "phone": phone.value, "state": state.value, "email": email.value, "password": password.value, }; arrayUsers.push(newUser); let jsonUsers = JSON.stringify(arrayUsers); localStorage.setItem("users", jsonUsers); name.value = ""; lastname.value = ""; phone.value = ""; state.value = ""; email.value = ""; password.value = ""; Swal.fire({ icon: 'success', title: '¡Éxito!', text: '¡Usuario registrado!', footer: '<a href="../index.html">Volver al inicio</a>' }) } else { Swal.fire({ icon: 'error', title: '¡Falló!', text: '¡Reintenta de nuevo!', }) } }
JavaScript
function validationForm(name, lastName, state, telephone, email, message) { let nameValue = name.value; let lastValue = lastName.value; let stateValue = state.value; let phoneValue = telephone.value; let emailValue = email.value; let messageValue = message.value; // Validar Nombre let text = /^[a-zA-ZÀ-ÿ\s]{1,40}$/; let textName; let condition = true; if (nameValue === "" || !text.test(nameValue)) { textName = `<div class="alert alert-danger" role="alert">¡Nombre inválido! </div>`; } else if (nameValue.length <= 3) { textName = `<div class="alert alert-danger" role="alert">¡Nombre menor a 4 caracteres!</div>`; condition = false; } else { textName = `<div class="alert alert-success" role="alert">¡Nombre válido!</div>`; } document.getElementById("nameDemo").innerHTML = textName; // Validar Apellido if (lastValue === "" || !text.test(lastValue)) { textName = `<div class="alert alert-danger" role="alert">¡Apellido inválido! </div>`; } else if (nameValue.length <= 3) { textName = `<div class="alert alert-danger" role="alert">¡Apellido menor a 4 caracteres!</div>`; condition = false; } else { textName = `<div class="alert alert-success" role="alert">¡Apellido válido!</div>`; } document.getElementById("lastNameDemo").innerHTML = textName; // Validar Estado if (stateValue === "") { textName = `<div class="alert alert-danger" role="alert">¡Estado no seleccionado! </div>`; } else { textName = `<div class="alert alert-success" role="alert">¡Estado válido!</div>`; } document.getElementById("stdDemo").innerHTML = textName; // Validar Telefono let num = /[^+\d]/g; if (phoneValue === "" || num.test(phoneValue)) { textName = `<div class="alert alert-danger" role="alert">¡Telefóno inválido!</div>`; condition = false; } else if (phoneValue.length <= 9) { textName = `<div class="alert alert-danger" role="alert">¡Telefóno menor a 10 dígitos!</div>`; condition = false; } else if (phoneValue.length >= 11) { textName = `<div class="alert alert-danger" role="alert">¡Telefóno mayor a 10 dígitos!</div>`; condition = false; } else { textName = `<div class="alert alert-success" role="alert">¡Teléfono válido!</div>`; } document.getElementById("telephoneDemo").innerHTML = textName; // Validar Correo let emailVal = /^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/; if (emailValue === "" || !emailVal.test(emailValue)) { textName = `<div class="alert alert-danger" role="alert">¡Correo inválido! </div>`; condition = false; } else { textName = `<div class="alert alert-success" role="alert">¡Correo válido!</div>`; } document.getElementById("emailDemo").innerHTML = textName; // Validar Message if (messageValue === "" || /^\s+$/.test(messageValue)) { textName = `<div class="alert alert-danger" role="alert">¡Mensaje inválido! </div>`; condition = false; } else { textName = `<div class="alert alert-success" role="alert">¡Mensaje válido!</div>`; } document.getElementById("menssageDemo").innerHTML = textName; if (condition === true) { Swal.fire({ icon: 'success', title: '¡Éxito!', text: '¡Correo Enviado!', footer: '<a href="../index.html">Volver al inicio</a>' }) } else { Swal.fire({ icon: 'error', title: '¡Falló!', text: '¡Reintenta de nuevo!', }) } }
function validationForm(name, lastName, state, telephone, email, message) { let nameValue = name.value; let lastValue = lastName.value; let stateValue = state.value; let phoneValue = telephone.value; let emailValue = email.value; let messageValue = message.value; // Validar Nombre let text = /^[a-zA-ZÀ-ÿ\s]{1,40}$/; let textName; let condition = true; if (nameValue === "" || !text.test(nameValue)) { textName = `<div class="alert alert-danger" role="alert">¡Nombre inválido! </div>`; } else if (nameValue.length <= 3) { textName = `<div class="alert alert-danger" role="alert">¡Nombre menor a 4 caracteres!</div>`; condition = false; } else { textName = `<div class="alert alert-success" role="alert">¡Nombre válido!</div>`; } document.getElementById("nameDemo").innerHTML = textName; // Validar Apellido if (lastValue === "" || !text.test(lastValue)) { textName = `<div class="alert alert-danger" role="alert">¡Apellido inválido! </div>`; } else if (nameValue.length <= 3) { textName = `<div class="alert alert-danger" role="alert">¡Apellido menor a 4 caracteres!</div>`; condition = false; } else { textName = `<div class="alert alert-success" role="alert">¡Apellido válido!</div>`; } document.getElementById("lastNameDemo").innerHTML = textName; // Validar Estado if (stateValue === "") { textName = `<div class="alert alert-danger" role="alert">¡Estado no seleccionado! </div>`; } else { textName = `<div class="alert alert-success" role="alert">¡Estado válido!</div>`; } document.getElementById("stdDemo").innerHTML = textName; // Validar Telefono let num = /[^+\d]/g; if (phoneValue === "" || num.test(phoneValue)) { textName = `<div class="alert alert-danger" role="alert">¡Telefóno inválido!</div>`; condition = false; } else if (phoneValue.length <= 9) { textName = `<div class="alert alert-danger" role="alert">¡Telefóno menor a 10 dígitos!</div>`; condition = false; } else if (phoneValue.length >= 11) { textName = `<div class="alert alert-danger" role="alert">¡Telefóno mayor a 10 dígitos!</div>`; condition = false; } else { textName = `<div class="alert alert-success" role="alert">¡Teléfono válido!</div>`; } document.getElementById("telephoneDemo").innerHTML = textName; // Validar Correo let emailVal = /^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/; if (emailValue === "" || !emailVal.test(emailValue)) { textName = `<div class="alert alert-danger" role="alert">¡Correo inválido! </div>`; condition = false; } else { textName = `<div class="alert alert-success" role="alert">¡Correo válido!</div>`; } document.getElementById("emailDemo").innerHTML = textName; // Validar Message if (messageValue === "" || /^\s+$/.test(messageValue)) { textName = `<div class="alert alert-danger" role="alert">¡Mensaje inválido! </div>`; condition = false; } else { textName = `<div class="alert alert-success" role="alert">¡Mensaje válido!</div>`; } document.getElementById("menssageDemo").innerHTML = textName; if (condition === true) { Swal.fire({ icon: 'success', title: '¡Éxito!', text: '¡Correo Enviado!', footer: '<a href="../index.html">Volver al inicio</a>' }) } else { Swal.fire({ icon: 'error', title: '¡Falló!', text: '¡Reintenta de nuevo!', }) } }
JavaScript
function servicesAdd(title, tipe, description, image) { let titleValue = title.value; let tipeValue = tipe.value; let descriptionValue = description.value; let imageValue = image.value; // valida titulo let text = /^[a-zA-ZÀ-ÿ\s]{1,40}$/; let textName; let condition = true; if (titleValue === "" || titleValue.length <= 10 || !text.test(titleValue)) { textName = `<div class="alert alert-danger" role="alert">¡Título inválido! </div>`; condition = false; } else { textName = `<div class="alert alert-success" role="alert">¡Título válido!</div>`; } document.getElementById("serviceDemo").innerHTML = textName; // valida tipo if (tipeValue === "") { textName = `<div class="alert alert-danger" role="alert">¡Elige un tipo de servicio! </div>`; condition = false; } else { textName = `<div class="alert alert-success" role="alert">¡Tipo de servicio válido!</div>`; } document.getElementById("tipeDemo").innerHTML = textName; // valida Descripcion if (descriptionValue === "" || descriptionValue.length <= 20 || /^\s+$/.test(description)) { textName = `<div class="alert alert-danger" role="alert">¡Ingresa una descripción! </div>`; condition = false; } else { textName = `<div class="alert alert-success" role="alert">¡Descripción válida!</div>`; } document.getElementById("descriptionDemo").innerHTML = textName; // valida imagen if (imageValue === "") { textName = `<div class="alert alert-danger" role="alert">¡Agrega una imagen! </div>`; condition = false; } else { textName = `<div class="alert alert-success" role="alert">¡Imagen válida!</div>`; } document.getElementById("imageDemo").innerHTML = textName; if (condition === true && tipe.value == "Terapia") { let newService = { "_id": arrayService.length + 1, "title": title.value, "tipe": tipe.value, "description": description.value, "image": image.value.substr(12) }; arrayService.push(newService); let jsonServices = JSON.stringify(arrayService); localStorage.setItem("services", jsonServices); Swal.fire({ icon: 'success', title: '¡Éxito!', text: '¡Se agregó el servicio!', footer: '<a href="./servicios.html">Ir a servicios</a>' }); } else if(condition === true && tipe.value == "Taller"){ let newTaller = { "_id": arrayTaller.length + 1, "title": title.value, "tipe": tipe.value, "description": description.value, "image": image.value.substr(12) }; arrayTaller.push(newTaller); let jsonTaller = JSON.stringify(arrayTaller); localStorage.setItem("talleres", jsonTaller); Swal.fire({ icon: 'success', title: '¡Éxito!', text: '¡Se agregó el servicio!', footer: '<a href="./servicios.html">Ir a servicios</a>' }); }else { Swal.fire({ icon: 'error', title: '¡Falló!', text: '¡No se agregó el servicio!', }) } }
function servicesAdd(title, tipe, description, image) { let titleValue = title.value; let tipeValue = tipe.value; let descriptionValue = description.value; let imageValue = image.value; // valida titulo let text = /^[a-zA-ZÀ-ÿ\s]{1,40}$/; let textName; let condition = true; if (titleValue === "" || titleValue.length <= 10 || !text.test(titleValue)) { textName = `<div class="alert alert-danger" role="alert">¡Título inválido! </div>`; condition = false; } else { textName = `<div class="alert alert-success" role="alert">¡Título válido!</div>`; } document.getElementById("serviceDemo").innerHTML = textName; // valida tipo if (tipeValue === "") { textName = `<div class="alert alert-danger" role="alert">¡Elige un tipo de servicio! </div>`; condition = false; } else { textName = `<div class="alert alert-success" role="alert">¡Tipo de servicio válido!</div>`; } document.getElementById("tipeDemo").innerHTML = textName; // valida Descripcion if (descriptionValue === "" || descriptionValue.length <= 20 || /^\s+$/.test(description)) { textName = `<div class="alert alert-danger" role="alert">¡Ingresa una descripción! </div>`; condition = false; } else { textName = `<div class="alert alert-success" role="alert">¡Descripción válida!</div>`; } document.getElementById("descriptionDemo").innerHTML = textName; // valida imagen if (imageValue === "") { textName = `<div class="alert alert-danger" role="alert">¡Agrega una imagen! </div>`; condition = false; } else { textName = `<div class="alert alert-success" role="alert">¡Imagen válida!</div>`; } document.getElementById("imageDemo").innerHTML = textName; if (condition === true && tipe.value == "Terapia") { let newService = { "_id": arrayService.length + 1, "title": title.value, "tipe": tipe.value, "description": description.value, "image": image.value.substr(12) }; arrayService.push(newService); let jsonServices = JSON.stringify(arrayService); localStorage.setItem("services", jsonServices); Swal.fire({ icon: 'success', title: '¡Éxito!', text: '¡Se agregó el servicio!', footer: '<a href="./servicios.html">Ir a servicios</a>' }); } else if(condition === true && tipe.value == "Taller"){ let newTaller = { "_id": arrayTaller.length + 1, "title": title.value, "tipe": tipe.value, "description": description.value, "image": image.value.substr(12) }; arrayTaller.push(newTaller); let jsonTaller = JSON.stringify(arrayTaller); localStorage.setItem("talleres", jsonTaller); Swal.fire({ icon: 'success', title: '¡Éxito!', text: '¡Se agregó el servicio!', footer: '<a href="./servicios.html">Ir a servicios</a>' }); }else { Swal.fire({ icon: 'error', title: '¡Falló!', text: '¡No se agregó el servicio!', }) } }
JavaScript
function isResponseSuccessful(status) { // An http 4xx or 5xx error. Signal an error. if (status === 0 || (status > 399 && status < 600)) { return false } return true }
function isResponseSuccessful(status) { // An http 4xx or 5xx error. Signal an error. if (status === 0 || (status > 399 && status < 600)) { return false } return true }
JavaScript
function handleAutoComplete({ currentTarget: { value } }) { // If we're typing a command, handle that and return if (value.startsWith("!")) { // Get the value after the !, in lowercase const search = value.slice(1).toLowerCase(); // Filter all of our commands by search const results = Object.keys(commands).filter(cmd => ~cmd.indexOf(search)); // Create an empty components array const components = []; // Iterate our results and push them to the components array for (const result of results) { const command = commands[result]; components.push( <div className="Item" key={result} onClick={() => fieldRef.current.value = "!" + result}> <FontAwesomeIcon icon={faTerminal}/> <span><b>!{result}</b><span style={{ opacity: 0.5 }}> - {command.description}</span></span> </div> ); setAutoCompleteEntries(components); } return; } // Put our raw path through the variable checks const fpRaw = getPathFromString(value); // Get the second to last path entry, to exclude what we're searching const fpDir = fpRaw.split("/").slice(0, -1).join("/"); // If the fp doesn't exist, but the dir does, set fp to dir const fp = !fs.existsSync(fpRaw) && fs.existsSync(fpDir) ? fpDir : fpRaw; // dir exists, get its files if (value && fs.existsSync(fp)) { // Read all files in the directory, filtered by searching the final path entry const files = fs.readdirSync(fp).filter(p => ~path.join(fp, p).toLowerCase().indexOf(fpRaw.split("/").slice(-1)[0].toLowerCase())); // Map the first 10 files into auto complete entry components const components = files.slice(0, 10).map(fn => ( <div className="Item" key={fn} onClick={() => fieldRef.current.value = path.join(fp, fn)}> <FontAwesomeIcon icon={fs.lstatSync(path.join(fp, fn)).isDirectory() ? faFolder : faFile}/> <span>{fn}</span> </div> )); // Set our entries to the components list setAutoCompleteEntries(components); } // If the directory doesn't exist, clear our entries else setAutoCompleteEntries([]); }
function handleAutoComplete({ currentTarget: { value } }) { // If we're typing a command, handle that and return if (value.startsWith("!")) { // Get the value after the !, in lowercase const search = value.slice(1).toLowerCase(); // Filter all of our commands by search const results = Object.keys(commands).filter(cmd => ~cmd.indexOf(search)); // Create an empty components array const components = []; // Iterate our results and push them to the components array for (const result of results) { const command = commands[result]; components.push( <div className="Item" key={result} onClick={() => fieldRef.current.value = "!" + result}> <FontAwesomeIcon icon={faTerminal}/> <span><b>!{result}</b><span style={{ opacity: 0.5 }}> - {command.description}</span></span> </div> ); setAutoCompleteEntries(components); } return; } // Put our raw path through the variable checks const fpRaw = getPathFromString(value); // Get the second to last path entry, to exclude what we're searching const fpDir = fpRaw.split("/").slice(0, -1).join("/"); // If the fp doesn't exist, but the dir does, set fp to dir const fp = !fs.existsSync(fpRaw) && fs.existsSync(fpDir) ? fpDir : fpRaw; // dir exists, get its files if (value && fs.existsSync(fp)) { // Read all files in the directory, filtered by searching the final path entry const files = fs.readdirSync(fp).filter(p => ~path.join(fp, p).toLowerCase().indexOf(fpRaw.split("/").slice(-1)[0].toLowerCase())); // Map the first 10 files into auto complete entry components const components = files.slice(0, 10).map(fn => ( <div className="Item" key={fn} onClick={() => fieldRef.current.value = path.join(fp, fn)}> <FontAwesomeIcon icon={fs.lstatSync(path.join(fp, fn)).isDirectory() ? faFolder : faFile}/> <span>{fn}</span> </div> )); // Set our entries to the components list setAutoCompleteEntries(components); } // If the directory doesn't exist, clear our entries else setAutoCompleteEntries([]); }
JavaScript
async createMarketBuyOrder(symbol, orderPrice, secondsPerIteration=SECONDS_PER_BUY_ITERATION) { let lastPrice = await this.getLastPrice(symbol) this._upsertCoininfo(symbol, lastPrice) // make sure what we buy does not gets sold (trailing stop) before we know we have it here for (let priceFactor = MIN_PRICE_FACTOR;priceFactor <= MAX_PRICE_FACTOR;priceFactor *= PRICE_FACTOR_FACTOR, lastPrice = await this.getLastPrice(symbol)) { const price = lastPrice * (1 + priceFactor) const amount = orderPrice / price log.info('exchange.createMarketBuyOrder', 'Market buy %s %s at %s [last: %s factor %s]', amount, symbol, price, lastPrice, (1 + priceFactor)); const result = await this.exchange.createLimitBuyOrder(symbol, amount, price) const orderId = result.id if (!orderId) { // cryptopia? this.setStatus(orderId, 'done', 'exchange.createMarketBuyOrder. Market buy order filled immediately') return } // this.log('sleep', secondsPerIteration) await sleep(secondsPerIteration * time.SECOND) secondsPerIteration *= SLEEP_FACTOR // just some number to make this work on slow exchanges also try { const order = await this.exchange.fetchOrder(orderId, symbol) if (order.remaining <= 0) { this.setStatus(orderId, 'done', 'exchange.createMarketBuyOrder. Market buy order filled') return } } catch (ex) { this.setStatus(orderId, 'done', 'exchange.createMarketBuyOrder. Assuming market buy order filled') return } // this.log('order.remaining', order.remaining) // JSON.stringify(order, null, 4)) await this.cancelOrder(orderId) } // next priceFactor this.setStatus(orderId, 'failed', 'exchange.createMarketBuyOrder. Market buy order not filled') } // end of buy()
async createMarketBuyOrder(symbol, orderPrice, secondsPerIteration=SECONDS_PER_BUY_ITERATION) { let lastPrice = await this.getLastPrice(symbol) this._upsertCoininfo(symbol, lastPrice) // make sure what we buy does not gets sold (trailing stop) before we know we have it here for (let priceFactor = MIN_PRICE_FACTOR;priceFactor <= MAX_PRICE_FACTOR;priceFactor *= PRICE_FACTOR_FACTOR, lastPrice = await this.getLastPrice(symbol)) { const price = lastPrice * (1 + priceFactor) const amount = orderPrice / price log.info('exchange.createMarketBuyOrder', 'Market buy %s %s at %s [last: %s factor %s]', amount, symbol, price, lastPrice, (1 + priceFactor)); const result = await this.exchange.createLimitBuyOrder(symbol, amount, price) const orderId = result.id if (!orderId) { // cryptopia? this.setStatus(orderId, 'done', 'exchange.createMarketBuyOrder. Market buy order filled immediately') return } // this.log('sleep', secondsPerIteration) await sleep(secondsPerIteration * time.SECOND) secondsPerIteration *= SLEEP_FACTOR // just some number to make this work on slow exchanges also try { const order = await this.exchange.fetchOrder(orderId, symbol) if (order.remaining <= 0) { this.setStatus(orderId, 'done', 'exchange.createMarketBuyOrder. Market buy order filled') return } } catch (ex) { this.setStatus(orderId, 'done', 'exchange.createMarketBuyOrder. Assuming market buy order filled') return } // this.log('order.remaining', order.remaining) // JSON.stringify(order, null, 4)) await this.cancelOrder(orderId) } // next priceFactor this.setStatus(orderId, 'failed', 'exchange.createMarketBuyOrder. Market buy order not filled') } // end of buy()
JavaScript
async createMarketSellOrder(symbol, amount, secondsPerIteration=SECONDS_PER_SELL_ITERATION) { for (let priceFactor = MIN_PRICE_FACTOR;priceFactor <= MAX_PRICE_FACTOR;priceFactor *= PRICE_FACTOR_FACTOR) { const lastPrice = await this.getLastPrice(symbol) const price = lastPrice / (1+priceFactor) // this.log('Market sell', amount, symbol, 'at', price, ',', lastPrice, '/', 1+priceFactor) log.info('exchange.createMarketSellOrder', 'Market sell %s %s at %s [last: %s factor %s]', amount, symbol, price, lastPrice, (1 + priceFactor)); const result = await this.exchange.createLimitSellOrder(symbol, amount, price) const orderId = result.id if (!orderId) { // cryptopia? this.setStatus(orderId, 'done', 'exchange.createMarketBuyOrder. Market sell order filled immediately') return } // this.log('sleep', secondsPerIteration) await sleep(secondsPerIteration * time.SECOND) secondsPerIteration *= SLEEP_FACTOR // just some number to make this work on slow exchanges also try { const order = await this.exchange.fetchOrder(orderId, symbol) if (order.remaining <= 0) { this.setStatus(orderId, 'done', 'exchange.createMarketBuyOrder. Market sell order filled') return } } catch (ex) { this.setStatus(orderId, 'done', 'exchange.createMarketBuyOrder. Assuming market sell order filled') return } // this.log('order.remaining', order.remaining) // JSON.stringify(order, null, 4)) await this.cancelOrder(orderId) } // next priceFactor this.setStatus(orderId, 'failed', 'exchange.createMarketBuyOrder. Market sell order not filled') } // end of sell()
async createMarketSellOrder(symbol, amount, secondsPerIteration=SECONDS_PER_SELL_ITERATION) { for (let priceFactor = MIN_PRICE_FACTOR;priceFactor <= MAX_PRICE_FACTOR;priceFactor *= PRICE_FACTOR_FACTOR) { const lastPrice = await this.getLastPrice(symbol) const price = lastPrice / (1+priceFactor) // this.log('Market sell', amount, symbol, 'at', price, ',', lastPrice, '/', 1+priceFactor) log.info('exchange.createMarketSellOrder', 'Market sell %s %s at %s [last: %s factor %s]', amount, symbol, price, lastPrice, (1 + priceFactor)); const result = await this.exchange.createLimitSellOrder(symbol, amount, price) const orderId = result.id if (!orderId) { // cryptopia? this.setStatus(orderId, 'done', 'exchange.createMarketBuyOrder. Market sell order filled immediately') return } // this.log('sleep', secondsPerIteration) await sleep(secondsPerIteration * time.SECOND) secondsPerIteration *= SLEEP_FACTOR // just some number to make this work on slow exchanges also try { const order = await this.exchange.fetchOrder(orderId, symbol) if (order.remaining <= 0) { this.setStatus(orderId, 'done', 'exchange.createMarketBuyOrder. Market sell order filled') return } } catch (ex) { this.setStatus(orderId, 'done', 'exchange.createMarketBuyOrder. Assuming market sell order filled') return } // this.log('order.remaining', order.remaining) // JSON.stringify(order, null, 4)) await this.cancelOrder(orderId) } // next priceFactor this.setStatus(orderId, 'failed', 'exchange.createMarketBuyOrder. Market sell order not filled') } // end of sell()
JavaScript
function addCheckDigit(partialCard) { // Get sum from luhnSum, pass in false for hasCheckDigit const sum = luhnSum(partialCard, false); // Multiply sum by nine, convert to string const tempSum = (sum * 9).toString(); // checkDigit is the last digit of the multiplied sum const checkDigit = tempSum[tempSum.length - 1]; // Return complete card as a string return partialCard + checkDigit; }
function addCheckDigit(partialCard) { // Get sum from luhnSum, pass in false for hasCheckDigit const sum = luhnSum(partialCard, false); // Multiply sum by nine, convert to string const tempSum = (sum * 9).toString(); // checkDigit is the last digit of the multiplied sum const checkDigit = tempSum[tempSum.length - 1]; // Return complete card as a string return partialCard + checkDigit; }
JavaScript
function ematrix( m1 , m2 , fn){ //the two matrix must be the same size for (let i = 0 ; i < m1.length ; i ++){ for(let j = 0 ; j < m1[i].length ; j++ ){ m1[i][j] = fn(m1[i][j] , m2[i][j] ) } } return m1 ; }
function ematrix( m1 , m2 , fn){ //the two matrix must be the same size for (let i = 0 ; i < m1.length ; i ++){ for(let j = 0 ; j < m1[i].length ; j++ ){ m1[i][j] = fn(m1[i][j] , m2[i][j] ) } } return m1 ; }
JavaScript
function nextQuest() { liveScore.innerHTML = "Your score: " + score; if (questionNum == 0) { for (var i = 0; i < options.length; i++) { options[i].innerHTML = test.quiz1.options[i]; } question.innerHTML = test.quiz1.question; } else if (questionNum == 1) { for (var i = 0; i < options.length; i++) { options[i].innerHTML = test.quiz2.options[i]; } question.innerHTML = test.quiz2.question; } else if (questionNum == 2) { for (var i = 0; i < options.length; i++) { options[i].innerHTML = test.quiz3.options[i]; } question.innerHTML = test.quiz3.question; } else if (questionNum == 3) { for (var i = 0; i < options.length; i++) { options[i].innerHTML = test.quiz4.options[i]; } question.innerHTML = test.quiz4.question; } else { asker.style.display = "none"; highscores.style.display = "block"; disScore.innerHTML = score; finished = true; } scoreCount.push(score); questionNum++; }
function nextQuest() { liveScore.innerHTML = "Your score: " + score; if (questionNum == 0) { for (var i = 0; i < options.length; i++) { options[i].innerHTML = test.quiz1.options[i]; } question.innerHTML = test.quiz1.question; } else if (questionNum == 1) { for (var i = 0; i < options.length; i++) { options[i].innerHTML = test.quiz2.options[i]; } question.innerHTML = test.quiz2.question; } else if (questionNum == 2) { for (var i = 0; i < options.length; i++) { options[i].innerHTML = test.quiz3.options[i]; } question.innerHTML = test.quiz3.question; } else if (questionNum == 3) { for (var i = 0; i < options.length; i++) { options[i].innerHTML = test.quiz4.options[i]; } question.innerHTML = test.quiz4.question; } else { asker.style.display = "none"; highscores.style.display = "block"; disScore.innerHTML = score; finished = true; } scoreCount.push(score); questionNum++; }
JavaScript
function countdown() { if (timeLeft < 0 && finished == false) { clearInterval(timerId); outOfTime(); } else if (finished == true) { } else { elem.innerHTML = timeLeft + " seconds remaining"; timeLeft--; } }
function countdown() { if (timeLeft < 0 && finished == false) { clearInterval(timerId); outOfTime(); } else if (finished == true) { } else { elem.innerHTML = timeLeft + " seconds remaining"; timeLeft--; } }
JavaScript
function outOfTime() { asker.style.display = "none"; highscores.style.display = "block"; disScore.innerHTML = score; document.querySelector("#outOfTime").innerHTML = "Out Of Time"; }
function outOfTime() { asker.style.display = "none"; highscores.style.display = "block"; disScore.innerHTML = score; document.querySelector("#outOfTime").innerHTML = "Out Of Time"; }
JavaScript
function flashRed() { document.querySelector("#someCont").classList.add("bg-danger"); window.setTimeout(function () { document.querySelector("#someCont").classList.remove("bg-danger") }, 300); }
function flashRed() { document.querySelector("#someCont").classList.add("bg-danger"); window.setTimeout(function () { document.querySelector("#someCont").classList.remove("bg-danger") }, 300); }
JavaScript
function flashGreen() { document.querySelector("#someCont").classList.add("bg-success"); window.setTimeout(function () { document.querySelector("#someCont").classList.remove("bg-success") }, 300); }
function flashGreen() { document.querySelector("#someCont").classList.add("bg-success"); window.setTimeout(function () { document.querySelector("#someCont").classList.remove("bg-success") }, 300); }
JavaScript
function remove(taskName) { if (taskName == null || taskName.length <= 0) { throw new Error('Param is not valid'); } var index = _tasks.indexOf(taskName); if (index < 0 || _tasks.length <= 0) { return; } _tasks.splice(index, 1); index = _completed.indexOf(taskName); if (index < 0 || _completed.length <= 0) { return; } _completed.splice(index, 1); }
function remove(taskName) { if (taskName == null || taskName.length <= 0) { throw new Error('Param is not valid'); } var index = _tasks.indexOf(taskName); if (index < 0 || _tasks.length <= 0) { return; } _tasks.splice(index, 1); index = _completed.indexOf(taskName); if (index < 0 || _completed.length <= 0) { return; } _completed.splice(index, 1); }
JavaScript
function clearAll() { _tasks = []; _completed = []; _isFinished = false; }
function clearAll() { _tasks = []; _completed = []; _isFinished = false; }
JavaScript
function handleDeleteItem(e) { console.log('click'); if (e.target.nodeName === 'BUTTON') { // removeClass(); // removeListener(); localStorage.removeItem('json'); } }
function handleDeleteItem(e) { console.log('click'); if (e.target.nodeName === 'BUTTON') { // removeClass(); // removeListener(); localStorage.removeItem('json'); } }
JavaScript
function cardDetailsMarkup(data) { const name = data.NAME; const lastIndex = name.lastIndexOf(' '); const croppedName = name.substring(0, lastIndex); const capitalizeWord = data.DESCRIPTION.charAt(0).toUpperCase() + data.DESCRIPTION.slice(1); const template = ` <span class="details__model">Model:${data.ID}</span> <h3 class="details__name">${croppedName}</h3> <p class="details__about">${capitalizeWord}</p>`; return details.insertAdjacentHTML('afterbegin', template); }
function cardDetailsMarkup(data) { const name = data.NAME; const lastIndex = name.lastIndexOf(' '); const croppedName = name.substring(0, lastIndex); const capitalizeWord = data.DESCRIPTION.charAt(0).toUpperCase() + data.DESCRIPTION.slice(1); const template = ` <span class="details__model">Model:${data.ID}</span> <h3 class="details__name">${croppedName}</h3> <p class="details__about">${capitalizeWord}</p>`; return details.insertAdjacentHTML('afterbegin', template); }
JavaScript
function __message(code, data) { if (typeof(log) != 'undefined' && log != null) { log.innerHTML = "msg: " + code + ": " + (data || '') + "\n" + log.innerHTML; } }
function __message(code, data) { if (typeof(log) != 'undefined' && log != null) { log.innerHTML = "msg: " + code + ": " + (data || '') + "\n" + log.innerHTML; } }
JavaScript
function assign_values( obj ) { /** * Get values from object attribute */ $('input[name="edit_id"]').val(obj.attr('id')); $('input[name="edit_item_id"]').val(obj.attr('p-name')); $('input[name="edit_category_name"]').val(obj.attr('c-name')); $('input[name="edit_order_unit"]').val(obj.attr('o-unit')); $('input[name="edit_price_per_unit"]').attr('u-equiv', obj.attr('u-equiv')); $('input[name="edit_price_per_unit"]').val(obj.attr('p-price')); $('input[name="edit_orderdetails_quantity"]').val(obj.attr('t-quan')); $('input[name="edit_selling_unit"]').val(obj.attr('s-unit')); $('input[name="edit_inv_item_srp"]').val(obj.attr('s-price')); $('input[name="edit_expiration_date"]').val(obj.attr('t-expire')); /** * Reset input icons */ input_icon_reset(); }
function assign_values( obj ) { /** * Get values from object attribute */ $('input[name="edit_id"]').val(obj.attr('id')); $('input[name="edit_item_id"]').val(obj.attr('p-name')); $('input[name="edit_category_name"]').val(obj.attr('c-name')); $('input[name="edit_order_unit"]').val(obj.attr('o-unit')); $('input[name="edit_price_per_unit"]').attr('u-equiv', obj.attr('u-equiv')); $('input[name="edit_price_per_unit"]').val(obj.attr('p-price')); $('input[name="edit_orderdetails_quantity"]').val(obj.attr('t-quan')); $('input[name="edit_selling_unit"]').val(obj.attr('s-unit')); $('input[name="edit_inv_item_srp"]').val(obj.attr('s-price')); $('input[name="edit_expiration_date"]').val(obj.attr('t-expire')); /** * Reset input icons */ input_icon_reset(); }
JavaScript
function product_values( obj ) { /** * Get values from object attribute */ $('input[name="pro_id"]').val(obj.attr('id')); $('input[name="pro_oid"]').val(obj.attr('o-id')); $('input[name="pro_iid"]').val(obj.attr('i-id')); $('input[name="pro_item_id"]').val(obj.attr('p-name')); $('input[name="pro_category_name"]').val(obj.attr('c-name')); $('input[name="pro_order_unit"]').val(obj.attr('o-unit')); $('input[name="pro_price_per_unit"]').attr('u-equiv', obj.attr('u-equiv')); $('input[name="pro_price_per_unit"]').val(obj.attr('p-price')); $('input[name="pro_orderdetails_quantity"]').val(obj.attr('t-quan')); $('input[name="pro_selling_unit"]').val(obj.attr('s-unit')); $('input[name="pro_inv_item_srp"]').val(obj.attr('s-price')); $('input[name="pro_expiration_date"]').val(obj.attr('t-expire')); /** * Reset input icons */ input_icon_reset(); }
function product_values( obj ) { /** * Get values from object attribute */ $('input[name="pro_id"]').val(obj.attr('id')); $('input[name="pro_oid"]').val(obj.attr('o-id')); $('input[name="pro_iid"]').val(obj.attr('i-id')); $('input[name="pro_item_id"]').val(obj.attr('p-name')); $('input[name="pro_category_name"]').val(obj.attr('c-name')); $('input[name="pro_order_unit"]').val(obj.attr('o-unit')); $('input[name="pro_price_per_unit"]').attr('u-equiv', obj.attr('u-equiv')); $('input[name="pro_price_per_unit"]').val(obj.attr('p-price')); $('input[name="pro_orderdetails_quantity"]').val(obj.attr('t-quan')); $('input[name="pro_selling_unit"]').val(obj.attr('s-unit')); $('input[name="pro_inv_item_srp"]').val(obj.attr('s-price')); $('input[name="pro_expiration_date"]').val(obj.attr('t-expire')); /** * Reset input icons */ input_icon_reset(); }
JavaScript
function data_checker(data) { for (var i=0; i < data.length; i++) { if (!data[i].value) { $.toast({ heading : 'Error', text : 'All fields is required.', showHideTransition: 'fade', icon : 'error', loaderBg : '#f2a654', position : 'bottom-right' }); break; } } return true; }
function data_checker(data) { for (var i=0; i < data.length; i++) { if (!data[i].value) { $.toast({ heading : 'Error', text : 'All fields is required.', showHideTransition: 'fade', icon : 'error', loaderBg : '#f2a654', position : 'bottom-right' }); break; } } return true; }
JavaScript
function input_icon(obj) { obj.each(function () { if (obj.val().length > 0) { obj.closest('.input-group').find('.mdi').removeClass('mdi-close-circle-outline'); obj.closest('.input-group').find('.input-group-text').removeClass('text-danger'); obj.closest('.input-group').find('.input-group-text').addClass('text-success'); obj.closest('.input-group').find('.mdi').addClass('mdi-check-circle-outline'); } else { obj.closest('.input-group').find('.input-group-text').removeClass('text-success'); obj.closest('.input-group').find('.mdi').removeClass('mdi-check-circle-outline'); obj.closest('.input-group').find('.mdi').addClass('mdi-close-circle-outline'); obj.closest('.input-group').find('.input-group-text').addClass('text-danger'); } }); }
function input_icon(obj) { obj.each(function () { if (obj.val().length > 0) { obj.closest('.input-group').find('.mdi').removeClass('mdi-close-circle-outline'); obj.closest('.input-group').find('.input-group-text').removeClass('text-danger'); obj.closest('.input-group').find('.input-group-text').addClass('text-success'); obj.closest('.input-group').find('.mdi').addClass('mdi-check-circle-outline'); } else { obj.closest('.input-group').find('.input-group-text').removeClass('text-success'); obj.closest('.input-group').find('.mdi').removeClass('mdi-check-circle-outline'); obj.closest('.input-group').find('.mdi').addClass('mdi-close-circle-outline'); obj.closest('.input-group').find('.input-group-text').addClass('text-danger'); } }); }
JavaScript
function __awaiter(thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }
function __awaiter(thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }
JavaScript
function AnimateOnVisible() { var observer = new IntersectionObserver((entries) => { entries.forEach(entry => { if (entry.intersectionRatio > 0) { entry.target.classList.add('animation_trigger'); observer.unobserve(entry.target); } }); }); var elements = document.querySelectorAll(".animate_on_visible"); elements.forEach(elt => { observer.observe(elt); }); }
function AnimateOnVisible() { var observer = new IntersectionObserver((entries) => { entries.forEach(entry => { if (entry.intersectionRatio > 0) { entry.target.classList.add('animation_trigger'); observer.unobserve(entry.target); } }); }); var elements = document.querySelectorAll(".animate_on_visible"); elements.forEach(elt => { observer.observe(elt); }); }
JavaScript
function CreateGallery() { let images = [ "./assets/gallery/2021-03-17 110526 showcase album.png", "./assets/gallery/2021-03-17 110828 showcase blackhole.png", "./assets/gallery/2021-03-17 110952 showcase nightsky.png", "./assets/gallery/2021-03-17 111307 showcase radioshow.png", "./assets/gallery/2021-03-17 111504 showcase sunphone.png", "./assets/gallery/2021-03-17 111658 showcase waves_fade.png", "./assets/gallery/2021-07-21 155400 wav2bar 0.2.0 beta.png", ]; let imagesDOM = []; let thumbnailsDOM = []; let selectedImage = 0; let imagesContainer = document.getElementById("gallery_images_container"); let thumbnailsContainer = document.getElementById("gallery_thumbnails_container"); //setup gallery //add space for thumbnails to the left let leftSpace = document.createElement("div"); thumbnailsContainer.appendChild(leftSpace); leftSpace.style.width = "200px"; leftSpace.style.height = "100%"; leftSpace.style.flex = "0 0 100px"; //add images and thumbnails for (let i=0; i<images.length; i++) { let src = images[i]; //image let img = document.createElement("img"); imagesContainer.appendChild(img); img.src = src; img.alt = src.replace(/^.*\//,""); if (i !== 0) img.style.display = "none"; imagesDOM.push(img); //thumbnail let thumbnail = document.createElement("img"); thumbnailsContainer.appendChild(thumbnail); thumbnail.src = src; thumbnail.alt = src.replace(/^.*\//,""); thumbnail.onclick = function() { DisplayGalleryImage(img, this); selectedImage = i; } thumbnailsDOM.push(thumbnail); } //add space for thumbnails to the right let rightSpace = document.createElement("div"); thumbnailsContainer.appendChild(rightSpace); rightSpace.style.width = "200px"; rightSpace.style.height = "100%"; rightSpace.style.flex = "0 0 100px"; //move in thumbnail timeline document.getElementById("thumbnails_go_left").onclick = function() { ThumbnailsGoLeft(); } document.getElementById("thumbnails_go_right").onclick = function() { ThumbnailsGoRight(); } //next or previous image document.getElementById("gallery_prev_img").onclick = function() { if (selectedImage > 0) { selectedImage--; DisplayGalleryImage(imagesDOM[selectedImage], thumbnailsDOM[selectedImage]); } } document.getElementById("gallery_next_img").onclick = function() { if (selectedImage < images.length-1) { selectedImage++; DisplayGalleryImage(imagesDOM[selectedImage], thumbnailsDOM[selectedImage]); } } }
function CreateGallery() { let images = [ "./assets/gallery/2021-03-17 110526 showcase album.png", "./assets/gallery/2021-03-17 110828 showcase blackhole.png", "./assets/gallery/2021-03-17 110952 showcase nightsky.png", "./assets/gallery/2021-03-17 111307 showcase radioshow.png", "./assets/gallery/2021-03-17 111504 showcase sunphone.png", "./assets/gallery/2021-03-17 111658 showcase waves_fade.png", "./assets/gallery/2021-07-21 155400 wav2bar 0.2.0 beta.png", ]; let imagesDOM = []; let thumbnailsDOM = []; let selectedImage = 0; let imagesContainer = document.getElementById("gallery_images_container"); let thumbnailsContainer = document.getElementById("gallery_thumbnails_container"); //setup gallery //add space for thumbnails to the left let leftSpace = document.createElement("div"); thumbnailsContainer.appendChild(leftSpace); leftSpace.style.width = "200px"; leftSpace.style.height = "100%"; leftSpace.style.flex = "0 0 100px"; //add images and thumbnails for (let i=0; i<images.length; i++) { let src = images[i]; //image let img = document.createElement("img"); imagesContainer.appendChild(img); img.src = src; img.alt = src.replace(/^.*\//,""); if (i !== 0) img.style.display = "none"; imagesDOM.push(img); //thumbnail let thumbnail = document.createElement("img"); thumbnailsContainer.appendChild(thumbnail); thumbnail.src = src; thumbnail.alt = src.replace(/^.*\//,""); thumbnail.onclick = function() { DisplayGalleryImage(img, this); selectedImage = i; } thumbnailsDOM.push(thumbnail); } //add space for thumbnails to the right let rightSpace = document.createElement("div"); thumbnailsContainer.appendChild(rightSpace); rightSpace.style.width = "200px"; rightSpace.style.height = "100%"; rightSpace.style.flex = "0 0 100px"; //move in thumbnail timeline document.getElementById("thumbnails_go_left").onclick = function() { ThumbnailsGoLeft(); } document.getElementById("thumbnails_go_right").onclick = function() { ThumbnailsGoRight(); } //next or previous image document.getElementById("gallery_prev_img").onclick = function() { if (selectedImage > 0) { selectedImage--; DisplayGalleryImage(imagesDOM[selectedImage], thumbnailsDOM[selectedImage]); } } document.getElementById("gallery_next_img").onclick = function() { if (selectedImage < images.length-1) { selectedImage++; DisplayGalleryImage(imagesDOM[selectedImage], thumbnailsDOM[selectedImage]); } } }
JavaScript
function DisplayGalleryImage(img, thumbnail) { console.log(img); let imagesContainer = document.getElementById("gallery_images_container"); let thumbnailsContainer = document.getElementById("gallery_thumbnails_container"); //switch image let imagesDOM = imagesContainer.getElementsByTagName("img"); for (let i of imagesDOM) i.style.display = "none"; img.style.display = "initial"; //update thumbnails container let thumbnails = thumbnailsContainer.children; for (let t of thumbnails) t.classList.remove("focused"); thumbnail.classList.add("focused"); }
function DisplayGalleryImage(img, thumbnail) { console.log(img); let imagesContainer = document.getElementById("gallery_images_container"); let thumbnailsContainer = document.getElementById("gallery_thumbnails_container"); //switch image let imagesDOM = imagesContainer.getElementsByTagName("img"); for (let i of imagesDOM) i.style.display = "none"; img.style.display = "initial"; //update thumbnails container let thumbnails = thumbnailsContainer.children; for (let t of thumbnails) t.classList.remove("focused"); thumbnail.classList.add("focused"); }
JavaScript
function ThumbnailsGoLeft() { let thumbnailsContainer = document.getElementById("gallery_thumbnails_container"); thumbnailsContainer.velocity("stop"); //in case of ongoing animation Velocity(thumbnailsContainer, {scrollLeft: `${thumbnailsContainer.scrollLeft - 350}px`, duration : 100}); }
function ThumbnailsGoLeft() { let thumbnailsContainer = document.getElementById("gallery_thumbnails_container"); thumbnailsContainer.velocity("stop"); //in case of ongoing animation Velocity(thumbnailsContainer, {scrollLeft: `${thumbnailsContainer.scrollLeft - 350}px`, duration : 100}); }
JavaScript
function ThumbnailsGoRight() { let thumbnailsContainer = document.getElementById("gallery_thumbnails_container"); thumbnailsContainer.velocity("stop"); //in case of ongoing animation Velocity(thumbnailsContainer, {scrollLeft: `${thumbnailsContainer.scrollLeft + 350}px`, duration : 100}); }
function ThumbnailsGoRight() { let thumbnailsContainer = document.getElementById("gallery_thumbnails_container"); thumbnailsContainer.velocity("stop"); //in case of ongoing animation Velocity(thumbnailsContainer, {scrollLeft: `${thumbnailsContainer.scrollLeft + 350}px`, duration : 100}); }
JavaScript
function isPlainObject(variable) { if (!variable || (typeof variable === "undefined" ? "undefined" : _typeof(variable)) !== "object" || variable.nodeType || Object.prototype.toString.call(variable) !== "[object Object]") { return false; } var proto = Object.getPrototypeOf(variable); return !proto || proto.hasOwnProperty("constructor") && proto.constructor === Object; }
function isPlainObject(variable) { if (!variable || (typeof variable === "undefined" ? "undefined" : _typeof(variable)) !== "object" || variable.nodeType || Object.prototype.toString.call(variable) !== "[object Object]") { return false; } var proto = Object.getPrototypeOf(variable); return !proto || proto.hasOwnProperty("constructor") && proto.constructor === Object; }
JavaScript
function addClass(element, className) { if (element instanceof Element) { if (element.classList) { element.classList.add(className); } else { removeClass(element, className); element.className += (element.className.length ? " " : "") + className; } } }
function addClass(element, className) { if (element instanceof Element) { if (element.classList) { element.classList.add(className); } else { removeClass(element, className); element.className += (element.className.length ? " " : "") + className; } } }
JavaScript
function defineProperty$1(proto, name, value, readonly) { if (proto) { Object.defineProperty(proto, name, { configurable: !readonly, writable: !readonly, value: value }); } }
function defineProperty$1(proto, name, value, readonly) { if (proto) { Object.defineProperty(proto, name, { configurable: !readonly, writable: !readonly, value: value }); } }
JavaScript
function removeClass(element, className) { if (element instanceof Element) { if (element.classList) { element.classList.remove(className); } else { // TODO: Need some jsperf tests on performance - can we get rid of the regex and maybe use split / array manipulation? element.className = element.className.replace(new RegExp("(^|\\s)" + className + "(\\s|$)", "gi"), " "); } } }
function removeClass(element, className) { if (element instanceof Element) { if (element.classList) { element.classList.remove(className); } else { // TODO: Need some jsperf tests on performance - can we get rid of the regex and maybe use split / array manipulation? element.className = element.className.replace(new RegExp("(^|\\s)" + className + "(\\s|$)", "gi"), " "); } } }
JavaScript
function registerAction(args, internal) { var name = args[0], callback = args[1]; if (!isString(name)) { console.warn("VelocityJS: Trying to set 'registerAction' name to an invalid value:", name); } else if (!isFunction(callback)) { console.warn("VelocityJS: Trying to set 'registerAction' callback to an invalid value:", name, callback); } else if (Actions[name] && !propertyIsEnumerable(Actions, name)) { console.warn("VelocityJS: Trying to override internal 'registerAction' callback", name); } else if (internal === true) { defineProperty$1(Actions, name, callback); } else { Actions[name] = callback; } }
function registerAction(args, internal) { var name = args[0], callback = args[1]; if (!isString(name)) { console.warn("VelocityJS: Trying to set 'registerAction' name to an invalid value:", name); } else if (!isFunction(callback)) { console.warn("VelocityJS: Trying to set 'registerAction' callback to an invalid value:", name, callback); } else if (Actions[name] && !propertyIsEnumerable(Actions, name)) { console.warn("VelocityJS: Trying to override internal 'registerAction' callback", name); } else if (internal === true) { defineProperty$1(Actions, name, callback); } else { Actions[name] = callback; } }
JavaScript
function registerEasing(args) { var name = args[0], callback = args[1]; if (!isString(name)) { console.warn("VelocityJS: Trying to set 'registerEasing' name to an invalid value:", name); } else if (!isFunction(callback)) { console.warn("VelocityJS: Trying to set 'registerEasing' callback to an invalid value:", name, callback); } else if (Easings[name]) { console.warn("VelocityJS: Trying to override 'registerEasing' callback", name); } else { Easings[name] = callback; } }
function registerEasing(args) { var name = args[0], callback = args[1]; if (!isString(name)) { console.warn("VelocityJS: Trying to set 'registerEasing' name to an invalid value:", name); } else if (!isFunction(callback)) { console.warn("VelocityJS: Trying to set 'registerEasing' callback to an invalid value:", name, callback); } else if (Easings[name]) { console.warn("VelocityJS: Trying to override 'registerEasing' callback", name); } else { Easings[name] = callback; } }
JavaScript
function parseDuration(duration, def) { if (isNumber(duration)) { return duration; } if (isString(duration)) { return Duration[duration.toLowerCase()] || parseFloat(duration.replace("ms", "").replace("s", "000")); } return def == null ? undefined : parseDuration(def); }
function parseDuration(duration, def) { if (isNumber(duration)) { return duration; } if (isString(duration)) { return Duration[duration.toLowerCase()] || parseFloat(duration.replace("ms", "").replace("s", "000")); } return def == null ? undefined : parseDuration(def); }
JavaScript
function Data(element) { // Use a string member so Uglify doesn't mangle it. var data = element[dataName]; if (data) { return data; } var window = element.ownerDocument.defaultView; var types = 0; for (var index = 0; index < constructors.length; index++) { var _constructor = constructors[index]; if (isString(_constructor)) { if (element instanceof window[_constructor]) { types |= 1 << index; // tslint:disable-line:no-bitwise } } else if (element instanceof _constructor) { types |= 1 << index; // tslint:disable-line:no-bitwise } } // Use an intermediate object so it errors on incorrect data. var newData = { types: types, count: 0, computedStyle: null, cache: {}, queueList: {}, lastAnimationList: {}, lastFinishList: {}, window: window }; Object.defineProperty(element, dataName, { value: newData }); return newData; }
function Data(element) { // Use a string member so Uglify doesn't mangle it. var data = element[dataName]; if (data) { return data; } var window = element.ownerDocument.defaultView; var types = 0; for (var index = 0; index < constructors.length; index++) { var _constructor = constructors[index]; if (isString(_constructor)) { if (element instanceof window[_constructor]) { types |= 1 << index; // tslint:disable-line:no-bitwise } } else if (element instanceof _constructor) { types |= 1 << index; // tslint:disable-line:no-bitwise } } // Use an intermediate object so it errors on incorrect data. var newData = { types: types, count: 0, computedStyle: null, cache: {}, queueList: {}, lastAnimationList: {}, lastFinishList: {}, window: window }; Object.defineProperty(element, dataName, { value: newData }); return newData; }
JavaScript
function queue$1(element, animation, queueName) { var data = Data(element); if (queueName !== false) { // Store the last animation added so we can use it for the // beginning of the next one. data.lastAnimationList[queueName] = animation; } if (queueName === false) { animate(animation); } else { if (!isString(queueName)) { queueName = ""; } var last = data.queueList[queueName]; if (!last) { if (last === null) { data.queueList[queueName] = animation; } else { data.queueList[queueName] = null; animate(animation); } } else { while (last._next) { last = last._next; } last._next = animation; animation._prev = last; } } }
function queue$1(element, animation, queueName) { var data = Data(element); if (queueName !== false) { // Store the last animation added so we can use it for the // beginning of the next one. data.lastAnimationList[queueName] = animation; } if (queueName === false) { animate(animation); } else { if (!isString(queueName)) { queueName = ""; } var last = data.queueList[queueName]; if (!last) { if (last === null) { data.queueList[queueName] = animation; } else { data.queueList[queueName] = null; animate(animation); } } else { while (last._next) { last = last._next; } last._next = animation; animation._prev = last; } } }
JavaScript
function dequeue(element, queueName, skip) { if (queueName !== false) { if (!isString(queueName)) { queueName = ""; } var data = Data(element), animation = data.queueList[queueName]; if (animation) { data.queueList[queueName] = animation._next || null; if (!skip) { animate(animation); } } else if (animation === null) { delete data.queueList[queueName]; } return animation; } }
function dequeue(element, queueName, skip) { if (queueName !== false) { if (!isString(queueName)) { queueName = ""; } var data = Data(element), animation = data.queueList[queueName]; if (animation) { data.queueList[queueName] = animation._next || null; if (!skip) { animate(animation); } } else if (animation === null) { delete data.queueList[queueName]; } return animation; } }
JavaScript
function freeAnimationCall(animation) { var next = animation._next, prev = animation._prev, queueName = animation.queue == null ? animation.options.queue : animation.queue; if (State.firstNew === animation) { State.firstNew = next; } if (State.first === animation) { State.first = next; } else if (prev) { prev._next = next; } if (State.last === animation) { State.last = prev; } else if (next) { next._prev = prev; } if (queueName) { var data = Data(animation.element); if (data) { animation._next = animation._prev = undefined; } } }
function freeAnimationCall(animation) { var next = animation._next, prev = animation._prev, queueName = animation.queue == null ? animation.options.queue : animation.queue; if (State.firstNew === animation) { State.firstNew = next; } if (State.first === animation) { State.first = next; } else if (prev) { prev._next = next; } if (State.last === animation) { State.last = prev; } else if (next) { next._prev = prev; } if (queueName) { var data = Data(animation.element); if (data) { animation._next = animation._prev = undefined; } } }
JavaScript
function callComplete(activeCall) { var callback = activeCall.complete || activeCall.options.complete; if (callback) { try { var elements = activeCall.elements; callback.call(elements, elements, activeCall); } catch (error) { setTimeout(function () { throw error; }, 1); } } }
function callComplete(activeCall) { var callback = activeCall.complete || activeCall.options.complete; if (callback) { try { var elements = activeCall.elements; callback.call(elements, elements, activeCall); } catch (error) { setTimeout(function () { throw error; }, 1); } } }
JavaScript
function completeCall(activeCall) { // TODO: Check if it's not been completed already var options = activeCall.options, queue = getValue(activeCall.queue, options.queue), isLoop = getValue(activeCall.loop, options.loop, defaults$1.loop), isRepeat = getValue(activeCall.repeat, options.repeat, defaults$1.repeat), isStopped = activeCall._flags & 8 /* STOPPED */; // tslint:disable-line:no-bitwise if (!isStopped && (isLoop || isRepeat)) { //////////////////// // Option: Loop // // Option: Repeat // //////////////////// if (isRepeat && isRepeat !== true) { activeCall.repeat = isRepeat - 1; } else if (isLoop && isLoop !== true) { activeCall.loop = isLoop - 1; activeCall.repeat = getValue(activeCall.repeatAgain, options.repeatAgain, defaults$1.repeatAgain); } if (isLoop) { activeCall._flags ^= 64 /* REVERSE */; // tslint:disable-line:no-bitwise } if (queue !== false) { // Can't be called when stopped so no need for an extra check. Data(activeCall.element).lastFinishList[queue] = activeCall.timeStart + getValue(activeCall.duration, options.duration, defaults$1.duration); } activeCall.timeStart = activeCall.ellapsedTime = activeCall.percentComplete = 0; activeCall._flags &= ~4 /* STARTED */; // tslint:disable-line:no-bitwise } else { var element = activeCall.element, data = Data(element); if (! --data.count && !isStopped) { //////////////////////// // Feature: Classname // //////////////////////// removeClass(element, State.className); } ////////////////////// // Option: Complete // ////////////////////// // If this is the last animation in this list then we can check for // and complete calls or Promises. // TODO: When deleting an element we need to adjust these values. if (options && ++options._completed === options._total) { if (!isStopped && options.complete) { // We don't call the complete if the animation is stopped, // and we clear the key to prevent it being called again. callComplete(activeCall); options.complete = null; } var resolver = options._resolver; if (resolver) { // Fulfil the Promise resolver(activeCall.elements); delete options._resolver; } } /////////////////// // Option: Queue // /////////////////// if (queue !== false) { // We only do clever things with queues... if (!isStopped) { // If we're not stopping an animation, we need to remember // what time it finished so that the next animation in // sequence gets the correct start time. data.lastFinishList[queue] = activeCall.timeStart + getValue(activeCall.duration, options.duration, defaults$1.duration); } // Start the next animation in sequence, or delete the queue if // this was the last one. dequeue(element, queue); } // Cleanup any pointers, and remember the last animation etc. freeAnimationCall(activeCall); } }
function completeCall(activeCall) { // TODO: Check if it's not been completed already var options = activeCall.options, queue = getValue(activeCall.queue, options.queue), isLoop = getValue(activeCall.loop, options.loop, defaults$1.loop), isRepeat = getValue(activeCall.repeat, options.repeat, defaults$1.repeat), isStopped = activeCall._flags & 8 /* STOPPED */; // tslint:disable-line:no-bitwise if (!isStopped && (isLoop || isRepeat)) { //////////////////// // Option: Loop // // Option: Repeat // //////////////////// if (isRepeat && isRepeat !== true) { activeCall.repeat = isRepeat - 1; } else if (isLoop && isLoop !== true) { activeCall.loop = isLoop - 1; activeCall.repeat = getValue(activeCall.repeatAgain, options.repeatAgain, defaults$1.repeatAgain); } if (isLoop) { activeCall._flags ^= 64 /* REVERSE */; // tslint:disable-line:no-bitwise } if (queue !== false) { // Can't be called when stopped so no need for an extra check. Data(activeCall.element).lastFinishList[queue] = activeCall.timeStart + getValue(activeCall.duration, options.duration, defaults$1.duration); } activeCall.timeStart = activeCall.ellapsedTime = activeCall.percentComplete = 0; activeCall._flags &= ~4 /* STARTED */; // tslint:disable-line:no-bitwise } else { var element = activeCall.element, data = Data(element); if (! --data.count && !isStopped) { //////////////////////// // Feature: Classname // //////////////////////// removeClass(element, State.className); } ////////////////////// // Option: Complete // ////////////////////// // If this is the last animation in this list then we can check for // and complete calls or Promises. // TODO: When deleting an element we need to adjust these values. if (options && ++options._completed === options._total) { if (!isStopped && options.complete) { // We don't call the complete if the animation is stopped, // and we clear the key to prevent it being called again. callComplete(activeCall); options.complete = null; } var resolver = options._resolver; if (resolver) { // Fulfil the Promise resolver(activeCall.elements); delete options._resolver; } } /////////////////// // Option: Queue // /////////////////// if (queue !== false) { // We only do clever things with queues... if (!isStopped) { // If we're not stopping an animation, we need to remember // what time it finished so that the next animation in // sequence gets the correct start time. data.lastFinishList[queue] = activeCall.timeStart + getValue(activeCall.duration, options.duration, defaults$1.duration); } // Start the next animation in sequence, or delete the queue if // this was the last one. dequeue(element, queue); } // Cleanup any pointers, and remember the last animation etc. freeAnimationCall(activeCall); } }
JavaScript
function registerNormalization(args) { var constructor = args[0], name = args[1], callback = args[2]; if (isString(constructor) && !(window[constructor] instanceof Object) || !isString(constructor) && !(constructor instanceof Object)) { console.warn("VelocityJS: Trying to set 'registerNormalization' constructor to an invalid value:", constructor); } else if (!isString(name)) { console.warn("VelocityJS: Trying to set 'registerNormalization' name to an invalid value:", name); } else if (!isFunction(callback)) { console.warn("VelocityJS: Trying to set 'registerNormalization' callback to an invalid value:", name, callback); } else { var index = constructors.indexOf(constructor), nextArg = 3; if (index < 0 && !isString(constructor)) { if (constructorCache.has(constructor)) { index = constructors.indexOf(constructorCache.get(constructor)); } else { for (var property in window) { if (window[property] === constructor) { index = constructors.indexOf(property); if (index < 0) { index = constructors.push(property) - 1; Normalizations[index] = {}; constructorCache.set(constructor, property); } break; } } } } if (index < 0) { index = constructors.push(constructor) - 1; Normalizations[index] = {}; } Normalizations[index][name] = callback; if (isString(args[nextArg])) { var unit = args[nextArg++]; var units = NormalizationUnits[unit]; if (!units) { units = NormalizationUnits[unit] = []; } units.push(callback); } if (args[nextArg] === false) { NoCacheNormalizations.add(name); } } }
function registerNormalization(args) { var constructor = args[0], name = args[1], callback = args[2]; if (isString(constructor) && !(window[constructor] instanceof Object) || !isString(constructor) && !(constructor instanceof Object)) { console.warn("VelocityJS: Trying to set 'registerNormalization' constructor to an invalid value:", constructor); } else if (!isString(name)) { console.warn("VelocityJS: Trying to set 'registerNormalization' name to an invalid value:", name); } else if (!isFunction(callback)) { console.warn("VelocityJS: Trying to set 'registerNormalization' callback to an invalid value:", name, callback); } else { var index = constructors.indexOf(constructor), nextArg = 3; if (index < 0 && !isString(constructor)) { if (constructorCache.has(constructor)) { index = constructors.indexOf(constructorCache.get(constructor)); } else { for (var property in window) { if (window[property] === constructor) { index = constructors.indexOf(property); if (index < 0) { index = constructors.push(property) - 1; Normalizations[index] = {}; constructorCache.set(constructor, property); } break; } } } } if (index < 0) { index = constructors.push(constructor) - 1; Normalizations[index] = {}; } Normalizations[index][name] = callback; if (isString(args[nextArg])) { var unit = args[nextArg++]; var units = NormalizationUnits[unit]; if (!units) { units = NormalizationUnits[unit] = []; } units.push(callback); } if (args[nextArg] === false) { NoCacheNormalizations.add(name); } } }
JavaScript
function hasNormalization(args) { var constructor = args[0], name = args[1]; var index = constructors.indexOf(constructor); if (index < 0 && !isString(constructor)) { if (constructorCache.has(constructor)) { index = constructors.indexOf(constructorCache.get(constructor)); } else { for (var property in window) { if (window[property] === constructor) { index = constructors.indexOf(property); break; } } } } return index >= 0 && Normalizations[index].hasOwnProperty(name); }
function hasNormalization(args) { var constructor = args[0], name = args[1]; var index = constructors.indexOf(constructor); if (index < 0 && !isString(constructor)) { if (constructorCache.has(constructor)) { index = constructors.indexOf(constructorCache.get(constructor)); } else { for (var property in window) { if (window[property] === constructor) { index = constructors.indexOf(property); break; } } } } return index >= 0 && Normalizations[index].hasOwnProperty(name); }
JavaScript
function camelCase(property) { var fixed = cache$2[property]; if (fixed) { return fixed; } return cache$2[property] = property.replace(/-([a-z])/g, function ($, letter) { return letter.toUpperCase(); }); }
function camelCase(property) { var fixed = cache$2[property]; if (fixed) { return fixed; } return cache$2[property] = property.replace(/-([a-z])/g, function ($, letter) { return letter.toUpperCase(); }); }
JavaScript
function augmentDimension(element, name, wantInner) { var isBorderBox = getPropertyValue(element, "boxSizing").toString().toLowerCase() === "border-box"; if (isBorderBox === wantInner) { // in box-sizing mode, the CSS width / height accessors already // give the outerWidth / outerHeight. var sides = name === "width" ? ["Left", "Right"] : ["Top", "Bottom"], fields = ["padding" + sides[0], "padding" + sides[1], "border" + sides[0] + "Width", "border" + sides[1] + "Width"]; var augment = 0; var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = fields[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var field = _step.value; var value = parseFloat(getPropertyValue(element, field)); if (!isNaN(value)) { augment += value; } } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } return wantInner ? -augment : augment; } return 0; }
function augmentDimension(element, name, wantInner) { var isBorderBox = getPropertyValue(element, "boxSizing").toString().toLowerCase() === "border-box"; if (isBorderBox === wantInner) { // in box-sizing mode, the CSS width / height accessors already // give the outerWidth / outerHeight. var sides = name === "width" ? ["Left", "Right"] : ["Top", "Bottom"], fields = ["padding" + sides[0], "padding" + sides[1], "border" + sides[0] + "Width", "border" + sides[1] + "Width"]; var augment = 0; var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = fields[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var field = _step.value; var value = parseFloat(getPropertyValue(element, field)); if (!isNaN(value)) { augment += value; } } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } return wantInner ? -augment : augment; } return 0; }
JavaScript
function computePropertyValue(element, property) { var data = Data(element), // If computedStyle is cached, use it. If not then get the correct one // for the element to support cross-iframe boundaries. computedStyle = data.computedStyle ? data.computedStyle : data.window.getComputedStyle(element, null); var computedValue = 0; if (!data.computedStyle) { data.computedStyle = computedStyle; } if (computedStyle["display"] === "none") { switch (property) { case "width": case "height": // Browsers do not return height and width values for elements // that are set to display:"none". Thus, we temporarily toggle // display to the element type's default value. setPropertyValue(element, "display", "auto"); computedValue = getWidthHeight(element, property); setPropertyValue(element, "display", "none"); return String(computedValue); } } /* IE and Firefox do not return a value for the generic borderColor -- they only return individual values for each border side's color. Also, in all browsers, when border colors aren't all the same, a compound value is returned that Velocity isn't setup to parse. So, as a polyfill for querying individual border side colors, we just return the top border's color and animate all borders from that value. */ /* TODO: There is a borderColor normalisation in legacy/ - figure out where this is needed... */ computedValue = computedStyle[property]; /* Fall back to the property's style value (if defined) when computedValue returns nothing, which can happen when the element hasn't been painted. */ if (!computedValue) { computedValue = element.style[property]; } /* For top, right, bottom, and left (TRBL) values that are set to "auto" on elements of "fixed" or "absolute" position, defer to jQuery for converting "auto" to a numeric value. (For elements with a "static" or "relative" position, "auto" has the same effect as being set to 0, so no conversion is necessary.) */ /* An example of why numeric conversion is necessary: When an element with "position:absolute" has an untouched "left" property, which reverts to "auto", left's value is 0 relative to its parent element, but is often non-zero relative to its *containing* (not parent) element, which is the nearest "position:relative" ancestor or the viewport (and always the viewport in the case of "position:fixed"). */ if (computedValue === "auto") { switch (property) { case "width": case "height": computedValue = getWidthHeight(element, property); break; case "top": case "left": case "right": case "bottom": var position = getPropertyValue(element, "position"); if (position === "fixed" || position === "absolute") { // Note: this has no pixel unit on its returned values, // we re-add it here to conform with // computePropertyValue's behavior. computedValue = element.getBoundingClientRect[property] + "px"; break; } // Deliberate fallthrough! default: computedValue = "0px"; break; } } return computedValue ? String(computedValue) : ""; }
function computePropertyValue(element, property) { var data = Data(element), // If computedStyle is cached, use it. If not then get the correct one // for the element to support cross-iframe boundaries. computedStyle = data.computedStyle ? data.computedStyle : data.window.getComputedStyle(element, null); var computedValue = 0; if (!data.computedStyle) { data.computedStyle = computedStyle; } if (computedStyle["display"] === "none") { switch (property) { case "width": case "height": // Browsers do not return height and width values for elements // that are set to display:"none". Thus, we temporarily toggle // display to the element type's default value. setPropertyValue(element, "display", "auto"); computedValue = getWidthHeight(element, property); setPropertyValue(element, "display", "none"); return String(computedValue); } } /* IE and Firefox do not return a value for the generic borderColor -- they only return individual values for each border side's color. Also, in all browsers, when border colors aren't all the same, a compound value is returned that Velocity isn't setup to parse. So, as a polyfill for querying individual border side colors, we just return the top border's color and animate all borders from that value. */ /* TODO: There is a borderColor normalisation in legacy/ - figure out where this is needed... */ computedValue = computedStyle[property]; /* Fall back to the property's style value (if defined) when computedValue returns nothing, which can happen when the element hasn't been painted. */ if (!computedValue) { computedValue = element.style[property]; } /* For top, right, bottom, and left (TRBL) values that are set to "auto" on elements of "fixed" or "absolute" position, defer to jQuery for converting "auto" to a numeric value. (For elements with a "static" or "relative" position, "auto" has the same effect as being set to 0, so no conversion is necessary.) */ /* An example of why numeric conversion is necessary: When an element with "position:absolute" has an untouched "left" property, which reverts to "auto", left's value is 0 relative to its parent element, but is often non-zero relative to its *containing* (not parent) element, which is the nearest "position:relative" ancestor or the viewport (and always the viewport in the case of "position:fixed"). */ if (computedValue === "auto") { switch (property) { case "width": case "height": computedValue = getWidthHeight(element, property); break; case "top": case "left": case "right": case "bottom": var position = getPropertyValue(element, "position"); if (position === "fixed" || position === "absolute") { // Note: this has no pixel unit on its returned values, // we re-add it here to conform with // computePropertyValue's behavior. computedValue = element.getBoundingClientRect[property] + "px"; break; } // Deliberate fallthrough! default: computedValue = "0px"; break; } } return computedValue ? String(computedValue) : ""; }
JavaScript
function expandProperties(animation, properties) { var tweens = animation.tweens = Object.create(null), elements = animation.elements, element = animation.element, elementArrayIndex = elements.indexOf(element), data = Data(element), queue = getValue(animation.queue, animation.options.queue), duration = getValue(animation.options.duration, defaults$1.duration); for (var property in properties) { if (properties.hasOwnProperty(property)) { var propertyName = camelCase(property), fn = getNormalization(element, propertyName); var valueData = properties[property]; if (!fn && propertyName !== "tween") { if (Velocity$$1.debug) { console.log("Skipping \"" + property + "\" due to a lack of browser support."); } continue; } if (valueData == null) { if (Velocity$$1.debug) { console.log("Skipping \"" + property + "\" due to no value supplied."); } continue; } var tween = tweens[propertyName] = {}; var endValue = void 0, startValue = void 0; tween.fn = fn; if (isFunction(valueData)) { // If we have a function as the main argument then resolve // it first, in case it returns an array that needs to be // split. valueData = valueData.call(element, elementArrayIndex, elements.length, elements); } if (Array.isArray(valueData)) { // valueData is an array in the form of // [ endValue, [, easing] [, startValue] ] var arr1 = valueData[1], arr2 = valueData[2]; endValue = valueData[0]; if (isString(arr1) && (/^[\d-]/.test(arr1) || rxHex.test(arr1)) || isFunction(arr1) || isNumber(arr1)) { startValue = arr1; } else if (isString(arr1) && Easings[arr1] || Array.isArray(arr1)) { tween.easing = validateEasing(arr1, duration); startValue = arr2; } else { startValue = arr1 || arr2; } } else { endValue = valueData; } tween.end = commands[typeof endValue === "undefined" ? "undefined" : _typeof(endValue)](endValue, element, elements, elementArrayIndex, propertyName, tween); if (startValue != null || queue === false || data.queueList[queue] === undefined) { tween.start = commands[typeof startValue === "undefined" ? "undefined" : _typeof(startValue)](startValue, element, elements, elementArrayIndex, propertyName, tween); explodeTween(propertyName, tween, duration); } } } }
function expandProperties(animation, properties) { var tweens = animation.tweens = Object.create(null), elements = animation.elements, element = animation.element, elementArrayIndex = elements.indexOf(element), data = Data(element), queue = getValue(animation.queue, animation.options.queue), duration = getValue(animation.options.duration, defaults$1.duration); for (var property in properties) { if (properties.hasOwnProperty(property)) { var propertyName = camelCase(property), fn = getNormalization(element, propertyName); var valueData = properties[property]; if (!fn && propertyName !== "tween") { if (Velocity$$1.debug) { console.log("Skipping \"" + property + "\" due to a lack of browser support."); } continue; } if (valueData == null) { if (Velocity$$1.debug) { console.log("Skipping \"" + property + "\" due to no value supplied."); } continue; } var tween = tweens[propertyName] = {}; var endValue = void 0, startValue = void 0; tween.fn = fn; if (isFunction(valueData)) { // If we have a function as the main argument then resolve // it first, in case it returns an array that needs to be // split. valueData = valueData.call(element, elementArrayIndex, elements.length, elements); } if (Array.isArray(valueData)) { // valueData is an array in the form of // [ endValue, [, easing] [, startValue] ] var arr1 = valueData[1], arr2 = valueData[2]; endValue = valueData[0]; if (isString(arr1) && (/^[\d-]/.test(arr1) || rxHex.test(arr1)) || isFunction(arr1) || isNumber(arr1)) { startValue = arr1; } else if (isString(arr1) && Easings[arr1] || Array.isArray(arr1)) { tween.easing = validateEasing(arr1, duration); startValue = arr2; } else { startValue = arr1 || arr2; } } else { endValue = valueData; } tween.end = commands[typeof endValue === "undefined" ? "undefined" : _typeof(endValue)](endValue, element, elements, elementArrayIndex, propertyName, tween); if (startValue != null || queue === false || data.queueList[queue] === undefined) { tween.start = commands[typeof startValue === "undefined" ? "undefined" : _typeof(startValue)](startValue, element, elements, elementArrayIndex, propertyName, tween); explodeTween(propertyName, tween, duration); } } } }
JavaScript
function explodeTween(propertyName, tween, duration, starting) { var startValue = tween.start, endValue = tween.end; if (!isString(endValue) || !isString(startValue)) { return; } var sequence = findPattern([startValue, endValue], propertyName); if (!sequence && starting) { // This little piece will take a startValue, split out the // various numbers in it, then copy the endValue into the // startValue while replacing the numbers in it to match the // original start numbers as a repeating sequence. // Finally this function will run again with the new // startValue and a now matching pattern. var startNumbers = startValue.match(/\d\.?\d*/g) || ["0"], count = startNumbers.length; var index = 0; sequence = findPattern([endValue.replace(/\d+\.?\d*/g, function () { return startNumbers[index++ % count]; }), endValue], propertyName); } if (sequence) { if (Velocity$$1.debug) { console.log("Velocity: Sequence found:", sequence); } sequence[0].percent = 0; sequence[1].percent = 1; tween.sequence = sequence; switch (tween.easing) { case Easings["at-start"]: case Easings["during"]: case Easings["at-end"]: sequence[0].easing = sequence[1].easing = tween.easing; break; } } }
function explodeTween(propertyName, tween, duration, starting) { var startValue = tween.start, endValue = tween.end; if (!isString(endValue) || !isString(startValue)) { return; } var sequence = findPattern([startValue, endValue], propertyName); if (!sequence && starting) { // This little piece will take a startValue, split out the // various numbers in it, then copy the endValue into the // startValue while replacing the numbers in it to match the // original start numbers as a repeating sequence. // Finally this function will run again with the new // startValue and a now matching pattern. var startNumbers = startValue.match(/\d\.?\d*/g) || ["0"], count = startNumbers.length; var index = 0; sequence = findPattern([endValue.replace(/\d+\.?\d*/g, function () { return startNumbers[index++ % count]; }), endValue], propertyName); } if (sequence) { if (Velocity$$1.debug) { console.log("Velocity: Sequence found:", sequence); } sequence[0].percent = 0; sequence[1].percent = 1; tween.sequence = sequence; switch (tween.easing) { case Easings["at-start"]: case Easings["during"]: case Easings["at-end"]: sequence[0].easing = sequence[1].easing = tween.easing; break; } } }
JavaScript
function validateTweens(activeCall) { // This might be called on an already-ready animation if (State.firstNew === activeCall) { State.firstNew = activeCall._next; } // Check if we're actually already ready if (activeCall._flags & 1 /* EXPANDED */) { // tslint:disable-line:no-bitwise return; } var element = activeCall.element, tweens = activeCall.tweens, duration = getValue(activeCall.options.duration, defaults$1.duration); // tslint:disable-next-line:forin for (var propertyName in tweens) { var tween = tweens[propertyName]; if (tween.start == null) { // Get the start value as it's not been passed in var startValue = getPropertyValue(activeCall.element, propertyName); if (isString(startValue)) { tween.start = fixColors(startValue); explodeTween(propertyName, tween, duration, true); } else if (!Array.isArray(startValue)) { console.warn("bad type", tween, propertyName, startValue); } } if (Velocity$$1.debug) { console.log("tweensContainer \"" + propertyName + "\": " + JSON.stringify(tween), element); } } activeCall._flags |= 1 /* EXPANDED */; // tslint:disable-line:no-bitwise }
function validateTweens(activeCall) { // This might be called on an already-ready animation if (State.firstNew === activeCall) { State.firstNew = activeCall._next; } // Check if we're actually already ready if (activeCall._flags & 1 /* EXPANDED */) { // tslint:disable-line:no-bitwise return; } var element = activeCall.element, tweens = activeCall.tweens, duration = getValue(activeCall.options.duration, defaults$1.duration); // tslint:disable-next-line:forin for (var propertyName in tweens) { var tween = tweens[propertyName]; if (tween.start == null) { // Get the start value as it's not been passed in var startValue = getPropertyValue(activeCall.element, propertyName); if (isString(startValue)) { tween.start = fixColors(startValue); explodeTween(propertyName, tween, duration, true); } else if (!Array.isArray(startValue)) { console.warn("bad type", tween, propertyName, startValue); } } if (Velocity$$1.debug) { console.log("tweensContainer \"" + propertyName + "\": " + JSON.stringify(tween), element); } } activeCall._flags |= 1 /* EXPANDED */; // tslint:disable-line:no-bitwise }
JavaScript
function beginCall(activeCall) { var callback = activeCall.begin || activeCall.options.begin; if (callback) { try { var elements = activeCall.elements; callback.call(elements, elements, activeCall); } catch (error) { setTimeout(function () { throw error; }, 1); } } }
function beginCall(activeCall) { var callback = activeCall.begin || activeCall.options.begin; if (callback) { try { var elements = activeCall.elements; callback.call(elements, elements, activeCall); } catch (error) { setTimeout(function () { throw error; }, 1); } } }
JavaScript
function progressCall(activeCall) { var callback = activeCall.progress || activeCall.options.progress; if (callback) { try { var elements = activeCall.elements, percentComplete = activeCall.percentComplete, options = activeCall.options, tweenValue = activeCall.tween; callback.call(elements, elements, percentComplete, Math.max(0, activeCall.timeStart + (activeCall.duration != null ? activeCall.duration : options.duration != null ? options.duration : defaults$1.duration) - lastTick), tweenValue !== undefined ? tweenValue : String(percentComplete * 100), activeCall); } catch (error) { setTimeout(function () { throw error; }, 1); } } }
function progressCall(activeCall) { var callback = activeCall.progress || activeCall.options.progress; if (callback) { try { var elements = activeCall.elements, percentComplete = activeCall.percentComplete, options = activeCall.options, tweenValue = activeCall.tween; callback.call(elements, elements, percentComplete, Math.max(0, activeCall.timeStart + (activeCall.duration != null ? activeCall.duration : options.duration != null ? options.duration : defaults$1.duration) - lastTick), tweenValue !== undefined ? tweenValue : String(percentComplete * 100), activeCall); } catch (error) { setTimeout(function () { throw error; }, 1); } } }
JavaScript
function asyncCallbacks() { var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = progressed[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var activeCall = _step.value; progressCall(activeCall); } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } progressed.clear(); var _iteratorNormalCompletion2 = true; var _didIteratorError2 = false; var _iteratorError2 = undefined; try { for (var _iterator2 = completed[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { var _activeCall = _step2.value; completeCall(_activeCall); } } catch (err) { _didIteratorError2 = true; _iteratorError2 = err; } finally { try { if (!_iteratorNormalCompletion2 && _iterator2.return) { _iterator2.return(); } } finally { if (_didIteratorError2) { throw _iteratorError2; } } } completed.clear(); }
function asyncCallbacks() { var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = progressed[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var activeCall = _step.value; progressCall(activeCall); } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } progressed.clear(); var _iteratorNormalCompletion2 = true; var _didIteratorError2 = false; var _iteratorError2 = undefined; try { for (var _iterator2 = completed[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { var _activeCall = _step2.value; completeCall(_activeCall); } } catch (err) { _didIteratorError2 = true; _iteratorError2 = err; } finally { try { if (!_iteratorNormalCompletion2 && _iterator2.return) { _iterator2.return(); } } finally { if (_didIteratorError2) { throw _iteratorError2; } } } completed.clear(); }
JavaScript
function workerFn() { var _this = this; var interval = void 0; this.onmessage = function (e) { switch (e.data) { case true: if (!interval) { interval = setInterval(function () { _this.postMessage(true); }, 1000 / 30); } break; case false: if (interval) { clearInterval(interval); interval = 0; } break; default: _this.postMessage(e.data); break; } }; }
function workerFn() { var _this = this; var interval = void 0; this.onmessage = function (e) { switch (e.data) { case true: if (!interval) { interval = setInterval(function () { _this.postMessage(true); }, 1000 / 30); } break; case false: if (interval) { clearInterval(interval); interval = 0; } break; default: _this.postMessage(e.data); break; } }; }
JavaScript
function checkAnimationShouldBeFinished(animation, queueName, defaultQueue) { validateTweens(animation); if (queueName === undefined || queueName === getValue(animation.queue, animation.options.queue, defaultQueue)) { if (!(animation._flags & 4 /* STARTED */)) { // tslint:disable-line:no-bitwise // Copied from tick.ts - ensure that the animation is completely // valid and run begin() before complete(). var options = animation.options; // The begin callback is fired once per call, not once per // element, and is passed the full raw DOM element set as both // its context and its first argument. if (options._started++ === 0) { options._first = animation; if (options.begin) { // Pass to an external fn with a try/catch block for optimisation beginCall(animation); // Only called once, even if reversed or repeated options.begin = undefined; } } animation._flags |= 4 /* STARTED */; // tslint:disable-line:no-bitwise } // tslint:disable-next-line:forin for (var property in animation.tweens) { var tween = animation.tweens[property], sequence = tween.sequence, pattern = sequence.pattern; var currentValue = "", i = 0; if (pattern) { var endValues = sequence[sequence.length - 1]; for (; i < pattern.length; i++) { var endValue = endValues[i]; currentValue += endValue == null ? pattern[i] : endValue; } } setPropertyValue(animation.element, property, currentValue, tween.fn); } completeCall(animation); } }
function checkAnimationShouldBeFinished(animation, queueName, defaultQueue) { validateTweens(animation); if (queueName === undefined || queueName === getValue(animation.queue, animation.options.queue, defaultQueue)) { if (!(animation._flags & 4 /* STARTED */)) { // tslint:disable-line:no-bitwise // Copied from tick.ts - ensure that the animation is completely // valid and run begin() before complete(). var options = animation.options; // The begin callback is fired once per call, not once per // element, and is passed the full raw DOM element set as both // its context and its first argument. if (options._started++ === 0) { options._first = animation; if (options.begin) { // Pass to an external fn with a try/catch block for optimisation beginCall(animation); // Only called once, even if reversed or repeated options.begin = undefined; } } animation._flags |= 4 /* STARTED */; // tslint:disable-line:no-bitwise } // tslint:disable-next-line:forin for (var property in animation.tweens) { var tween = animation.tweens[property], sequence = tween.sequence, pattern = sequence.pattern; var currentValue = "", i = 0; if (pattern) { var endValues = sequence[sequence.length - 1]; for (; i < pattern.length; i++) { var endValue = endValues[i]; currentValue += endValue == null ? pattern[i] : endValue; } } setPropertyValue(animation.element, property, currentValue, tween.fn); } completeCall(animation); } }
JavaScript
function finish(args, elements, promiseHandler) { var queueName = validateQueue(args[0], true), defaultQueue = defaults$1.queue, finishAll = args[queueName === undefined ? 0 : 1] === true; if (isVelocityResult(elements) && elements.velocity.animations) { var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = elements.velocity.animations[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var animation = _step.value; checkAnimationShouldBeFinished(animation, queueName, defaultQueue); } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } } else { while (State.firstNew) { validateTweens(State.firstNew); } for (var activeCall = State.first, nextCall; activeCall && (finishAll || activeCall !== State.firstNew); activeCall = nextCall || State.firstNew) { nextCall = activeCall._next; if (!elements || elements.includes(activeCall.element)) { checkAnimationShouldBeFinished(activeCall, queueName, defaultQueue); } } } if (promiseHandler) { if (isVelocityResult(elements) && elements.velocity.animations && elements.then) { elements.then(promiseHandler._resolver); } else { promiseHandler._resolver(elements); } } }
function finish(args, elements, promiseHandler) { var queueName = validateQueue(args[0], true), defaultQueue = defaults$1.queue, finishAll = args[queueName === undefined ? 0 : 1] === true; if (isVelocityResult(elements) && elements.velocity.animations) { var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = elements.velocity.animations[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var animation = _step.value; checkAnimationShouldBeFinished(animation, queueName, defaultQueue); } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } } else { while (State.firstNew) { validateTweens(State.firstNew); } for (var activeCall = State.first, nextCall; activeCall && (finishAll || activeCall !== State.firstNew); activeCall = nextCall || State.firstNew) { nextCall = activeCall._next; if (!elements || elements.includes(activeCall.element)) { checkAnimationShouldBeFinished(activeCall, queueName, defaultQueue); } } } if (promiseHandler) { if (isVelocityResult(elements) && elements.velocity.animations && elements.then) { elements.then(promiseHandler._resolver); } else { promiseHandler._resolver(elements); } } }
JavaScript
function option(args, elements, promiseHandler, action) { var key = args[0], queue = action.indexOf(".") >= 0 ? action.replace(/^.*\./, "") : undefined, queueName = queue === "false" ? false : validateQueue(queue, true); var animations = void 0, value = args[1]; if (!key) { console.warn("VelocityJS: Cannot access a non-existant key!"); return null; } // If we're chaining the return value from Velocity then we are only // interested in the values related to that call if (isVelocityResult(elements) && elements.velocity.animations) { animations = elements.velocity.animations; } else { animations = []; for (var activeCall = State.first; activeCall; activeCall = activeCall._next) { if (elements.indexOf(activeCall.element) >= 0 && getValue(activeCall.queue, activeCall.options.queue) === queueName) { animations.push(activeCall); } } // If we're dealing with multiple elements that are pointing at a // single running animation, then instead treat them as a single // animation. if (elements.length > 1 && animations.length > 1) { var i = 1, options = animations[0].options; while (i < animations.length) { if (animations[i++].options !== options) { options = null; break; } } // TODO: this needs to check that they're actually a sync:true animation to merge the results, otherwise the individual values may be different if (options) { animations = [animations[0]]; } } } // GET if (value === undefined) { var result = [], flag = animationFlags[key]; var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = animations[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var animation = _step.value; if (flag === undefined) { // A normal key to get. result.push(getValue(animation[key], animation.options[key])); } else { // A flag that we're checking against. result.push((animation._flags & flag) === 0); // tslint:disable-line:no-bitwise } } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } if (elements.length === 1 && animations.length === 1) { // If only a single animation is found and we're only targetting a // single element, then return the value directly return result[0]; } return result; } // SET var isPercentComplete = void 0; switch (key) { case "cache": value = validateCache(value); break; case "begin": value = validateBegin(value); break; case "complete": value = validateComplete(value); break; case "delay": value = validateDelay(value); break; case "duration": value = validateDuration(value); break; case "fpsLimit": value = validateFpsLimit(value); break; case "loop": value = validateLoop(value); break; case "percentComplete": isPercentComplete = true; value = parseFloat(value); break; case "repeat": case "repeatAgain": value = validateRepeat(value); break; default: if (key[0] !== "_") { var num = parseFloat(value); if (value === String(num)) { value = num; } break; } // deliberate fallthrough case "queue": case "promise": case "promiseRejectEmpty": case "easing": case "started": console.warn("VelocityJS: Trying to set a read-only key:", key); return; } if (value === undefined || value !== value) { console.warn("VelocityJS: Trying to set an invalid value:" + key + "=" + value + " (" + args[1] + ")"); return null; } var _iteratorNormalCompletion2 = true; var _didIteratorError2 = false; var _iteratorError2 = undefined; try { for (var _iterator2 = animations[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { var _animation = _step2.value; if (isPercentComplete) { _animation.timeStart = lastTick - getValue(_animation.duration, _animation.options.duration, defaults$1.duration) * value; } else { _animation[key] = value; } } } catch (err) { _didIteratorError2 = true; _iteratorError2 = err; } finally { try { if (!_iteratorNormalCompletion2 && _iterator2.return) { _iterator2.return(); } } finally { if (_didIteratorError2) { throw _iteratorError2; } } } if (promiseHandler) { if (isVelocityResult(elements) && elements.velocity.animations && elements.then) { elements.then(promiseHandler._resolver); } else { promiseHandler._resolver(elements); } } }
function option(args, elements, promiseHandler, action) { var key = args[0], queue = action.indexOf(".") >= 0 ? action.replace(/^.*\./, "") : undefined, queueName = queue === "false" ? false : validateQueue(queue, true); var animations = void 0, value = args[1]; if (!key) { console.warn("VelocityJS: Cannot access a non-existant key!"); return null; } // If we're chaining the return value from Velocity then we are only // interested in the values related to that call if (isVelocityResult(elements) && elements.velocity.animations) { animations = elements.velocity.animations; } else { animations = []; for (var activeCall = State.first; activeCall; activeCall = activeCall._next) { if (elements.indexOf(activeCall.element) >= 0 && getValue(activeCall.queue, activeCall.options.queue) === queueName) { animations.push(activeCall); } } // If we're dealing with multiple elements that are pointing at a // single running animation, then instead treat them as a single // animation. if (elements.length > 1 && animations.length > 1) { var i = 1, options = animations[0].options; while (i < animations.length) { if (animations[i++].options !== options) { options = null; break; } } // TODO: this needs to check that they're actually a sync:true animation to merge the results, otherwise the individual values may be different if (options) { animations = [animations[0]]; } } } // GET if (value === undefined) { var result = [], flag = animationFlags[key]; var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = animations[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var animation = _step.value; if (flag === undefined) { // A normal key to get. result.push(getValue(animation[key], animation.options[key])); } else { // A flag that we're checking against. result.push((animation._flags & flag) === 0); // tslint:disable-line:no-bitwise } } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } if (elements.length === 1 && animations.length === 1) { // If only a single animation is found and we're only targetting a // single element, then return the value directly return result[0]; } return result; } // SET var isPercentComplete = void 0; switch (key) { case "cache": value = validateCache(value); break; case "begin": value = validateBegin(value); break; case "complete": value = validateComplete(value); break; case "delay": value = validateDelay(value); break; case "duration": value = validateDuration(value); break; case "fpsLimit": value = validateFpsLimit(value); break; case "loop": value = validateLoop(value); break; case "percentComplete": isPercentComplete = true; value = parseFloat(value); break; case "repeat": case "repeatAgain": value = validateRepeat(value); break; default: if (key[0] !== "_") { var num = parseFloat(value); if (value === String(num)) { value = num; } break; } // deliberate fallthrough case "queue": case "promise": case "promiseRejectEmpty": case "easing": case "started": console.warn("VelocityJS: Trying to set a read-only key:", key); return; } if (value === undefined || value !== value) { console.warn("VelocityJS: Trying to set an invalid value:" + key + "=" + value + " (" + args[1] + ")"); return null; } var _iteratorNormalCompletion2 = true; var _didIteratorError2 = false; var _iteratorError2 = undefined; try { for (var _iterator2 = animations[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { var _animation = _step2.value; if (isPercentComplete) { _animation.timeStart = lastTick - getValue(_animation.duration, _animation.options.duration, defaults$1.duration) * value; } else { _animation[key] = value; } } } catch (err) { _didIteratorError2 = true; _iteratorError2 = err; } finally { try { if (!_iteratorNormalCompletion2 && _iterator2.return) { _iterator2.return(); } } finally { if (_didIteratorError2) { throw _iteratorError2; } } } if (promiseHandler) { if (isVelocityResult(elements) && elements.velocity.animations && elements.then) { elements.then(promiseHandler._resolver); } else { promiseHandler._resolver(elements); } } }
JavaScript
function checkAnimation(animation, queueName, defaultQueue, isPaused) { if (queueName === undefined || queueName === getValue(animation.queue, animation.options.queue, defaultQueue)) { if (isPaused) { animation._flags |= 16 /* PAUSED */; // tslint:disable-line:no-bitwise } else { animation._flags &= ~16 /* PAUSED */; // tslint:disable-line:no-bitwise } } }
function checkAnimation(animation, queueName, defaultQueue, isPaused) { if (queueName === undefined || queueName === getValue(animation.queue, animation.options.queue, defaultQueue)) { if (isPaused) { animation._flags |= 16 /* PAUSED */; // tslint:disable-line:no-bitwise } else { animation._flags &= ~16 /* PAUSED */; // tslint:disable-line:no-bitwise } } }
JavaScript
function pauseResume(args, elements, promiseHandler, action) { var isPaused = action.indexOf("pause") === 0, queue = action.indexOf(".") >= 0 ? action.replace(/^.*\./, "") : undefined, queueName = queue === "false" ? false : validateQueue(args[0]), defaultQueue = defaults$1.queue; if (isVelocityResult(elements) && elements.velocity.animations) { var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = elements.velocity.animations[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var animation = _step.value; checkAnimation(animation, queueName, defaultQueue, isPaused); } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } } else { var activeCall = State.first; while (activeCall) { if (!elements || elements.includes(activeCall.element)) { checkAnimation(activeCall, queueName, defaultQueue, isPaused); } activeCall = activeCall._next; } } if (promiseHandler) { if (isVelocityResult(elements) && elements.velocity.animations && elements.then) { elements.then(promiseHandler._resolver); } else { promiseHandler._resolver(elements); } } }
function pauseResume(args, elements, promiseHandler, action) { var isPaused = action.indexOf("pause") === 0, queue = action.indexOf(".") >= 0 ? action.replace(/^.*\./, "") : undefined, queueName = queue === "false" ? false : validateQueue(args[0]), defaultQueue = defaults$1.queue; if (isVelocityResult(elements) && elements.velocity.animations) { var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = elements.velocity.animations[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var animation = _step.value; checkAnimation(animation, queueName, defaultQueue, isPaused); } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } } else { var activeCall = State.first; while (activeCall) { if (!elements || elements.includes(activeCall.element)) { checkAnimation(activeCall, queueName, defaultQueue, isPaused); } activeCall = activeCall._next; } } if (promiseHandler) { if (isVelocityResult(elements) && elements.velocity.animations && elements.then) { elements.then(promiseHandler._resolver); } else { promiseHandler._resolver(elements); } } }
JavaScript
function checkAnimationShouldBeStopped(animation, queueName, defaultQueue) { validateTweens(animation); if (queueName === undefined || queueName === getValue(animation.queue, animation.options.queue, defaultQueue)) { animation._flags |= 8 /* STOPPED */; // tslint:disable-line:no-bitwise completeCall(animation); } }
function checkAnimationShouldBeStopped(animation, queueName, defaultQueue) { validateTweens(animation); if (queueName === undefined || queueName === getValue(animation.queue, animation.options.queue, defaultQueue)) { animation._flags |= 8 /* STOPPED */; // tslint:disable-line:no-bitwise completeCall(animation); } }
JavaScript
function stop(args, elements, promiseHandler, action) { var queueName = validateQueue(args[0], true), defaultQueue = defaults$1.queue, finishAll = args[queueName === undefined ? 0 : 1] === true; if (isVelocityResult(elements) && elements.velocity.animations) { var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = elements.velocity.animations[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var animation = _step.value; checkAnimationShouldBeStopped(animation, queueName, defaultQueue); } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } } else { while (State.firstNew) { validateTweens(State.firstNew); } for (var activeCall = State.first, nextCall; activeCall && (finishAll || activeCall !== State.firstNew); activeCall = nextCall || State.firstNew) { nextCall = activeCall._next; if (!elements || elements.includes(activeCall.element)) { checkAnimationShouldBeStopped(activeCall, queueName, defaultQueue); } } } if (promiseHandler) { if (isVelocityResult(elements) && elements.velocity.animations && elements.then) { elements.then(promiseHandler._resolver); } else { promiseHandler._resolver(elements); } } }
function stop(args, elements, promiseHandler, action) { var queueName = validateQueue(args[0], true), defaultQueue = defaults$1.queue, finishAll = args[queueName === undefined ? 0 : 1] === true; if (isVelocityResult(elements) && elements.velocity.animations) { var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = elements.velocity.animations[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var animation = _step.value; checkAnimationShouldBeStopped(animation, queueName, defaultQueue); } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } } else { while (State.firstNew) { validateTweens(State.firstNew); } for (var activeCall = State.first, nextCall; activeCall && (finishAll || activeCall !== State.firstNew); activeCall = nextCall || State.firstNew) { nextCall = activeCall._next; if (!elements || elements.includes(activeCall.element)) { checkAnimationShouldBeStopped(activeCall, queueName, defaultQueue); } } } if (promiseHandler) { if (isVelocityResult(elements) && elements.velocity.animations && elements.then) { elements.then(promiseHandler._resolver); } else { promiseHandler._resolver(elements); } } }
JavaScript
function patchPromise(promiseObject, result) { defineProperty$1(result, "promise", promiseObject); defineProperty$1(result, "then", promiseObject.then.bind(promiseObject)); defineProperty$1(result, "catch", promiseObject.catch.bind(promiseObject)); if (promiseObject.finally) { // Semi-standard defineProperty$1(result, "finally", promiseObject.finally.bind(promiseObject)); } }
function patchPromise(promiseObject, result) { defineProperty$1(result, "promise", promiseObject); defineProperty$1(result, "then", promiseObject.then.bind(promiseObject)); defineProperty$1(result, "catch", promiseObject.catch.bind(promiseObject)); if (promiseObject.finally) { // Semi-standard defineProperty$1(result, "finally", promiseObject.finally.bind(promiseObject)); } }
JavaScript
function optionCallback(fn, element, index, length, elements, option) { try { return fn.call(element, index, length, elements, option); } catch (e) { console.error("VelocityJS: Exception when calling '" + option + "' callback:", e); } }
function optionCallback(fn, element, index, length, elements, option) { try { return fn.call(element, index, length, elements, option); } catch (e) { console.error("VelocityJS: Exception when calling '" + option + "' callback:", e); } }
JavaScript
function patch(proto, global) { try { defineProperty$1(proto, (global ? "V" : "v") + "elocity", Velocity$1); } catch (e) { console.warn("VelocityJS: Error when trying to add prototype.", e); } }
function patch(proto, global) { try { defineProperty$1(proto, (global ? "V" : "v") + "elocity", Velocity$1); } catch (e) { console.warn("VelocityJS: Error when trying to add prototype.", e); } }
JavaScript
function noRedir() { var links = document.getElementsByTagName('a'); for (var i = 0; i < links.length; i++) { links[i].onclick = function(e) { var node = e.target; while (!('href' in node)) { node = node.parentNode; } var commentsContainer = document.getElementById('comments-container'); var commentsNode = document.getElementById('comments'); var contentNode = document.getElementById('content'); for (var i = 0; i < contentNode.children.length; i++) { var child = contentNode.children[i]; if (child.classList.contains('adv-desc')) { child.style.display = 'none'; } } var homeNode = document.getElementById('home'); // Reload contents into page if (node.href.includes('#')) { window.history.pushState('', '', '#'); homeNode.style.display = 'block'; commentsContainer.style.display = 'block'; commentsNode.style.display = 'block'; } else if ( node.href.includes('javascript:') || node.href.includes('mailto:')) { homeNode.style.display = 'block'; commentsContainer.style.display = 'block'; commentsNode.style.display = 'block'; return true; // Want the javascript the activate } else { homeNode.style.display = 'none'; commentsNode.style.display = 'none'; commentsContainer.style.display = 'none'; addContentToId('content', node.href + '.html', node.href); } return false; } } }
function noRedir() { var links = document.getElementsByTagName('a'); for (var i = 0; i < links.length; i++) { links[i].onclick = function(e) { var node = e.target; while (!('href' in node)) { node = node.parentNode; } var commentsContainer = document.getElementById('comments-container'); var commentsNode = document.getElementById('comments'); var contentNode = document.getElementById('content'); for (var i = 0; i < contentNode.children.length; i++) { var child = contentNode.children[i]; if (child.classList.contains('adv-desc')) { child.style.display = 'none'; } } var homeNode = document.getElementById('home'); // Reload contents into page if (node.href.includes('#')) { window.history.pushState('', '', '#'); homeNode.style.display = 'block'; commentsContainer.style.display = 'block'; commentsNode.style.display = 'block'; } else if ( node.href.includes('javascript:') || node.href.includes('mailto:')) { homeNode.style.display = 'block'; commentsContainer.style.display = 'block'; commentsNode.style.display = 'block'; return true; // Want the javascript the activate } else { homeNode.style.display = 'none'; commentsNode.style.display = 'none'; commentsContainer.style.display = 'none'; addContentToId('content', node.href + '.html', node.href); } return false; } } }
JavaScript
function filtraArray() { return function (items,sName) { var iLenTotal= 0; var aSearch= sName; for (var i = 0; i < sName.length; i++) { aSearch[i] = String( sName[i] ).toLowerCase(); iLenTotal+= aSearch[i].length; } //console.log( "aSearch",aSearch ,'iLenTotal',iLenTotal ) if( iLenTotal== 0 ) { //console.log( "filter:empty" ) //console.log( "aSearch",aSearch ) return items; } var filtered = []; for (var j = 0; j < items.length; j++){ var item = items[j]; var skipRow= false; for (var i = 0; i < aSearch.length; i++) { var str= String( item[i] ).toLowerCase(); var iPos= str.indexOf( aSearch[i] ) if( iPos <0 ){ skipRow= true; //console.log( "skipped search" ,aSearch[i] ," ->" ,str ) break; } } if( skipRow === false ) filtered.push(item) } return filtered; }; }
function filtraArray() { return function (items,sName) { var iLenTotal= 0; var aSearch= sName; for (var i = 0; i < sName.length; i++) { aSearch[i] = String( sName[i] ).toLowerCase(); iLenTotal+= aSearch[i].length; } //console.log( "aSearch",aSearch ,'iLenTotal',iLenTotal ) if( iLenTotal== 0 ) { //console.log( "filter:empty" ) //console.log( "aSearch",aSearch ) return items; } var filtered = []; for (var j = 0; j < items.length; j++){ var item = items[j]; var skipRow= false; for (var i = 0; i < aSearch.length; i++) { var str= String( item[i] ).toLowerCase(); var iPos= str.indexOf( aSearch[i] ) if( iPos <0 ){ skipRow= true; //console.log( "skipped search" ,aSearch[i] ," ->" ,str ) break; } } if( skipRow === false ) filtered.push(item) } return filtered; }; }
JavaScript
function refrescaDiv(div,segs,url) { // define our vars var div,segs,url,fetch_unix_timestamp; // Chequeamos que las variables no esten vacias.. if(div == ""){ alert('Error: escribe el id del div que quieres refrescar'); return;} else if(!document.getElementById(div)){ alert('Error: el Div ID selectionado no esta definido: '+div); return;} else if(segs == ""){ alert('Error: indica la cantidad de segundos que quieres que el div se refresque'); return;} else if(url == ""){ alert('Error: la URL del documento que quieres cargar en el div no puede estar vacia.'); return;} // The XMLHttpRequest object var xmlHttp; try { xmlHttp=new XMLHttpRequest(); // Firefox, Opera 8.0+, Safari } catch (e) { try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer } catch (e) { try { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } catch (e){ alert("Tu explorador no soporta AJAX."); return false; } } } // Timestamp para evitar que se cachee el array GET fetch_unix_timestamp = function() { return parseInt(new Date().getTime().toString().substring(0, 10)) } var timestamp = fetch_unix_timestamp(); var nocacheurl = url+"?t="+timestamp; // the ajax call xmlHttp.onreadystatechange=function() { if(xmlHttp.readyState == 4 && xmlHttp.status == 200) { //alert("responseText: "+xmlHttp.responseText); if(xmlHttp.responseText == "Salir") { window.location='index.php?cnt=Sesion&act=cierreforzado'; //alert('Sesi\u00f3n expirada!'); } else { document.getElementById(div).innerHTML=xmlHttp.responseText; } setTimeout(function(){refrescaDiv(div,segs,url);},segs*1000); } } xmlHttp.open("GET",nocacheurl,true); xmlHttp.send(null); }
function refrescaDiv(div,segs,url) { // define our vars var div,segs,url,fetch_unix_timestamp; // Chequeamos que las variables no esten vacias.. if(div == ""){ alert('Error: escribe el id del div que quieres refrescar'); return;} else if(!document.getElementById(div)){ alert('Error: el Div ID selectionado no esta definido: '+div); return;} else if(segs == ""){ alert('Error: indica la cantidad de segundos que quieres que el div se refresque'); return;} else if(url == ""){ alert('Error: la URL del documento que quieres cargar en el div no puede estar vacia.'); return;} // The XMLHttpRequest object var xmlHttp; try { xmlHttp=new XMLHttpRequest(); // Firefox, Opera 8.0+, Safari } catch (e) { try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer } catch (e) { try { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } catch (e){ alert("Tu explorador no soporta AJAX."); return false; } } } // Timestamp para evitar que se cachee el array GET fetch_unix_timestamp = function() { return parseInt(new Date().getTime().toString().substring(0, 10)) } var timestamp = fetch_unix_timestamp(); var nocacheurl = url+"?t="+timestamp; // the ajax call xmlHttp.onreadystatechange=function() { if(xmlHttp.readyState == 4 && xmlHttp.status == 200) { //alert("responseText: "+xmlHttp.responseText); if(xmlHttp.responseText == "Salir") { window.location='index.php?cnt=Sesion&act=cierreforzado'; //alert('Sesi\u00f3n expirada!'); } else { document.getElementById(div).innerHTML=xmlHttp.responseText; } setTimeout(function(){refrescaDiv(div,segs,url);},segs*1000); } } xmlHttp.open("GET",nocacheurl,true); xmlHttp.send(null); }
JavaScript
_autoAnimate(auto) { if (auto) { this._autoInterval = setInterval(() => { this.next(); }, this.duration); } else { clearInterval(this._autoInterval); } }
_autoAnimate(auto) { if (auto) { this._autoInterval = setInterval(() => { this.next(); }, this.duration); } else { clearInterval(this._autoInterval); } }
JavaScript
_drag(event) { if (this.disableSwipe || this.disabled) { // Reset selected to original in case is changed while dragging this._x = 0; this._y = 0; this._setSwiping(false); return; } const width = this.offsetWidth; const height = this.offsetHeight; const x = event.detail.ddx ? event.detail.ddx : 0; const y = event.detail.ddy ? event.detail.ddy : 0; let finalX = x / width; let finalY = y / height; let finalLeft = 0; let finalTop = 0; if (this.direction === 'horizontal') finalLeft = this._x + finalX; if (this.direction === 'vertical') finalTop = this._y + finalY; let finalPositionLeft = Number(finalLeft); let finalPositionTop = Number(finalTop); // Prevent drag to the wrong direction if is not available if (!this.showPrev) { if (finalPositionLeft > 0) { finalPositionLeft = 0; } if (finalPositionTop > 0) { finalPositionTop = 0; } } if (!this.showNext) { if (finalPositionLeft < 0) { finalPositionLeft = 0; } if (finalPositionTop < 0) { finalPositionTop = 0; } } switch (event.detail.state) { case 'track': this._autoAnimate(false); this._x = finalPositionLeft; this._y = finalPositionTop; this._setSwiping(true); break; case 'end': this._autoAnimate(this.auto); this._x = 0; this._y = 0; this._setSwiping(false); if (finalPositionLeft >= 0.1 || finalPositionTop >= 0.1) { this.prev(); } else if (finalPositionLeft <= -0.1 || finalPositionTop <= -0.1) { this.next(); } break; } }
_drag(event) { if (this.disableSwipe || this.disabled) { // Reset selected to original in case is changed while dragging this._x = 0; this._y = 0; this._setSwiping(false); return; } const width = this.offsetWidth; const height = this.offsetHeight; const x = event.detail.ddx ? event.detail.ddx : 0; const y = event.detail.ddy ? event.detail.ddy : 0; let finalX = x / width; let finalY = y / height; let finalLeft = 0; let finalTop = 0; if (this.direction === 'horizontal') finalLeft = this._x + finalX; if (this.direction === 'vertical') finalTop = this._y + finalY; let finalPositionLeft = Number(finalLeft); let finalPositionTop = Number(finalTop); // Prevent drag to the wrong direction if is not available if (!this.showPrev) { if (finalPositionLeft > 0) { finalPositionLeft = 0; } if (finalPositionTop > 0) { finalPositionTop = 0; } } if (!this.showNext) { if (finalPositionLeft < 0) { finalPositionLeft = 0; } if (finalPositionTop < 0) { finalPositionTop = 0; } } switch (event.detail.state) { case 'track': this._autoAnimate(false); this._x = finalPositionLeft; this._y = finalPositionTop; this._setSwiping(true); break; case 'end': this._autoAnimate(this.auto); this._x = 0; this._y = 0; this._setSwiping(false); if (finalPositionLeft >= 0.1 || finalPositionTop >= 0.1) { this.prev(); } else if (finalPositionLeft <= -0.1 || finalPositionTop <= -0.1) { this.next(); } break; } }
JavaScript
function arrowTranslate(d){ if(d.arrow === undefined || d.arrow === ARROW.NONE ){ return; } //make the scale of the arrow a function of the line width var arrow_scale; if(layer.lineWidth() <=2){ arrow_scale = 0; }else if(layer.lineWidth() <= 4){ arrow_scale = 2; }else if(layer.lineWidth() <= 6){ arrow_scale = 3; }else{ arrow_scale = 4; } var path = d3.select(this.parentNode).select("path").filter(".adjacencyShadow")[0][0]; var p = path.getPointAtLength(path.getTotalLength()/2); //look after the midpoint in the path (away from A) to get our angle var p2 = path.getPointAtLength((path.getTotalLength()/2)+12); //if Z is passing more traffic, look before the midpoint to get the angle away from Z if(d.arrow == ARROW.ZA){ p2 = path.getPointAtLength((path.getTotalLength()/2)-12); } var angle = getAngle(p,p2); //this works b/c it we know the ratio of the height/width of the arrow is 2 to 1 //initially it's rendered with the top left corner of its bounding box centered on p //so we need to shift it left and up the arrows width and height respectively p.y -= 1 * arrow_scale; p.x -= 2 * arrow_scale; return "translate(" + p.x+','+p.y+ ") scale("+arrow_scale+") rotate("+angle+",2,1)" }
function arrowTranslate(d){ if(d.arrow === undefined || d.arrow === ARROW.NONE ){ return; } //make the scale of the arrow a function of the line width var arrow_scale; if(layer.lineWidth() <=2){ arrow_scale = 0; }else if(layer.lineWidth() <= 4){ arrow_scale = 2; }else if(layer.lineWidth() <= 6){ arrow_scale = 3; }else{ arrow_scale = 4; } var path = d3.select(this.parentNode).select("path").filter(".adjacencyShadow")[0][0]; var p = path.getPointAtLength(path.getTotalLength()/2); //look after the midpoint in the path (away from A) to get our angle var p2 = path.getPointAtLength((path.getTotalLength()/2)+12); //if Z is passing more traffic, look before the midpoint to get the angle away from Z if(d.arrow == ARROW.ZA){ p2 = path.getPointAtLength((path.getTotalLength()/2)-12); } var angle = getAngle(p,p2); //this works b/c it we know the ratio of the height/width of the arrow is 2 to 1 //initially it's rendered with the top left corner of its bounding box centered on p //so we need to shift it left and up the arrows width and height respectively p.y -= 1 * arrow_scale; p.x -= 2 * arrow_scale; return "translate(" + p.x+','+p.y+ ") scale("+arrow_scale+") rotate("+angle+",2,1)" }
JavaScript
function vertexFind(region, width, height, flatHex ){ if(flatHex){ return { x: flatHexVertexScalar[region - 1][0] * width, y: flatHexVertexScalar[region - 1][1] * height } } else{ return { x: pointHexVertexScalar[region - 1][0] * width, y: pointHexVertexScalar[region - 1][1] * height } } }
function vertexFind(region, width, height, flatHex ){ if(flatHex){ return { x: flatHexVertexScalar[region - 1][0] * width, y: flatHexVertexScalar[region - 1][1] * height } } else{ return { x: pointHexVertexScalar[region - 1][0] * width, y: pointHexVertexScalar[region - 1][1] * height } } }
JavaScript
function changeColor(){ let button = document.getElementById('target') var red =Math.floor(Math.random() * 256) var green = Math.floor(Math.random() * 256) var blue = Math.floor(Math.random()* 256) var redGreenBlue = 'rgb('+ red +', '+ green+', '+ blue +')' button.style.backgroundColor = redGreenBlue }
function changeColor(){ let button = document.getElementById('target') var red =Math.floor(Math.random() * 256) var green = Math.floor(Math.random() * 256) var blue = Math.floor(Math.random()* 256) var redGreenBlue = 'rgb('+ red +', '+ green+', '+ blue +')' button.style.backgroundColor = redGreenBlue }
JavaScript
set subDenominationOrder(sdo){ sdo = parseInt(sdo); if(is.nan(sdo) || is.not.number(sdo)){ throw new TypeError('subDenominationOrder must be a whole number greater than or equal to zero'); } if(sdo < 0){ throw new RangeError("subDomainOrder can't be negative"); } this._subDenominationOrder = sdo; if(sdo === 0){ this._subDenomination = null; } }
set subDenominationOrder(sdo){ sdo = parseInt(sdo); if(is.nan(sdo) || is.not.number(sdo)){ throw new TypeError('subDenominationOrder must be a whole number greater than or equal to zero'); } if(sdo < 0){ throw new RangeError("subDomainOrder can't be negative"); } this._subDenominationOrder = sdo; if(sdo === 0){ this._subDenomination = null; } }
JavaScript
splitAmount(amount){ amount = parseFloat(amount); if(is.nan(amount)) throw new TypeError('amount must be a number'); // short-circuit the simple case were there is no seconardy denomination if(this.subDenominationOrder === 0){ return [Math.round(amount), 0]; } // short-circuit the case where the amount is an integer if(is.integer(amount)){ return [amount, 0]; } // // calculate the primary amount // // NOTE - Math.floor() does not behave as expected with negative numbers // so need the absolute value before flooring. // keep a record of whether or not the amount is negative const isNegative = amount < 0; // get the absolute value of the amount const absAmount = Math.abs(amount); // get the absolute and actual values of the primary amount const absPrimaryAmount = Math.floor(absAmount); let primaryAmount = isNegative ? 0 - absPrimaryAmount : absPrimaryAmount; // // calculate the secondary amount // // start with just the decimal part of the amount, e.g. 0.123 let secondaryAmount = Math.abs(amount) - absPrimaryAmount; // calculate the number of secondary units in one primary based on the order const numSecInPri = Math.pow(10, this.subDenominationOrder); // e.g. 100 // multiply by the number of secondary units in one primary, e.g. 12.3 secondaryAmount *= numSecInPri; // round to the nearest whole number, e.g. 12 secondaryAmount = Math.round(secondaryAmount); // deal with the special case where the secondary amount gets rounded // up to be a whole primary unit if(secondaryAmount === numSecInPri){ secondaryAmount = 0; if(isNegative){ primaryAmount--; }else{ primaryAmount++; } } // return the two amounts return [primaryAmount, secondaryAmount]; }
splitAmount(amount){ amount = parseFloat(amount); if(is.nan(amount)) throw new TypeError('amount must be a number'); // short-circuit the simple case were there is no seconardy denomination if(this.subDenominationOrder === 0){ return [Math.round(amount), 0]; } // short-circuit the case where the amount is an integer if(is.integer(amount)){ return [amount, 0]; } // // calculate the primary amount // // NOTE - Math.floor() does not behave as expected with negative numbers // so need the absolute value before flooring. // keep a record of whether or not the amount is negative const isNegative = amount < 0; // get the absolute value of the amount const absAmount = Math.abs(amount); // get the absolute and actual values of the primary amount const absPrimaryAmount = Math.floor(absAmount); let primaryAmount = isNegative ? 0 - absPrimaryAmount : absPrimaryAmount; // // calculate the secondary amount // // start with just the decimal part of the amount, e.g. 0.123 let secondaryAmount = Math.abs(amount) - absPrimaryAmount; // calculate the number of secondary units in one primary based on the order const numSecInPri = Math.pow(10, this.subDenominationOrder); // e.g. 100 // multiply by the number of secondary units in one primary, e.g. 12.3 secondaryAmount *= numSecInPri; // round to the nearest whole number, e.g. 12 secondaryAmount = Math.round(secondaryAmount); // deal with the special case where the secondary amount gets rounded // up to be a whole primary unit if(secondaryAmount === numSecInPri){ secondaryAmount = 0; if(isNegative){ primaryAmount--; }else{ primaryAmount++; } } // return the two amounts return [primaryAmount, secondaryAmount]; }
JavaScript
amountAsString(amount){ amount = parseFloat(amount); // build and return the string let ans = `${is.negative(amount) ? '-' : ''}${this.denomination.symbol}`; ans += this.amountAsHumanFloat(Math.abs(amount)); return ans; }
amountAsString(amount){ amount = parseFloat(amount); // build and return the string let ans = `${is.negative(amount) ? '-' : ''}${this.denomination.symbol}`; ans += this.amountAsHumanFloat(Math.abs(amount)); return ans; }
JavaScript
splitAmount(amount){ amount = this.constructor.coerceAmount(amount); // could throw error // short-circuit the simple case were there is no seconardy denomination if(this.subDenominationOrder === 0){ return [Math.round(amount), 0]; } // short-circuit the case where the amount is an integer if(is.integer(amount)){ return [amount, 0]; } // NOTE - Math.floor() does not behave as expected with negative numbers // so need the absolute value before flooring. // keep a record of whether or not the amount is negative const isNegative = amount < 0; // // calculate the primary amount // // get the absolute value of the amount const absAmount = Math.abs(amount); // get the absolute and actual values of the primary amount const absPrimaryAmount = Math.floor(absAmount); // // calculate the secondary amount // // start with just the decimal part of the amount, e.g. 0.123 let absSecondaryAmount = Math.abs(amount) - absPrimaryAmount; // calculate the number of secondary units in one primary based on the order const numSecInPri = Math.pow(10, this.subDenominationOrder); // e.g. 100 // multiply by the number of secondary units in one primary, e.g. 12.3 absSecondaryAmount *= numSecInPri; // round to the nearest whole number, e.g. 12 absSecondaryAmount = Math.round(absSecondaryAmount); // deal with the special case where the secondary amount gets rounded // up to be a whole primary unit if(absSecondaryAmount === numSecInPri){ absSecondaryAmount = 0; absPrimaryAmount++; } // re-negate if needed let primaryAmount = isNegative ? 0 - absPrimaryAmount : absPrimaryAmount; let secondaryAmount = isNegative ? 0 - absSecondaryAmount : absSecondaryAmount; // return the two amounts return [primaryAmount, secondaryAmount]; }
splitAmount(amount){ amount = this.constructor.coerceAmount(amount); // could throw error // short-circuit the simple case were there is no seconardy denomination if(this.subDenominationOrder === 0){ return [Math.round(amount), 0]; } // short-circuit the case where the amount is an integer if(is.integer(amount)){ return [amount, 0]; } // NOTE - Math.floor() does not behave as expected with negative numbers // so need the absolute value before flooring. // keep a record of whether or not the amount is negative const isNegative = amount < 0; // // calculate the primary amount // // get the absolute value of the amount const absAmount = Math.abs(amount); // get the absolute and actual values of the primary amount const absPrimaryAmount = Math.floor(absAmount); // // calculate the secondary amount // // start with just the decimal part of the amount, e.g. 0.123 let absSecondaryAmount = Math.abs(amount) - absPrimaryAmount; // calculate the number of secondary units in one primary based on the order const numSecInPri = Math.pow(10, this.subDenominationOrder); // e.g. 100 // multiply by the number of secondary units in one primary, e.g. 12.3 absSecondaryAmount *= numSecInPri; // round to the nearest whole number, e.g. 12 absSecondaryAmount = Math.round(absSecondaryAmount); // deal with the special case where the secondary amount gets rounded // up to be a whole primary unit if(absSecondaryAmount === numSecInPri){ absSecondaryAmount = 0; absPrimaryAmount++; } // re-negate if needed let primaryAmount = isNegative ? 0 - absPrimaryAmount : absPrimaryAmount; let secondaryAmount = isNegative ? 0 - absSecondaryAmount : absSecondaryAmount; // return the two amounts return [primaryAmount, secondaryAmount]; }
JavaScript
amountAsString(amount){ amount = this.constructor.coerceAmount(amount); // could throw error // build and return the string let ans = `${is.negative(amount) ? '-' : ''}${this.denomination.symbol}`; ans += this.amountAsHumanFloat(Math.abs(amount)); return ans; }
amountAsString(amount){ amount = this.constructor.coerceAmount(amount); // could throw error // build and return the string let ans = `${is.negative(amount) ? '-' : ''}${this.denomination.symbol}`; ans += this.amountAsHumanFloat(Math.abs(amount)); return ans; }
JavaScript
static coerceDenominationRateList(list){ const errMsg = 'list must be an array of denominations separated by rates'; if(is.not.array(list)) throw new TypeError(errMsg); if(list.length < 1) throw new RangeError('list cannot be empty'); const denominationRateList = []; const rateList = []; const listCopy = [...list]; // a shallow copy // start with the largest denomination if(!(listCopy[0] instanceof Denomination)){ throw new TypeError(errMsg); } denominationRateList.push(listCopy.shift()); // then move forward in pairs while(listCopy.length > 0){ const rate = this.coerceDenominationRate(listCopy.shift()); const denomination = listCopy.shift(); if(!(denomination instanceof Denomination)){ throw new TypeError(errMsg); } denominationRateList.push(rate, denomination); } // return the list return denominationRateList; }
static coerceDenominationRateList(list){ const errMsg = 'list must be an array of denominations separated by rates'; if(is.not.array(list)) throw new TypeError(errMsg); if(list.length < 1) throw new RangeError('list cannot be empty'); const denominationRateList = []; const rateList = []; const listCopy = [...list]; // a shallow copy // start with the largest denomination if(!(listCopy[0] instanceof Denomination)){ throw new TypeError(errMsg); } denominationRateList.push(listCopy.shift()); // then move forward in pairs while(listCopy.length > 0){ const rate = this.coerceDenominationRate(listCopy.shift()); const denomination = listCopy.shift(); if(!(denomination instanceof Denomination)){ throw new TypeError(errMsg); } denominationRateList.push(rate, denomination); } // return the list return denominationRateList; }
JavaScript
amountAsHumanFloat(amount){ amount = this.constructor.coerceAmount(amount); // could throw error // default single-denomination currencies to the parent class if(this.length === 1){ return super.amountAsHumanFloat(amount); } // calculate the total rate between the smallest and largest denominations let totalRate = 1; for(const rate of this.rateList){ totalRate *= rate; } // get the order of magnitude of the total rate // simply the number of digits minus one const order = String(totalRate).length - 1; // build a format string with the appropriate number of decimal places const formatString = `0,0[.]${'0'.repeat(order)}`; // format and return return numeral(amount).format(formatString); }
amountAsHumanFloat(amount){ amount = this.constructor.coerceAmount(amount); // could throw error // default single-denomination currencies to the parent class if(this.length === 1){ return super.amountAsHumanFloat(amount); } // calculate the total rate between the smallest and largest denominations let totalRate = 1; for(const rate of this.rateList){ totalRate *= rate; } // get the order of magnitude of the total rate // simply the number of digits minus one const order = String(totalRate).length - 1; // build a format string with the appropriate number of decimal places const formatString = `0,0[.]${'0'.repeat(order)}`; // format and return return numeral(amount).format(formatString); }
JavaScript
splitAmount(amount){ amount = this.constructor.coerceAmount(amount); // could throw error // if there's only one denomination, use the default implementation from the parent class if(this.length === 1){ return super.splitAmount(amount); } const amounts = []; // // round to a whole number of the smallest denomination // // NOTE - Math.floor() does not behave as expected with negative numbers // so need the absolute value before flooring. // to avoid rounding problems, convert to absolute value if negative and remember const isNegative = amount < 0; let absAmount = Math.abs(amount); // Start with the amount in the largest denomination let currentAbsAmount = Math.floor(absAmount); amounts.push(currentAbsAmount); // keep just the decimal part absAmount = absAmount - currentAbsAmount; //loop over the remaining denominations for(let rate of this.rateList){ // if there's nothing left, exit the loop if(absAmount === 0) break; // multiple by the current rate absAmount *= rate; // get and store the whole number part currentAbsAmount = Math.floor(absAmount); amounts.push(currentAbsAmount); // keep just the decimal part absAmount = absAmount - currentAbsAmount; } // if the decimal part is >= 0.5, increment the lowest denomination by 1 and ripple up if needed if(absAmount >= 0.5){ // increment the lowest denomination amounts[amounts.length - 1]++; // ripple the increment up the denominations if needed let doneRippling = false; for(let i = this.rateList.length - 1; !doneRippling && i >= 0; i--){ if(amounts[i+1] === this.rateList[i]){ amounts[i+1] = 0; amounts[i]++; }else{ doneRippling = true; } } } // re-negate if needed if(isNegative){ for(let i = 0; i < amounts.length; i++){ amounts[i] = 0 - amounts[i]; } } // return the amounts return amounts; }
splitAmount(amount){ amount = this.constructor.coerceAmount(amount); // could throw error // if there's only one denomination, use the default implementation from the parent class if(this.length === 1){ return super.splitAmount(amount); } const amounts = []; // // round to a whole number of the smallest denomination // // NOTE - Math.floor() does not behave as expected with negative numbers // so need the absolute value before flooring. // to avoid rounding problems, convert to absolute value if negative and remember const isNegative = amount < 0; let absAmount = Math.abs(amount); // Start with the amount in the largest denomination let currentAbsAmount = Math.floor(absAmount); amounts.push(currentAbsAmount); // keep just the decimal part absAmount = absAmount - currentAbsAmount; //loop over the remaining denominations for(let rate of this.rateList){ // if there's nothing left, exit the loop if(absAmount === 0) break; // multiple by the current rate absAmount *= rate; // get and store the whole number part currentAbsAmount = Math.floor(absAmount); amounts.push(currentAbsAmount); // keep just the decimal part absAmount = absAmount - currentAbsAmount; } // if the decimal part is >= 0.5, increment the lowest denomination by 1 and ripple up if needed if(absAmount >= 0.5){ // increment the lowest denomination amounts[amounts.length - 1]++; // ripple the increment up the denominations if needed let doneRippling = false; for(let i = this.rateList.length - 1; !doneRippling && i >= 0; i--){ if(amounts[i+1] === this.rateList[i]){ amounts[i+1] = 0; amounts[i]++; }else{ doneRippling = true; } } } // re-negate if needed if(isNegative){ for(let i = 0; i < amounts.length; i++){ amounts[i] = 0 - amounts[i]; } } // return the amounts return amounts; }
JavaScript
amountAsString(amount){ amount = this.constructor.coerceAmount(amount); // could throw error // build and return the string let ans = is.negative(amount) ? '-' : ''; ans += this.denomination.symbol; ans += this.amountAsHumanFloat(Math.abs(amount)); return ans; }
amountAsString(amount){ amount = this.constructor.coerceAmount(amount); // could throw error // build and return the string let ans = is.negative(amount) ? '-' : ''; ans += this.denomination.symbol; ans += this.amountAsHumanFloat(Math.abs(amount)); return ans; }
JavaScript
amountAsHumanString(amount){ amount = this.constructor.coerceAmount(amount); // could throw error // short-circut zero if(amount === 0){ return `${this.denomination.symbol}0`; } // split the amount into denominations const denominatedAmounts = this.splitAmount(amount); // filter down to non-zero amounts, pre-fix symbols, and format const formattedAmounts = []; for(let i = 0; i < denominatedAmounts.length; i++){ // skip zero amounts if(denominatedAmounts[i] === 0) continue; // format the amount let formattedAmount = this.denominationList[i].symbol; formattedAmount += this.constructor.amountAsHumanInt(Math.abs(denominatedAmounts[i])); formattedAmounts.push(formattedAmount); } // assemble the final answer and return it return `${is.negative(amount) ? '-' : ''}${formattedAmounts.join(' ')}`; }
amountAsHumanString(amount){ amount = this.constructor.coerceAmount(amount); // could throw error // short-circut zero if(amount === 0){ return `${this.denomination.symbol}0`; } // split the amount into denominations const denominatedAmounts = this.splitAmount(amount); // filter down to non-zero amounts, pre-fix symbols, and format const formattedAmounts = []; for(let i = 0; i < denominatedAmounts.length; i++){ // skip zero amounts if(denominatedAmounts[i] === 0) continue; // format the amount let formattedAmount = this.denominationList[i].symbol; formattedAmount += this.constructor.amountAsHumanInt(Math.abs(denominatedAmounts[i])); formattedAmounts.push(formattedAmount); } // assemble the final answer and return it return `${is.negative(amount) ? '-' : ''}${formattedAmounts.join(' ')}`; }
JavaScript
static set defaultHandle(h){ if(is.not.string(h)) throw new TypeError('Default Handle must be a string'); if(is.empty(h)) throw new RangeError("Default Handle can't be an empty string"); this._defaultHandle = e; }
static set defaultHandle(h){ if(is.not.string(h)) throw new TypeError('Default Handle must be a string'); if(is.empty(h)) throw new RangeError("Default Handle can't be an empty string"); this._defaultHandle = e; }
JavaScript
static set defaultEmoji(e){ if(is.not.string(e)) throw new TypeError('Default Emoji must be a string'); if(!this.isEmoji(e)) throw new RangeError('Default Emoji must be a single Unicode character'); this._defaultEmoji = e; }
static set defaultEmoji(e){ if(is.not.string(e)) throw new TypeError('Default Emoji must be a string'); if(!this.isEmoji(e)) throw new RangeError('Default Emoji must be a single Unicode character'); this._defaultEmoji = e; }
JavaScript
static isEmoji(val){ if(is.not.string(val)){ return false; } return (new GraphemeSplitter()).countGraphemes(val) === 1; }
static isEmoji(val){ if(is.not.string(val)){ return false; } return (new GraphemeSplitter()).countGraphemes(val) === 1; }
JavaScript
set handle(h){ if(is.not.string(h)) throw new TypeError('Handle must be a string'); if(is.empty(h)) throw new RangeError('Handle cannot be an empty string'); this._handle = h; }
set handle(h){ if(is.not.string(h)) throw new TypeError('Handle must be a string'); if(is.empty(h)) throw new RangeError('Handle cannot be an empty string'); this._handle = h; }
JavaScript
set emoji(e){ const errMsg = `emoji must be an array of ${this.constructor.length} single Unicode graphemes`; if(is.not.array(e) || !is.all.string(e)){ throw new TypeError(errMsg); } for(const emoji of e){ if(!this.constructor.isEmoji(emoji)){ throw new RangeError('each emoji must be a single Unicode graphemes'); } } if(e.length < this.constructor.length){ throw new TypeError(errMsg); } this._emoji = e.slice(0, this.constructor.length); }
set emoji(e){ const errMsg = `emoji must be an array of ${this.constructor.length} single Unicode graphemes`; if(is.not.array(e) || !is.all.string(e)){ throw new TypeError(errMsg); } for(const emoji of e){ if(!this.constructor.isEmoji(emoji)){ throw new RangeError('each emoji must be a single Unicode graphemes'); } } if(e.length < this.constructor.length){ throw new TypeError(errMsg); } this._emoji = e.slice(0, this.constructor.length); }