Best JavaScript code snippet using best
VirtualNodeContext.js
Source:VirtualNodeContext.js
1import ExtendableProxy from "./ExtendableProxy.js";2import FrameworkEventTarget from "./FrameworkEventTarget.js";3import GlobalObserverHandler from "./GlobalObserverHandler.js";4import GlobalValueChangedEventArgs from "./GlobalValueChangedEventArgs.js";5import ValueChangedEventArgs from "./ValueChangedEventArgs.js";6import VirtualNode from "./VirtualNode.js";7/**8 * @typedef {Object} HookGetEventArgs9 * @property {*} object10 * @property {string | symbol} key11 * @property {boolean} handled12 * @property {VirtualNodeContext} sender13 */14/**15 * @callback HookGetEventHandler16 * @param {HookGetEventArgs} e17 * @returns {*}18 */19/**20 * @typedef {Object} HookSetEventArgs21 * @property {*} object22 * @property {string | symbol} key23 * @property {*} value24 * @property {boolean} handled25 * @property {VirtualNodeContext} sender26 */27/**28 * @callback HookSetEventHandler29 * @param {HookSetEventArgs} e30 * @returns {void}31 */32/**33 * @typedef {Object} HookHandler34 * @property {?HookGetEventHandler} get35 * @property {?HookSetEventHandler} set36 */37export default class VirtualNodeContext extends ExtendableProxy {38 /** @type {VirtualNode} */ #virtualNode39 /** @type {FrameworkEventTarget} */ #eventTarget = new FrameworkEventTarget()40 /** @type {Object<string, HookHandler[]>} */ #hookHandlers = {}41 /** @type {any} */ #object42 /**43 * @param {VirtualNode} virtualNode44 */45 constructor(virtualNode) {46 const parameters = { target: {}, handler: {} };47 super(parameters, VirtualNodeContext.prototype);48 parameters.handler.get = this.#OnGet.bind(this);49 parameters.handler.set = this.#OnSet.bind(this);50 this.#object = parameters.target;51 this.#virtualNode = virtualNode;52 }53 /**54 * @param {string} script 55 * @returns {any}56 */57 EvalScript(script) {58 return (function() { return eval(script) }).call(this);59 }60 /**61 * @param {string} script 62 * @returns {any}63 */64 EvalFunction(script) {65 return new Function(script).call(this);66 }67 /**68 * @param {string} key69 * @param {HookHandler} hookHandler 70 */71 AddHook(key, hookHandler) {72 if (!this.#hookHandlers[key])73 this.#hookHandlers[key] = [hookHandler];74 else75 this.#hookHandlers[key].push(hookHandler);76 }77 /**78 * @param {string} key79 * @param {HookHandler} hookHandler 80 */81 RemoveHook(key, hookHandler) {82 if (this.#hookHandlers[key])83 this.#hookHandlers[key] = this.#hookHandlers[key].filter(hh => hh != hookHandler);84 }85 /**86 * @param {string} type87 * @param {HookGetEventArgs | HookSetEventArgs} eventArgs88 */89 #DispatchHook(type, eventArgs) {90 if (this.#hookHandlers[eventArgs.key])91 for (let hookHandler of this.#hookHandlers[eventArgs.key]) {92 if (!hookHandler[type])93 continue;94 const value = hookHandler[type](eventArgs);95 if (eventArgs.handled)96 return value;97 }98 if (this.#hookHandlers["any"])99 for (let hookHandler of this.#hookHandlers["any"]) {100 if (!hookHandler[type])101 continue;102 const value = hookHandler[type](eventArgs);103 if (eventArgs.handled)104 return value;105 }106 return null;107 }108 /**109 * @param {string} type110 * @param {import("./FrameworkEventTarget").EventHandler<ValueChangedEventArgs>} callback111 */112 On(type, callback) {113 this.#eventTarget.On(type, callback);114 }115 /**116 * @param {string} type117 * @param {import("./FrameworkEventTarget").EventHandler<ValueChangedEventArgs>} callback118 */119 Off(type, callback) {120 this.#eventTarget.Off(type, callback);121 }122 /**123 * @param {string} name124 * @param {*} object125 * @param {string | symbol} key126 * @param {*} value127 */128 #Dispatch(name, object, key, value) {129 this.#eventTarget.Dispatch(new ValueChangedEventArgs(object, key, value, name, this));130 GlobalObserverHandler.Dispatch(new GlobalValueChangedEventArgs(this.#eventTarget, object, key, value, name, this));131 }132 /**133 * @param {*} object134 * @param {string | symbol} key135 * @returns {*}136 */137 #OnGet(object, key) {138 /** @type {HookGetEventArgs} */139 const e = { object, key, handled: false, sender: this };140 const value = this.#DispatchHook("get", e);141 if (e.handled)142 return value;143 if (key in object) {144 const value = object[key];145 if (!(key in VirtualNodeContext.prototype))146 this.#Dispatch("get", object, key, value);147 return value;148 }149 if (key.length > 0 && key[0] == '$') {150 if (key.length == 1) {151 return this.#virtualNode;152 } else {153 const nodeKey = key[1].toUpperCase() + key.slice(2);154 if (nodeKey in this.#virtualNode) {155 const value = this.#virtualNode[nodeKey];156 if (value instanceof Function)157 return value.bind(this.#virtualNode);158 else159 return value;160 }161 }162 }163 if (!this.#virtualNode.IsComponent && this.#virtualNode.Parent)164 return this.#virtualNode.Parent.Context[key];165 else166 return window[key];167 }168 /**169 * @param {*} object170 * @param {string | symbol} key171 * @param {*} value172 * @returns {boolean}173 */174 #OnSet(object, key, value) {175 /** @type {HookSetEventArgs} */176 const e = { object, key, value, handled: false, sender: this };177 this.#DispatchHook("set", e);178 if (e.handled)179 return true;180 if (!this.#DeepSetValue(key, value))181 return this.#SetValue(object, key, value);182 183 return true;184 }185 /**186 * @param {string | symbol} key187 * @param {*} value188 * @returns {boolean}189 */190 #DeepSetValue(key, value) {191 if (key in this.#object) {192 this.#object[key] = value;193 return this.#SetValue(this.#object, key, value);194 }195 if (this.#virtualNode.Parent) {196 if (!this.#virtualNode.IsComponent)197 return this.#virtualNode.Parent.Context.#DeepSetValue(key, value);198 } else {199 if (key in window) {200 window[key] = value;201 return true;202 }203 }204 return false;205 }206 /**207 * @param {*} object208 * @param {string | symbol} key209 * @param {*} value210 * @returns {boolean}211 */212 #SetValue(object, key, value) {213 const isAdded = !(key in object);214 // if (value instanceof Array)215 // value = new ObservableArray(value);216 // else if (value instanceof Object && !(value instanceof Function))217 // value = new ObservableObject(value);218 object[key] = value;219 if (isAdded)220 this.#Dispatch("add", object, key, value);221 else222 this.#Dispatch("set", object, key, value);223 return true;224 }...
saga.js
Source:saga.js
1import { take, put, call, fork, select, all, takeLatest, takeEvery } from 'redux-saga/effects'2import { ForkListeners } from '../../utils/saga'3import { devLogger } from '../../utils/console'4import actions, { TYPES } from './actions'5import consoleTools from 'template-ui/lib/utils/console'6const RouterSaga = (opts = {}) => {7 if(!opts.hooks) throw new Error('hooks needed for RouterSaga')8 if(!opts.basepath) throw new Error('basepath needed for RouterSaga')9 const { hooks, basepath } = opts10 consoleTools.devRun(() => {11 console.log('have hooks:')12 console.dir(Object.keys(hooks))13 })14 const getRoute = (path) => basepath + path15 // a named hook might actually have multiple handler functions16 // run each handler function with the same payload in series17 function* runHook(name, payload) {18 if(opts.trigger) opts.trigger(name, payload)19 if(name.indexOf('/') == 0) {20 // replace `:param` with values from state21 const routerParams = yield select(state => state.router.params)22 name = name.replace(/:(\w+)/g, name => {23 return routerParams[name.replace(/^:/, '')]24 })25 yield put(actions.push(getRoute(name)))26 }27 else {28 const hookHandlers = hooks[name]29 if(!hookHandlers) {30 devLogger(`no hook found for ${name}`, 'error')31 return32 }33 const hookHandlerArray = hookHandlers.constructor === Array ?34 [].concat(hookHandlers) :35 [hookHandlers]36 const useHandlers = hookHandlerArray.filter(h => h)37 if(useHandlers.length <= 0) {38 devLogger(`no hooks found for ${name}`, 'error')39 return40 }41 42 while(hookHandlerArray.length > 0) {43 const nextHandler = hookHandlerArray.shift()44 // allow hooks to call other hooks with the same payload45 if(typeof(nextHandler) == 'string') {46 yield call(runHook, nextHandler, payload) 47 }48 else {49 yield call(nextHandler, payload) 50 }51 52 }53 }54 }55 // handle a trigger from other code56 function* handleHookAction(action) {57 yield call(runHook, action.name, action.payload)58 }59 // execute the hooks found in the route config60 function* runRouteHooks(hookArray) {61 hookArray = typeof(hookArray) == 'string' ? [hookArray] : hookArray62 if(hookArray && hookArray.length > 0) {63 const hookHandlerArray = hookArray64 .map(hook => {65 return typeof(hook) == 'string' ?66 {name:hook,payload:null} :67 hook68 })69 while(hookHandlerArray.length > 0) {70 const nextHook = hookHandlerArray.shift()71 yield call(runHook, nextHook.name, nextHook.payload)72 }73 }74 }75 // the route config may list an array of handler names76 // if the handler is a string - it is turned into {name}77 // this way - the router can also pass a payload {name,payload}78 // each name/payload combo is run in series79 function* routerChanged() {80 if(opts.onChange) {81 yield call(opts.onChange)82 }83 const router = yield select(state => state.router)84 const routeInfo = router.result || {}85 if(opts.authenticate) {86 const authResult = yield call(opts.authenticate)87 if(!authResult) return88 }89 // run the onLeave hooks for the previous route (if any)90 const previousRouteInfo = router.previous || {}91 const previousRouteHooks = (previousRouteInfo.result || {}).onLeave92 if(previousRouteHooks) {93 yield call(runRouteHooks, previousRouteHooks)94 }95 // if we have a redirect then do it and cancel any other hooks96 if(routeInfo.redirect) {97 yield call(runHook, routeInfo.redirect)98 return99 }100 const routeHooks = (routeInfo.onEnter || routeInfo.hooks || [])101 yield call(runRouteHooks, routeHooks)102 }103 // called once we have loaded user info104 function* initialize() {105 const routerState = yield select(state => state.router)106 yield call(routerChanged)107 }108 const listeners = ForkListeners([109 [TYPES.changed, routerChanged],110 [TYPES.redirect, handleHookAction],111 [TYPES.hook, handleHookAction]112 ])113 function* main() {114 yield fork(listeners)115 }116 function* setupListeners() {117 yield fork(listeners)118 }119 return {120 initialize,121 main,122 setupListeners123 }124}...
main.ts
Source:main.ts
1import 'dayjs/locale/ko';2import dayjs from 'dayjs';3import * as admin from 'firebase-admin';4import * as functions from 'firebase-functions';5import apiHandler from './api';6import * as batchHandlers from './batch';7import * as cronHandlers from './cron';8import * as hookHandlers from './hook';9import { CLIENT_COLLECTION_ID, WORKER_COLLECTION_ID, WORK_COLLECTION_ID, RECRUIT_COLLECTION_ID, REVIEW_COLLECTION_ID } from '../firestore';10const REGION = 'asia-northeast3';11dayjs.locale('ko');12admin.initializeApp();13export const api = functions.region(REGION).https.onRequest(apiHandler);14export const batch = {15 generateFake: functions.region(REGION).https.onRequest(batchHandlers.generateFake),16};17export const cron = {18 dailyJob: functions.region(REGION).pubsub.schedule('every day 00:00').timeZone('Asia/Seoul').onRun(cronHandlers.dailyJob),19};20export const hook = {21 onCreateClient: functions.region(REGION).firestore.document(`${CLIENT_COLLECTION_ID}/{clientId}`).onCreate(hookHandlers.onCreateClient),22 onCreateWorker: functions.region(REGION).firestore.document(`${WORKER_COLLECTION_ID}/{workerId}`).onCreate(hookHandlers.onCreateWorker),23 onUpdateWorker: functions.region(REGION).firestore.document(`${WORKER_COLLECTION_ID}/{workerId}`).onUpdate(hookHandlers.onUpdateWorker),24 onCreateWork: functions.region(REGION).firestore.document(`${WORK_COLLECTION_ID}/{workId}`).onCreate(hookHandlers.onCreateWork),25 onUpdateWork: functions.region(REGION).firestore.document(`${WORK_COLLECTION_ID}/{workId}`).onUpdate(hookHandlers.onUpdateWork),26 onCreateRecruit: functions.region(REGION).firestore.document(`${RECRUIT_COLLECTION_ID}/{recruitId}`).onCreate(hookHandlers.onCreateRecruit),27 onUpdateRecruit: functions.region(REGION).firestore.document(`${RECRUIT_COLLECTION_ID}/{recruitId}`).onUpdate(hookHandlers.onUpdateRecruit),28 onCreateReview: functions.region(REGION).firestore.document(`${REVIEW_COLLECTION_ID}/{reviewId}`).onCreate(hookHandlers.onCreateReview),...
Using AI Code Generation
1var BestPractice = require('BestPractice');2var bestPractice = new BestPractice();3var BestPractice = require('BestPractice');4var bestPractice = new BestPractice();5bestPractice.hookHandlers();6var BestPractice = require('BestPractice');7var bestPractice = new BestPractice();8bestPractice.hookHandlers();9var BestPractice = require('BestPractice');10var bestPractice = new BestPractice();11bestPractice.hookHandlers();12var BestPractice = require('BestPractice');13var bestPractice = new BestPractice();14bestPractice.hookHandlers();15var BestPractice = require('BestPractice');16var bestPractice = new BestPractice();17bestPractice.hookHandlers();18var BestPractice = require('BestPractice');19var bestPractice = new BestPractice();20bestPractice.hookHandlers();21var BestPractice = require('BestPractice');22var bestPractice = new BestPractice();23bestPractice.hookHandlers();24var BestPractice = require('BestPractice');25var bestPractice = new BestPractice();26bestPractice.hookHandlers();27var BestPractice = require('BestPractice');28var bestPractice = new BestPractice();29bestPractice.hookHandlers();30var BestPractice = require('BestPractice');31var bestPractice = new BestPractice();32bestPractice.hookHandlers();33var BestPractice = require('BestPractice');34var bestPractice = new BestPractice();35bestPractice.hookHandlers();36var BestPractice = require('BestPractice');37var bestPractice = new BestPractice();38bestPractice.hookHandlers();39var BestPractice = require('BestPractice');40var bestPractice = new BestPractice();41bestPractice.hookHandlers();42var BestPractice = require('BestPractice');
Using AI Code Generation
1var BestPracticeChecker = require('./BestPracticeChecker');2var bestPracticeChecker = new BestPracticeChecker();3var path = require('path');4var filePath = path.resolve(__dirname, 'test3.js');5bestPracticeChecker.hookHandlers(filePath, function (err, data) {6 if (err) {7 console.log(err);8 }9 console.log(data);10});11var BestPracticeChecker = require('./BestPracticeChecker');12var bestPracticeChecker = new BestPracticeChecker();13var path = require('path');14var filePath = path.resolve(__dirname, 'test4.js');15bestPracticeChecker.hookHandlers(filePath, function (err, data) {16 if (err) {17 console.log(err);18 }19 console.log(data);20});21var BestPracticeChecker = require('./BestPracticeChecker');22var bestPracticeChecker = new BestPracticeChecker();23var path = require('path');24var filePath = path.resolve(__dirname, 'test5.js');25bestPracticeChecker.hookHandlers(filePath, function (err, data) {26 if (err) {27 console.log(err);28 }29 console.log(data);30});31var BestPracticeChecker = require('./BestPracticeChecker');32var bestPracticeChecker = new BestPracticeChecker();33var path = require('path');34var filePath = path.resolve(__dirname, 'test6.js');35bestPracticeChecker.hookHandlers(filePath, function (err, data) {36 if (err) {37 console.log(err);38 }39 console.log(data);40});41var BestPracticeChecker = require('./BestPracticeChecker');42var bestPracticeChecker = new BestPracticeChecker();43var path = require('path');44var filePath = path.resolve(__dirname, 'test7.js');45bestPracticeChecker.hookHandlers(filePath, function (err, data) {46 if (err) {47 console.log(err);48 }49 console.log(data);50});51var BestPracticeChecker = require('./BestPracticeChecker');52var bestPracticeChecker = new BestPracticeChecker();53var path = require('
Using AI Code Generation
1var BestPractice = require('./BestPractice');2var bp = new BestPractice();3var BestPractice = require('./BestPractice');4var bp = new BestPractice();5var BestPractice = require('./BestPractice');6var bp = new BestPractice();7var BestPractice = require('./BestPractice');8var bp = new BestPractice();9var BestPractice = require('./BestPractice');10var bp = new BestPractice();11var BestPractice = require('./BestPractice');12var bp = new BestPractice();13var BestPractice = require('./BestPractice');14var bp = new BestPractice();15var BestPractice = require('./BestPractice');16var bp = new BestPractice();17var BestPractice = require('./BestPractice');18var bp = new BestPractice();19var BestPractice = require('./BestPractice');20var bp = new BestPractice();21var BestPractice = require('./BestPractice');22var bp = new BestPractice();23var BestPractice = require('./BestPractice');24var bp = new BestPractice();25var BestPractice = require('./BestPractice');26var bp = new BestPractice();
Using AI Code Generation
1var BestPractice = require('bestpractice');2var bestPractice = new BestPractice();3bestPractice.hookHandlers();4var test = require('./test2');5test.foo();6var BestPractice = require('bestpractice');7var bestPractice = new BestPractice();8bestPractice.hookHandlers();9var test = require('./test3');10test.foo();11var BestPractice = require('bestpractice');12var bestPractice = new BestPractice();13bestPractice.hookHandlers();14var test = require('./test4');15test.foo();16var BestPractice = require('bestpractice');17var bestPractice = new BestPractice();18bestPractice.hookHandlers();19var test = require('./test2');20test.foo();21var BestPractice = require('bestpractice');22var bestPractice = new BestPractice();23bestPractice.hookHandlers();24var test = require('./test3');25test.foo();26var BestPractice = require('bestpractice');27var bestPractice = new BestPractice();28bestPractice.hookHandlers();29var test = require('./test4');30test.foo();31var BestPractice = require('bestpractice');32var bestPractice = new BestPractice();33bestPractice.hookHandlers();34var test = require('./test2');35test.foo();36var BestPractice = require('bestpractice');37var bestPractice = new BestPractice();38bestPractice.hookHandlers();39var test = require('./test3');40test.foo();41var BestPractice = require('bestpractice');42var bestPractice = new BestPractice();43bestPractice.hookHandlers();44var test = require('./test4');45test.foo();
Using AI Code Generation
1var BestPractice = require('./BestPractice.js');2var bestPractice = new BestPractice();3var fs = require('fs');4var test4 = function(){5 fs.writeFile('test4.txt','test4',function(err){6 if (err) throw err;7 console.log('file saved');8 });
Using AI Code Generation
1var test = require('tape');2var hook = require('../lib/hook');3test('test4', function(t) {4 t.plan(1);5 hook.hookHandlers('before', function() {6 t.pass('before hook called');7 });8 t.pass('test4 called');9});
Using AI Code Generation
1var BestPractice = require('bestpractice');2var bp = new BestPractice();3var path = require('path');4var hookHandlers = {5 'hook1': function() {6 console.log('hook1 called');7 },8 'hook2': function() {9 console.log('hook2 called');10 }11};12bp.hookHandlers(hookHandlers);13bp.addHook('hook1');14bp.addHook('hook2');15bp.runHooks();16var BestPractice = require('bestpractice');17var bp = new BestPractice();18var path = require('path');19var hookHandlers = {20 'hook1': function() {21 console.log('hook1 called');22 },23 'hook2': function() {24 console.log('hook2 called');25 }26};27bp.hookHandlers(hookHandlers);28bp.addHook('hook1');29bp.addHook('hook2');30bp.runHooks();31var BestPractice = require('bestpractice');32var bp = new BestPractice();33var path = require('path');34var hookHandlers = {35 'hook1': function() {36 console.log('hook1 called');37 },38 'hook2': function() {39 console.log('hook2 called');40 }41};42bp.hookHandlers(hookHandlers);43bp.addHook('hook1');44bp.addHook('hook2');45bp.runHooks();
Using AI Code Generation
1var fs = require('fs');2var BestBuyAPI = require('./BestBuyAPI.js');3var bestBuyAPI = new BestBuyAPI();4bestBuyAPI.hookHandlers(function(data){5 fs.writeFile('products.json', JSON.stringify(data), function(err){6 if(err){7 console.log(err);8 }else{9 console.log('products.json saved');10 }11 });12});
Using AI Code Generation
1var bestbuy = require('bestbuy')('d1c8a6e3a2c2e3f3f2c8d2a2');2bestbuy.hookHandlers({3 products: function (data) {4 console.log('products', data);5 }6});7bestbuy.products('(search=ipod)', {show: 'sku,name,salePrice', pageSize: 5, page: 2}).then(function (data) {8 console.log('products', data);9});10bestbuy.products('(search=ipod)', {show: 'sku,name,salePrice', pageSize: 5, page: 2}).then(function (data) {11 console.log('products', data);12});13bestbuy.product('sku=1000001').then(function (data) {14 console.log('product', data);15});16bestbuy.categories('(id=abcat0101000)', {show: 'id,name', pageSize: 5, page: 2}).then(function (data) {17 console.log('categories', data);18});19bestbuy.category('abcat0101000').then(function (data) {20 console.log('category', data);21});22bestbuy.stores('(area(60618,25))', {show: 'storeId,city,distance,region', pageSize: 5, page: 2}).then(function (data) {23 console.log('stores', data);24});25bestbuy.store('storeId=2740').then(function (data) {26 console.log('store', data);27});28bestbuy.deals('(area(60618,25))', {show: 'sku,name,salePrice', pageSize: 5, page: 2}).then(function (data) {29 console.log('deals', data);30});31bestbuy.deal('sku=1000001').then(function (data) {32 console.log('deal', data);33});34bestbuy.openBox('(
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!!