Best JavaScript code snippet using root
primus.service.ts
Source:primus.service.ts
...77 position: 'top',78 showCloseButton: true79 }).present();80 }81 _emit(event: string, data?: any, callback?: Function): void {82 if(!this.socket) return;83 this.callbacks[event] = callback;84 if(!data) data = {};85 const next = () => {86 data.token = this.storage.retrieve('idToken');87 this.socket.emit(event, data);88 };89 if(!data.skipRenew && !this.auth.authenticated) {90 this.auth.renew().then(next);91 return;92 }93 next();94 }95 initSocket(): void {96 if(this.socket) return;97 this.socket = PrimusSocket.connect(`${settings.protocol}://${settings.hostname}:${settings.port}`, {98 reconnect: {99 min: 500,100 retries: 100,101 factor: 1.7102 }103 });104 (<any>window).socket = this.socket;105 this.socket.on('error', e => { Logger.error(e); });106 this.socket.on('close', () => {107 if(this.appState.onlineStatus.getValue() !== 'offline') {108 this.appState.onlineStatus.next('offline');109 this.appState.loggedIn.next(false);110 }111 });112 this.socket.on('reconnect scheduled', () => {113 if(this.appState.onlineStatus.getValue() !== 'connecting') {114 this.appState.onlineStatus.next('connecting');115 }116 });117 this.socket.on('reconnected', () => {118 this._reconnecting = true;119 });120 this.socket.on('open', () => {121 if(this.appState.onlineStatus.getValue() !== 'online') {122 this.appState.onlineStatus.next('online');123 }124 this.checkIfExists()125 .then(exists => {126 if(!exists) {127 this.appState.hasCharacter.next(false);128 return;129 }130 this.appState.hasCharacter.next(true);131 return this.login();132 })133 .catch((e) => {134 Logger.error(e);135 });136 });137 this.socket.on('data', data => {138 if(data.notify) {139 this._handleNotification({ message: data.notify });140 if(data.type === 'error') return;141 }142 if(data.playerListOperation) return this.handleUserListUpdate(data);143 if(data.route && data.channel && data.text) return this.handleChatMessage(data, true);144 if(data.update) return this.handleContentUpdate(data);145 if(data.event === 'adventurelog') return this.handleAdventureLog(data);146 if(!data.event) {147 Logger.error(new Error('no event specified' + JSON.parse(data)));148 return;149 }150 if(!this.callbacks[data.event]) return;151 this.callbacks[data.event](data);152 delete this.callbacks[data.event];153 });154 }155 handleUserListUpdate(data) {156 const operations = {157 add: () => {158 let userList = this.appState.chatUsers.getValue();159 if(_.find(userList, { name: data.data.name })) return;160 userList.push(data.data);161 userList = _.sortBy(userList, 'name');162 this.appState.chatUsers.next(userList);163 },164 del: () => {165 let userList = this.appState.chatUsers.getValue();166 userList = _.reject(userList, p => p.name === data.data);167 this.appState.chatUsers.next(userList);168 },169 set: () => {170 this.appState.chatUsers.next(data.data);171 },172 update: () => {173 let userList = this.appState.chatUsers.getValue();174 const player = _.find(userList, { name: data.data.name });175 if(player) {176 _.extend(player, data.data);177 } else {178 userList.push(data.data);179 userList = _.sortBy(userList, 'name');180 }181 this.appState.chatUsers.next(userList);182 },183 updateMass: () => {184 const userList = this.appState.chatUsers.getValue();185 _.each(data.data, player => {186 const playerRef = _.find(userList, { name: player.name });187 _.extend(playerRef, player);188 });189 this.appState.chatUsers.next(userList);190 }191 };192 operations[data.playerListOperation]();193 }194 handleChatMessage(message: ChatMessage, fromPrimus = false) {195 const playerName = this.playerName;196 if(fromPrimus && message.playerName === playerName) return;197 if(!message.timestamp) message.timestamp = Date.now();198 this.appState.chatMessages.next(message);199 this.chatLog.push(message);200 this.saveChatLog();201 }202 sendChatMessage(messageObject: ChatMessage) {203 this._emit('plugin:chat:sendmessage', messageObject);204 messageObject.playerName = this.playerName;205 messageObject.guildTag = this.appState.guild.getValue().tag;206 this.handleChatMessage(messageObject);207 }208 handleContentUpdate(content) {209 if(!content.update || !this.appState[content.update]) return;210 let value = content.data;211 if(content.update === 'achievements') {212 value = _.sortBy(_.values(value), 'name');213 }214 if(content.update === 'collectibles') {215 value = { orig: value, current: _.sortBy(_.values(value.current), 'name'), prior: value.prior };216 }217 if(content.update === 'petbasic') {218 value = _.sortBy(value, 'bought').reverse();219 }220 this.appState[content.update].next(value);221 }222 handleAdventureLog(object: AdventureLog) {223 if(!_.includes(object.targets, this.appState.player.getValue().name)) return;224 object.timestamp = Date.now();225 this.appState.adventureLog.next(object);226 this.advLog.unshift(object);227 this.saveAdventureLog();228 }229 disconnectSocket(): void {230 if(!this.socket) return;231 this._emit('plugin:player:logout', { skipRenew: true });232 this.socket = null;233 }234 requestNoKill(): void {235 this._emit('plugin:player:imregisteringrightnowdontkillme');236 }237 requestEquipment(): void {238 this.loggedIn$.subscribe(() => {239 this._emit('plugin:player:request:equipment');240 });241 }242 requestAchievements(): void {243 this.loggedIn$.subscribe(() => {244 this._emit('plugin:player:request:achievements');245 });246 }247 requestCollectibles(): void {248 this.loggedIn$.subscribe(() => {249 this._emit('plugin:player:request:collectibles');250 });251 }252 requestStatistics(): void {253 this.loggedIn$.subscribe(() => {254 this._emit('plugin:player:request:statistics');255 });256 }257 requestPets(): void {258 this.loggedIn$.subscribe(() => {259 this._emit('plugin:player:request:pets');260 });261 }262 requestPersonalities(): void {263 this.loggedIn$.subscribe(() => {264 this._emit('plugin:player:request:personalities');265 });266 }267 requestParty(): void {268 this.loggedIn$.subscribe(() => {269 this._emit('plugin:player:request:party');270 });271 }272 requestBossTimers(): void {273 this.loggedIn$.subscribe(() => {274 this._emit('plugin:player:request:bosstimers');275 })276 }277 requestShop(): void {278 this.loggedIn$.subscribe(() => {279 this._emit('plugin:player:request:shop');280 });281 }282 requestGuild(): void {283 this.loggedIn$.subscribe(() => {284 this._emit('plugin:player:request:guild');285 });286 }287 requestGuildBuildings(): void {288 this.loggedIn$.subscribe(() => {289 this._emit('plugin:player:request:guildbuildings');290 });291 }292 loadBattle(battleName): void {293 this._emit('plugin:combat:retrieve', { battleName });294 }295 checkIfExists(): Promise<any> {296 return new Promise((resolve, reject) => {297 const profile = this.storage.retrieve('profile');298 if(!profile) return reject(new Error('No profile to check against'));299 this._emit('plugin:player:exists', { userId: profile.user_id }, data => {300 resolve(data.exists);301 });302 });303 }304 login(registerArgs: any = {}): Promise<any> {305 return new Promise((resolve, reject) => {306 const isLoggedIn = this.appState.loggedIn.getValue();307 if(isLoggedIn) return reject(new Error('Already logged in'));308 const profile = this.storage.retrieve('profile');309 if(!profile) return reject(new Error('No profile to login'));310 return this.auth.renew()311 .then(() => {312 registerArgs.userId = profile.user_id;313 this._emit('plugin:player:login', registerArgs, res => {314 if(!res.ok) return;315 this.appState.loggedIn.next(true);316 resolve(res);317 });318 })319 .catch(e => {320 if(e.error === 'too_many_requests') {321 this._handleNotification({ message: 'Too many login requests - take a break and refresh in a bit.' });322 return;323 }324 reject(e);325 });326 })327 }328 register(args) {329 return this.login(args);330 }331 // PLAYER332 makeChoice(id, response) {333 this._emit('plugin:player:makechoice', {334 id,335 response336 });337 }338 togglePersonality(personality) {339 this._emit('plugin:player:togglepersonality', { personality });340 }341 changeGender(gender) {342 this._emit('plugin:player:changegender', { gender });343 }344 changeTitle(title) {345 this._emit('plugin:player:changetitle', { title });346 }347 leaveParty() {348 this._emit('plugin:player:partyleave');349 }350 ascend() {351 this._emit('plugin:player:ascend');352 }353 buyShopItem(itemId) {354 this._emit('plugin:player:buyshopitem', { itemId });355 }356 // PREMIUM357 buyIlp(ilpBuy) {358 this._emit('plugin:premium:buyilp', { ilpBuy });359 }360 buyIlpItem(itemName) {361 this._emit('plugin:premium:buyilpitem', { itemName });362 }363 // PET364 sellItemFromPet(itemId) {365 this._emit('plugin:pet:sell', { itemId });366 }367 salvageItemFromPet(itemId) {368 this._emit('plugin:pet:salvage', { itemId });369 }370 sellAllItemsFromPet() {371 this._emit('plugin:pet:sellall');372 }373 salvageAllItemsFromPet() {374 this._emit('plugin:pet:salvageall');375 }376 equipItemOnPet(itemId) {377 this._emit('plugin:pet:equip', { itemId });378 }379 unequipItemFromPet(itemId) {380 this._emit('plugin:pet:unequip', { itemId });381 }382 giveItemToPet(itemId) {383 this._emit('plugin:pet:giveitem', { itemId });384 }385 giveItemToPlayer(itemId) {386 this._emit('plugin:pet:takeitem', { itemId });387 }388 buyPet(petType, petName) {389 if(!petName || !petName.trim()) {390 this._handleNotification({ message: 'Invalid pet name! '});391 return;392 }393 if(petName.length > 20) {394 this._handleNotification({ message: 'Your pet name is too long! '});395 return;396 }397 this._emit('plugin:pet:buy', { petType, petName });398 }399 makePetActive(petType) {400 this._emit('plugin:pet:swap', { petType });401 }402 changePetClass(newProfession) {403 this._emit('plugin:pet:profession', { newProfession });404 }405 changePetAttr(newAttr) {406 this._emit('plugin:pet:attr', { newAttr });407 }408 takePetGold() {409 this._emit('plugin:pet:takegold');410 }411 feedPetGold(gold, maxGold) {412 if(gold < 0 || _.isNaN(gold)) {413 this._handleNotification({ message: 'Invalid gold value! '});414 return;415 }416 if(gold > maxGold) {417 this._handleNotification({ message: 'Cannot overfeed gold! '});418 return;419 }420 this._emit('plugin:pet:feed', { gold });421 }422 feedMax() {423 this._emit('plugin:pet:feedmax');424 }425 upgradePetAttr(upgradeAttr) {426 this._emit('plugin:pet:upgrade', { upgradeAttr });427 }428 togglePetSmart(setting) {429 this._emit('plugin:pet:smart', { setting });430 }431 renamePet(petId, newName) {432 this._emit('plugin:pet:rename', { petId, newName });433 }434 giveItemToOtherPet(itemId, petId) {435 this._emit('plugin:pet:pass', { itemId, petId });436 }437 // GUILD438 createGuild(name, tag) {439 this._emit('plugin:guild:create', { name, tag });440 }441 changeMOTD(motd) {442 this._emit('plugin:guild:motd', { motd });443 }444 updatePlayerTaxRate(newRate) {445 this._emit('plugin:guild:player:tax', { newRate });446 }447 updateGuildTaxRate(newRate) {448 this._emit('plugin:guild:tax', { newRate });449 }450 donateGuildGold(gold) {451 this._emit('plugin:guild:donate', { gold });452 }453 inviteGuildMember(newMemberName) {454 this._emit('plugin:guild:invite', { newMemberName });455 }456 kickGuildMember(memberName) {457 this._emit('plugin:guild:kick', { memberName });458 }459 acceptGuildInvite() {460 this._emit('plugin:guild:invite:accept');461 }462 rejectGuildInvite() {463 this._emit('plugin:guild:invite:reject');464 }465 leaveGuild() {466 this._emit('plugin:guild:leave');467 }468 disbandGuild() {469 this._emit('plugin:guild:disband');470 }471 guildPromote(memberName) {472 this._emit('plugin:guild:promote', { memberName });473 }474 guildDemote(memberName) {475 this._emit('plugin:guild:demote', { memberName });476 }477 renameRetagGuild(name, tag) {478 this._emit('plugin:guild:renameretag', { name, tag });479 }480 buildBuilding(buildingName, slot) {481 this._emit('plugin:guild:building:build', { buildingName, slot });482 }483 upgradeBuilding(buildingName) {484 this._emit('plugin:guild:building:upgrade', { buildingName });485 }486 moveBase(newBase) {487 this._emit('plugin:guild:building:movebase', { newBase });488 }489 updateGuildProp(buildingName, propName, propValue) {490 this._emit('plugin:guild:building:updateprop', { buildingName, propName, propValue });491 }492 // GM493 mute(targetName) {494 this._emit('plugin:chat:togglemute', { targetName });495 }496 ban(targetName) {497 this._emit('plugin:chat:toggleban', { targetName });498 }499 pardon(targetName) {500 this._emit('plugin:chat:togglepardon', { targetName });501 }502 toggleModerator(targetName) {503 this._emit('plugin:gm:togglemod', { targetName });504 }505 rename(targetName, newName) {506 this._emit('plugin:player:changename', { targetName, newName });507 }508 relevel(targetName, targetLevel) {509 this._emit('plugin:gm:setlevel', { targetName, targetLevel });510 }511 restat(targetName, targetStat, targetValue) {512 this._emit('plugin:gm:setstat', { targetName, targetStat, targetValue });513 }514 giveItem(targetName, targetItemString) {515 this._emit('plugin:gm:giveitem', { targetName, targetItemString });516 }517 giveGold(targetName, bonusGold) {518 this._emit('plugin:gm:givegold', { targetName, bonusGold });519 }520 giveILP(targetName, bonusIlp) {521 this._emit('plugin:gm:giveilp', { targetName, bonusIlp });522 }523 teleport(targetName, teleData) {524 this._emit('plugin:gm:teleport', { targetName, teleData });525 }526 toggleAchievement(targetName, achievement) {527 this._emit('plugin:gm:toggleachievement', { targetName, achievement });528 }529 event(targetName, targetEvent) {530 this._emit('plugin:gm:giveevent', { targetName, targetEvent });531 }532 createFestival(targetFestivalString) {533 this._emit('plugin:festival:create', { targetFestivalString });534 }535 cancelFestival(festivalId) {536 this._emit('plugin:festival:cancel', { festivalId });537 }...
CalamansiAudio.js
Source:CalamansiAudio.js
...19 _addEventListeners() {20 this.audio.addEventListener('loadedmetadata', (event) => {21 this.duration = this.audio.duration;22 this._calamansi.currentTrack().info.duration = this.audio.duration;23 this._calamansi._emit('loadedmetadata', this._calamansi);24 CalamansiEvents._emit('loadedmetadata', this._calamansi);25 });26 // Fired when the first frame of the media has finished loading.27 this.audio.addEventListener('loadeddata', (event) => {28 this._setCurrentTime(this.audio.currentTime);29 this._calamansi._emit('loadeddata', this._calamansi);30 CalamansiEvents._emit('loadeddata', this._calamansi);31 });32 // Data loading progress33 this.audio.addEventListener('progress', (event, progress) => {34 // NOTE: There seems to be no way to actually determine how much has35 // been loaded36 });37 // Data has been fully loaded till the end38 this.audio.addEventListener('canplaythrough', (event) => {39 this.loadedPercent = 100;40 this._calamansi._emit('canplaythrough', this._calamansi);41 CalamansiEvents._emit('canplaythrough', this._calamansi);42 this._calamansi._emit('loadingProgress', this._calamansi);43 CalamansiEvents._emit('loadingProgress', this._calamansi);44 });45 this.audio.addEventListener('timeupdate', (event) => {46 this._setCurrentTime(this.audio.currentTime);47 });48 this.audio.addEventListener('ended', (event) => {49 this._setCurrentTime(0);50 this._calamansi._emit('trackEnded', this._calamansi);51 CalamansiEvents._emit('trackEnded', this._calamansi);52 });53 }54 /**55 * Load an audio track from a source56 * 57 * @param string source 58 */59 load(source) {60 this.stop();61 if (source.startsWith('https://api.soundcloud.com')) {62 if (source.endsWith('/')) {63 source = source.substring(0, source.length - 1);64 }65 if (!this._calamansi._options.soundcloudClientId) {66 console.error('Please set your SoundCloud client id in the soundcloudClientId option to play SoundCloud tracks.');67 }68 69 source += '/stream?client_id=' + this._calamansi._options.soundcloudClientId;70 }71 this.audio.src = source;72 this.audio.load();73 }74 /**75 * Start playing the current track from the start76 */77 playFromStart() {78 this.audio.pause();79 this.audio.currentTime = 0;80 this.currentTime = 0;81 this.audio.play();82 this._calamansi._emit('play', this._calamansi);83 CalamansiEvents._emit('play', this._calamansi);84 }85 /**86 * Start/resume playback of the current track87 */88 play() {89 this.audio.play();90 this._calamansi._emit('play', this._calamansi);91 CalamansiEvents._emit('play', this._calamansi);92 }93 /**94 * Pause playback of the current track95 */96 pause() {97 this.audio.pause();98 this._calamansi._emit('pause', this._calamansi);99 CalamansiEvents._emit('pause', this._calamansi);100 }101 /**102 * Stop playback of the current track103 */104 stop() {105 this.audio.pause();106 this.audio.currentTime = 0;107 this.currentTime = 0;108 this._calamansi._emit('stop', this._calamansi);109 CalamansiEvents._emit('stop', this._calamansi);110 }111 /**112 * Unload the currently loaded audio113 */114 unload() {115 this.audio.pause();116 this.audio.removeAttribute('src');117 this.audio.load();118 }119 _setCurrentTime(time) {120 this.currentTime = time;121 this._calamansi._emit('timeupdate', this._calamansi);122 CalamansiEvents._emit('timeupdate', this._calamansi);123 }124 /**125 * Seek to a position126 * 127 * @param int time (seconds)128 */129 seekTo(time) {130 this.audio.currentTime = time;131 this._setCurrentTime(time);132 }133 /**134 * Set player's volume135 * 136 * @param float volume [0.0-1.0]137 */138 changeVolume(volume) {139 volume = volume >= 0 ? volume : 0;140 volume = volume <= 1 ? volume : 1;141 142 this.audio.volume = volume;143 this.volume = volume;144 this._calamansi._emit('volumechange', this._calamansi);145 CalamansiEvents._emit('volumechange', this._calamansi);146 }147 /**148 * Set player's playback rate149 * 150 * @param float rate [0.0-1.0]151 */152 changePlaybackRate(rate) {153 this.playbackRate = rate;154 this.audio.playbackRate = rate;155 this._calamansi._emit('ratechange', this._calamansi);156 CalamansiEvents._emit('ratechange', this._calamansi);157 }158}...
watch.spec.js
Source:watch.spec.js
...29 });30 it('should fire callback once for events which occur within `delay` window', function() {31 var cb = jasmine.createSpy('callback');32 watcher = watch('./$$fake_path/**/*', {delay: 10, log: false}, cb);33 watcher._emit('add', './$$fake_path/test.txt');34 timeout.flush(9);35 expect(cb).not.toHaveBeenCalled();36 watcher._emit('change', './$$fake_path/test.txt');37 watcher._emit('add', './$$fake_path/test2.txt');38 watcher._emit('change', './$$fake_path/test2.txt');39 watcher._emit('add', './$$fake_path/test3.txt');40 watcher._emit('change', './$$fake_path/test3.txt');41 expect(cb).not.toHaveBeenCalled();42 timeout.flush(1);43 expect(cb.calls.count()).toBe(1);44 });45 it('should trigger callback if events are collected during task running', function() {46 var calls = 0;47 function cb(done) {48 if (++calls !== 1) return done();49 watcher._emit('change', './$$fake_path/test1.txt');50 watcher._emit('change', './$$fake_path/test2.txt');51 // Before the done callback, there are no pending timer events52 expect(timeout.pending).toBe(0);53 done();54 // Afterwards, there is one55 expect(timeout.pending).toBe(1);56 }57 var watcher = watch('./$$fake_path/**/*', {delay: 10, log: false}, cb);58 watcher._emit('change', './$$fake_path/test1.txt');59 expect(timeout.pending).toBe(1);60 expect(calls).toBe(0);61 timeout.flush(10);62 expect(calls).toBe(2);63 });64 it('should continue to trigger callbacks if task throws', function() {65 var calls = 0;66 spyOn(console, 'log');67 function cb(done) {68 calls += 1;69 if (calls === 1) throw new Error('oops!');70 done();71 }72 var watcher = watch('./$$fake_path/**/*', {delay: 10, log: false}, cb);73 watcher._emit('change', './$$fake_path/test1.txt');74 timeout.flush();75 expect(calls).toBe(1);76 expect(console.log).toHaveBeenCalledWith('Watch task error:', 'Error: oops!');77 watcher._emit('change', './$$fake_path/test2.txt');78 timeout.flush();79 expect(calls).toBe(2);80 });81 it('should cancel pending callback if FSWatcher is closed', function() {82 var cb = jasmine.createSpy('callback');83 var watcher = watch('./$$fake_path/**/*', {delay: 10, log: false}, cb);84 watcher._emit('change', './$$fake_path/test1.txt');85 expect(timeout.pending).toBe(1);86 expect(cb).not.toHaveBeenCalled();87 watcher.close();88 expect(timeout.pending).toBe(0);89 });90 it('should cancel followup pending callback if FSWatcher is closed during task', function() {91 var calls = 0;92 function cb(done) {93 if (++calls !== 1) return done();94 watcher._emit('change', './$$fake_path/test2.txt');95 done();96 expect(timeout.pending).toBe(1);97 watcher.close();98 expect(timeout.pending).toBe(0);99 }100 var watcher = watch('./$$fake_path/**/*', {delay: 10, log: false}, cb);101 watcher._emit('change', './$$fake_path/test1.txt');102 timeout.flush(10);103 expect(calls).toBe(1);104 });105});106// setTimeout/clearTimeout mocking, mostly stolen from angular-mocks.js107function mockTimeout() {108 var events = [];109 var id = 0;110 var now = 0;111 return {112 mocks: {setTimeout: mockSetTimeout, clearTimeout: mockClearTimeout},113 flush: flush, get pending() { return events.length; }114 };115 function mockSetTimeout(fn, delay) {...
Using AI Code Generation
1var root = new Node('root');2var child1 = new Node('child1');3var child2 = new Node('child2');4root.addChild(child1);5root.addChild(child2);6var child1Child1 = new Node('child1Child1');7var child1Child2 = new Node('child1Child2');8child1.addChild(child1Child1);9child1.addChild(child1Child2);10var child2Child1 = new Node('child2Child1');11var child2Child2 = new Node('child2Child2');12child2.addChild(child2Child1);13child2.addChild(child2Child2);14root._emit('test', 'test1');15var Node = require('./node');16var child1 = new Node('child1');17child1._emit('test', 'test2');18var Node = require('./node');19var child2 = new Node('child2');20child2._emit('test', 'test3');21var Node = require('./node');22var child1Child1 = new Node('child1Child1');23child1Child1._emit('test', 'test4');24var Node = require('./node');25var child1Child2 = new Node('child1Child2');26child1Child2._emit('test', 'test5');27var Node = require('./node');28var child2Child1 = new Node('child2Child1');29child2Child1._emit('test', 'test6');30var Node = require('./node');
Using AI Code Generation
1var root = this;2root._emit('test', 'this is a test');3var root = this;4root._emit('test', 'this is a test2');5var root = this;6root._emit('test', 'this is a test3');7root._emit('test', 'this is a test');8root._on('test', function (data) {9 console.log(data);10});11root._once('test', function (data) {12 console.log(data);13});14root._off('test');15root._offAll();16root._hasListener('test');17root._hasListeners();18root._hasListenersFor('test');
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!