Skip to content

Commit

Permalink
refactor: Unglobalize NumberUtil and ArrayUtil (#6129)
Browse files Browse the repository at this point in the history
  • Loading branch information
AndyLnd committed Mar 18, 2019
1 parent ffc7e21 commit c125cff
Show file tree
Hide file tree
Showing 23 changed files with 232 additions and 188 deletions.
6 changes: 4 additions & 2 deletions src/script/assets/AssetMetaDataBuilder.js
Expand Up @@ -19,6 +19,8 @@

import {Asset} from '@wireapp/protocol-messaging';
import TimeUtil from 'utils/TimeUtil';
import {capToByte, rootMeanSquare} from 'utils/NumberUtil';
import {chunk} from 'utils/ArrayUtil';

/**
* Constructs corresponding asset metadata depending on the given file type
Expand Down Expand Up @@ -140,10 +142,10 @@ const normaliseLoudness = audioBuffer => {
const AMPLIFIER = 700; // in favour of iterating all samples before we interpolate them
const channel = audioBuffer.getChannelData(0);
const bucketSize = parseInt(channel.length / MAX_SAMPLES);
const buckets = z.util.ArrayUtil.chunk(channel, bucketSize);
const buckets = chunk(channel, bucketSize);

const audioPreview = buckets.map(bucket => {
return z.util.NumberUtil.capToByte(AMPLIFIER * z.util.NumberUtil.rootMeanSquare(bucket));
return capToByte(AMPLIFIER * rootMeanSquare(bucket));
});

return new Uint8Array(audioPreview);
Expand Down
25 changes: 13 additions & 12 deletions src/script/backup/BackupRepository.js
Expand Up @@ -24,6 +24,7 @@ import JSZip from 'jszip';
import StorageSchemata from '../storage/StorageSchemata';

import BackupService from './BackupService';
import {chunk} from 'utils/ArrayUtil';

window.z = window.z || {};
window.z.backup = z.backup || {};
Expand Down Expand Up @@ -230,13 +231,13 @@ z.backup.BackupRepository = class BackupRepository {
const entityCount = conversationEntities.length;
let importedEntities = [];

const entityChunks = z.util.ArrayUtil.chunk(conversationEntities, BackupService.CONFIG.BATCH_SIZE);
const entityChunks = chunk(conversationEntities, BackupService.CONFIG.BATCH_SIZE);

const importConversationChunk = chunk =>
this.conversationRepository.updateConversationStates(chunk).then(importedConversationEntities => {
const importConversationChunk = conversationChunk =>
this.conversationRepository.updateConversationStates(conversationChunk).then(importedConversationEntities => {
importedEntities = importedEntities.concat(importedConversationEntities);
this.logger.log(`Imported '${importedEntities.length}' of '${entityCount}' conversation states from backup`);
progressCallback(chunk.length);
progressCallback(conversationChunk.length);
});

return this._chunkImport(importConversationChunk, entityChunks).then(() => importedEntities);
Expand All @@ -247,25 +248,25 @@ z.backup.BackupRepository = class BackupRepository {
let importedEntities = 0;

const entities = eventEntities.map(entity => this.mapEntityDataType(entity));
const entityChunks = z.util.ArrayUtil.chunk(entities, BackupService.CONFIG.BATCH_SIZE);
const entityChunks = chunk(entities, BackupService.CONFIG.BATCH_SIZE);

const importEventChunk = chunk =>
this.backupService.importEntities(this.EVENTS_STORE_NAME, chunk).then(() => {
importedEntities += chunk.length;
const importEventChunk = eventChunk =>
this.backupService.importEntities(this.EVENTS_STORE_NAME, eventChunk).then(() => {
importedEntities += eventChunk.length;
this.logger.log(`Imported '${importedEntities}' of '${entityCount}' events from backup`);
progressCallback(chunk.length);
progressCallback(eventChunk.length);
});

return this._chunkImport(importEventChunk, entityChunks);
}

_chunkImport(importFunction, chunks) {
return chunks.reduce((promise, chunk) => {
_chunkImport(importFunction, importChunks) {
return importChunks.reduce((promise, importChunk) => {
return promise.then(() => {
if (this.isCanceled) {
return Promise.reject(new z.backup.CancelError());
}
return importFunction(chunk);
return importFunction(importChunk);
});
}, Promise.resolve());
}
Expand Down
4 changes: 3 additions & 1 deletion src/script/calling/VideoGridRepository.js
Expand Up @@ -17,6 +17,8 @@
*
*/

import {getDifference} from 'utils/ArrayUtil';

window.z = window.z || {};
window.z.calling = z.calling || {};

Expand Down Expand Up @@ -100,7 +102,7 @@ z.calling.VideoGridRepository = class VideoGridRepository {
const previousStreamIds = previousGrid.filter(streamId => streamId !== 0);
const currentStreamIds = streams.map(stream => stream.id);

const addedStreamIds = z.util.ArrayUtil.getDifference(previousStreamIds, currentStreamIds);
const addedStreamIds = getDifference(previousStreamIds, currentStreamIds);

const filteredGrid = previousGrid.map(id => (currentStreamIds.includes(id) ? id : 0));

Expand Down
3 changes: 2 additions & 1 deletion src/script/calling/entities/CallEntity.js
Expand Up @@ -23,6 +23,7 @@ import CALL_MESSAGE_TYPE from '../enum/CallMessageType';
import CALL_STATE from '../enum/CallState';
import CALL_STATE_GROUP from '../enum/CallStateGroup';
import TERMINATION_REASON from '../enum/TerminationReason';
import {getRandomNumber} from 'utils/NumberUtil';

window.z = window.z || {};
window.z.calling = z.calling || {};
Expand Down Expand Up @@ -527,7 +528,7 @@ z.calling.entities.CallEntity = class CallEntity {
*/
_setSendGroupCheckTimeout() {
const {MAXIMUM_TIMEOUT, MINIMUM_TIMEOUT} = CallEntity.CONFIG.GROUP_CHECK;
const timeoutInSeconds = z.util.NumberUtil.getRandomNumber(MINIMUM_TIMEOUT, MAXIMUM_TIMEOUT);
const timeoutInSeconds = getRandomNumber(MINIMUM_TIMEOUT, MAXIMUM_TIMEOUT);

const timeout = timeoutInSeconds * TimeUtil.UNITS_IN_MILLIS.SECOND;
this.groupCheckTimeoutId = window.setTimeout(() => this._onSendGroupCheckTimeout(timeoutInSeconds), timeout);
Expand Down
8 changes: 4 additions & 4 deletions src/script/components/asset/controls/audioSeekBar.js
Expand Up @@ -17,8 +17,8 @@
*
*/

import {ArrayUtil} from 'utils/ArrayUtil';
import {NumberUtil} from 'utils/NumberUtil';
import {interpolate} from 'utils/ArrayUtil';
import {clamp} from 'utils/NumberUtil';

class AudioSeekBarComponent {
/**
Expand Down Expand Up @@ -67,7 +67,7 @@ class AudioSeekBarComponent {

_renderLevels() {
const numberOfLevelsFitOnScreen = Math.floor(this.element.clientWidth / 3); // 2px + 1px
const scaledLoudness = ArrayUtil.interpolate(this.loudness, numberOfLevelsFitOnScreen);
const scaledLoudness = interpolate(this.loudness, numberOfLevelsFitOnScreen);
this.element.innerHTML = '';

this.levels = scaledLoudness.map(loudness => {
Expand All @@ -89,7 +89,7 @@ class AudioSeekBarComponent {
const calculatedTime = (this.audioElement.duration * mouse_x) / event.currentTarget.clientWidth;
const currentTime = window.isNaN(calculatedTime) ? 0 : calculatedTime;

this.audioElement.currentTime = NumberUtil.clamp(currentTime, 0, this.audioElement.duration);
this.audioElement.currentTime = clamp(currentTime, 0, this.audioElement.duration);
this._onTimeUpdate();
}

Expand Down
4 changes: 3 additions & 1 deletion src/script/components/asset/controls/seekBar.js
Expand Up @@ -17,6 +17,8 @@
*
*/

import {clamp} from 'utils/NumberUtil';

window.z = window.z || {};
window.z.components = z.components || {};

Expand Down Expand Up @@ -80,7 +82,7 @@ z.components.SeekBarComponent = class SeekBarComponent {

on_change() {
const currentTime = this.media_element.duration * (this.seek_bar.value / 100);
this.media_element.currentTime = z.util.NumberUtil.clamp(currentTime, 0, this.media_element.duration);
this.media_element.currentTime = clamp(currentTime, 0, this.media_element.duration);
}

on_timeupdate() {
Expand Down
6 changes: 4 additions & 2 deletions src/script/components/mentionSuggestions.js
Expand Up @@ -17,6 +17,8 @@
*
*/

import {clamp} from 'utils/NumberUtil';

class MentionSuggestions {
constructor(params) {
this.onInput = this.onInput.bind(this);
Expand Down Expand Up @@ -90,7 +92,7 @@ class MentionSuggestions {

moveSelection(delta) {
const currentIndex = this.selectedSuggestionIndex();
const newIndex = z.util.NumberUtil.clamp(currentIndex + delta, 0, this.suggestions().length - 1);
const newIndex = clamp(currentIndex + delta, 0, this.suggestions().length - 1);
this.selectedSuggestionIndex(newIndex);
return true;
}
Expand Down Expand Up @@ -146,7 +148,7 @@ class MentionSuggestions {

updateSelectedIndexBoundaries(suggestions) {
const currentIndex = this.selectedSuggestionIndex();
this.selectedSuggestionIndex(z.util.NumberUtil.clamp(currentIndex, 0, suggestions.length - 1));
this.selectedSuggestionIndex(clamp(currentIndex, 0, suggestions.length - 1));
}

teardownList() {
Expand Down
3 changes: 2 additions & 1 deletion src/script/conversation/ClientMismatchHandler.js
Expand Up @@ -18,6 +18,7 @@
*/

import Logger from 'utils/Logger';
import {getDifference} from 'utils/ArrayUtil';

window.z = window.z || {};
window.z.conversation = z.conversation || {};
Expand Down Expand Up @@ -110,7 +111,7 @@ z.conversation.ClientMismatchHandler = class ClientMismatchHandler {
? Promise.resolve()
: this.conversationRepository.get_conversation_by_id(conversationId).then(conversationEntity => {
const knownUserIds = conversationEntity.participating_user_ids();
const unknownUserIds = z.util.ArrayUtil.getDifference(knownUserIds, missingUserIds);
const unknownUserIds = getDifference(knownUserIds, missingUserIds);

if (unknownUserIds.length) {
return this.conversationRepository.addMissingMember(conversationId, unknownUserIds, timestamp - 1);
Expand Down
3 changes: 2 additions & 1 deletion src/script/conversation/ConversationEphemeralHandler.js
Expand Up @@ -22,6 +22,7 @@ import {Article, LinkPreview} from '@wireapp/protocol-messaging';
import EphemeralStatusType from '../message/EphemeralStatusType';
import Logger from 'utils/Logger';
import TimeUtil from 'utils/TimeUtil';
import {clamp} from 'utils/NumberUtil';

window.z = window.z || {};
window.z.conversation = z.conversation || {};
Expand All @@ -42,7 +43,7 @@ z.conversation.ConversationEphemeralHandler = class ConversationEphemeralHandler
const TIMER_RANGE = ConversationEphemeralHandler.CONFIG.TIMER_RANGE;
const isTimerReset = messageTimer === null;

return isTimerReset ? messageTimer : z.util.NumberUtil.clamp(messageTimer, TIMER_RANGE.MIN, TIMER_RANGE.MAX);
return isTimerReset ? messageTimer : clamp(messageTimer, TIMER_RANGE.MIN, TIMER_RANGE.MAX);
}

constructor(conversationMapper, eventService, eventListeners) {
Expand Down
4 changes: 3 additions & 1 deletion src/script/conversation/ConversationRepository.js
Expand Up @@ -54,6 +54,8 @@ import {areMentionsDifferent, isTextDifferent} from 'utils/messageComparator';

import AssetMetaDataBuilder from '../assets/AssetMetaDataBuilder';

import {getNextItem} from 'utils/ArrayUtil';

window.z = window.z || {};
window.z.conversation = z.conversation || {};

Expand Down Expand Up @@ -904,7 +906,7 @@ z.conversation.ConversationRepository = class ConversationRepository {
* @returns {Conversation} Next conversation
*/
get_next_conversation(conversation_et) {
return z.util.ArrayUtil.getNextItem(this.conversations_unarchived(), conversation_et);
return getNextItem(this.conversations_unarchived(), conversation_et);
}

/**
Expand Down
3 changes: 2 additions & 1 deletion src/script/entity/User.js
Expand Up @@ -22,6 +22,7 @@ import ko from 'knockout';
import {ROLE as TEAM_ROLE} from '../user/UserPermission';
import {t} from 'utils/LocalizerUtil';
import TimeUtil from 'utils/TimeUtil';
import {clamp} from 'utils/NumberUtil';

// Please note: The own user has a "locale"
class User {
Expand Down Expand Up @@ -284,7 +285,7 @@ class User {
}

_setRemainingExpirationTime(expirationTime) {
const remainingTime = z.util.NumberUtil.clamp(expirationTime - Date.now(), 0, User.CONFIG.TEMPORARY_GUEST.LIFETIME);
const remainingTime = clamp(expirationTime - Date.now(), 0, User.CONFIG.TEMPORARY_GUEST.LIFETIME);
const remainingMinutes = Math.ceil(remainingTime / TimeUtil.UNITS_IN_MILLIS.MINUTE);

if (remainingMinutes <= 45) {
Expand Down
2 changes: 0 additions & 2 deletions src/script/main/globals.js
Expand Up @@ -10,7 +10,6 @@ import bubble from '../../ext/js/webapp-module-bubble/webapp-module-bubble.js';

import configGlobal from '../config.js';
import envGlobal from '../util/Environment.js';
import ArrayUtilGlobal from '../util/ArrayUtil.js';
import CryptoGlobal from '../util/Crypto.js';
import DebugUtilGlobal from '../util/DebugUtil.js';
import EmojiUtilGlobal from '../util/EmojiUtil.js';
Expand All @@ -20,7 +19,6 @@ import KeyboardUtilGlobal from '../util/KeyboardUtil.js';
import LocalizerUtilGlobal from '../util/LocalizerUtil.js';
import linkifyGlobal from '../util/linkify.js';
import htmlGlobal from '../util/linkify-html.js';
import NumberUtilGlobal from '../util/NumberUtil.js';
import helpersGlobal from '../util/scroll-helpers.js';
import StorageUtilGlobal from '../util/StorageUtil.js';
import StringUtilGlobal from '../util/StringUtil.js';
Expand Down
3 changes: 2 additions & 1 deletion src/script/media/MediaDevicesHandler.js
Expand Up @@ -21,6 +21,7 @@ import Logger from 'utils/Logger';

import * as StorageUtil from 'utils/StorageUtil';
import MediaRepository from './MediaRepository';
import {iterateIndex} from 'utils/ArrayUtil';

export default class MediaDevicesHandler {
static get CONFIG() {
Expand Down Expand Up @@ -332,7 +333,7 @@ export default class MediaDevicesHandler {

_toggleNextDevice(availableDevices, currentDeviceIdObservable, currentDeviceIndex) {
const {device} = this._getCurrentDevice(availableDevices, currentDeviceIdObservable());
const nextIndex = z.util.ArrayUtil.iterateIndex(availableDevices, currentDeviceIndex);
const nextIndex = iterateIndex(availableDevices, currentDeviceIndex);

const nextDevice = availableDevices[nextIndex || 0];
const deviceId = nextDevice.deviceId || nextDevice.id;
Expand Down
6 changes: 4 additions & 2 deletions src/script/user/UserHandleGenerator.js
Expand Up @@ -18,6 +18,8 @@
*/

import getSlug from 'speakingurl';
import {getRandomNumber} from 'utils/NumberUtil';
import {randomElement} from 'utils/ArrayUtil';

window.z = window.z || {};
window.z.user = z.user || {};
Expand Down Expand Up @@ -281,7 +283,7 @@ window.z.user = z.user || {};
}

function get_random_word_combination() {
return `${z.util.ArrayUtil.randomElement(RANDOM_WORDS_1)}${z.util.ArrayUtil.randomElement(RANDOM_WORDS_2)}`;
return `${randomElement(RANDOM_WORDS_1)}${randomElement(RANDOM_WORDS_2)}`;
}

/**
Expand All @@ -303,7 +305,7 @@ window.z.user = z.user || {};
* @returns {string} String appended with random digits.
*/
function append_random_digits(handle, additional_numbers) {
const random_digits = _.range(additional_numbers).map(() => z.util.NumberUtil.getRandomNumber(1, 8));
const random_digits = _.range(additional_numbers).map(() => getRandomNumber(1, 8));
return `${handle}${random_digits.join('')}`;
}

Expand Down
4 changes: 3 additions & 1 deletion src/script/user/UserRepository.js
Expand Up @@ -31,6 +31,8 @@ import ConsentType from './ConsentType';
import User from '../entity/User';
import UserMapper from './UserMapper';

import {chunk} from 'utils/ArrayUtil';

export default class UserRepository {
static get CONFIG() {
return {
Expand Down Expand Up @@ -395,7 +397,7 @@ export default class UserRepository {
});
};

const chunksOfUserIds = z.util.ArrayUtil.chunk(userIds, z.config.MAXIMUM_USERS_PER_REQUEST);
const chunksOfUserIds = chunk(userIds, z.config.MAXIMUM_USERS_PER_REQUEST);
return Promise.all(chunksOfUserIds.map(chunkOfUserIds => _getUsers(chunkOfUserIds)))
.then(resolveArray => {
const newUserEntities = _.flatten(resolveArray);
Expand Down

0 comments on commit c125cff

Please sign in to comment.