Best JavaScript code snippet using wpt
play.js
Source:play.js  
1var XSystem35 = (function () {2    function XSystem35() {3        isInstalled().then(this.init.bind(this), function () { return show($('.unsupported')); });4        this.naclModule = $('#nacl_module');5        this.volumeControl = new VolumeControl();6        this.zoom = new ZoomManager();7        this.webMidiLinkUrl = localStorage.getItem('midi');8        var naclArgs = [];9        if (this.webMidiLinkUrl)10            naclArgs.push('-Mn');11        if (localStorage.getItem('antialias'))12            naclArgs.push('-antialias');13        var ppapiSimpleVerbosity = '2';14        var debuglv = '1';15        if (window.location.search.length > 1) {16            for (var _i = 0, _a = window.location.search.substr(1).split('&'); _i < _a.length; _i++) {17                var pair = _a[_i];18                var keyValue = pair.split('=');19                switch (keyValue[0]) {20                    case 'debuglv':21                        debuglv = keyValue[1];22                        break;23                    case 'ps_verbosity':24                        ppapiSimpleVerbosity = keyValue[1];25                        break;26                }27            }28        }29        naclArgs.push('-debuglv', debuglv);30        for (var i = 0; i < naclArgs.length; i++)31            this.naclModule.setAttribute('ARG' + (i + 1), naclArgs[i]);32        this.naclModule.setAttribute('PS_VERBOSITY', ppapiSimpleVerbosity);33    }34    XSystem35.prototype.postMessage = function (message) {35        this.naclModule.postMessage(message);36    };37    XSystem35.prototype.init = function (installed) {38        var _this = this;39        if (!installed) {40            show($('.notInstalled'));41            return;42        }43        show($('#contents'));44        document.body.classList.add('bgblack-fade');45        var listener = $('#contents');46        listener.addEventListener('progress', this.onLoadProgress.bind(this), true);47        listener.addEventListener('load', this.moduleDidLoad.bind(this), true);48        listener.addEventListener('message', this.handleMessage.bind(this), true);49        listener.addEventListener('error', this.handleError.bind(this), true);50        listener.addEventListener('crash', this.handleCrash.bind(this), true);51        setupTouchHandlers(this.naclModule);52        this.volumeControl.addEventListener(this.updateVolume.bind(this));53        requestFileSystem().then(function (fs) { return _this.audio = new AudioPlayer(fs.root.toURL(), _this.volumeControl); });54    };55    XSystem35.prototype.onLoadProgress = function (e) {56        if (!e.lengthComputable)57            return;58        var progressBar = $('#progressBar');59        if (!isVisible(progressBar)) {60            show(progressBar);61            ga('send', 'event', 'play', 'slow-load');62        }63        progressBar.max = e.total;64        progressBar.value = e.loaded;65    };66    XSystem35.prototype.moduleDidLoad = function () {67        this.updateStatus('ã');68        hide($('#progressBar'));69        this.zoom.init();70        this.volumeControl.init();71        if (this.webMidiLinkUrl)72            this.midiPlayer = new MidiPlayer(this.webMidiLinkUrl, this.volumeControl);73    };74    XSystem35.prototype.handleMessage = function (message) {75        var data = message.data;76        switch (data.command) {77            case 'ready':78                this.onNaclReady();79                break;80            case 'exit':81                console.log('exit code: ' + data.code);82                hide($('#contents'));83                setTimeout(function () { return show($('#contents')); }, 3000);84                this.audio.stop();85                if (this.midiPlayer)86                    this.midiPlayer.stop();87                break;88            case 'localtime':89                this.reply(data, this.localtime(data.time));90                break;91            case 'set_window_size':92                this.zoom.setWindowSize(data.width, data.height);93                break;94            case 'set_caption':95                this.setCaption(data.caption);96                break;97            case 'cd_play':98                this.audio.play(data.track, data.loop);99                break;100            case 'cd_stop':101                this.audio.stop();102                break;103            case 'cd_getposition':104                this.reply(data, this.audio.getPosition());105                break;106            case 'midi_start':107                this.midiPlayer.play(data.data);108                break;109            case 'midi_stop':110                this.midiPlayer.stop();111                break;112            case 'input_string':113                this.inputString(data);114                break;115            case 'input_number':116                this.inputNumber(data);117                break;118            default:119                if (typeof data === 'string') {120                    console.log(data);121                }122                else {123                    console.log('unknown message');124                    console.log(message);125                }126                break;127        }128    };129    XSystem35.prototype.handleError = function (event) {130        this.updateStatus('ERROR: ' + this.naclModule.lastError);131    };132    XSystem35.prototype.handleCrash = function (event) {133        ga('send', 'event', 'play', 'crashed', this.naclModule.exitStatus + '');134        if (this.naclModule.exitStatus == -1)135            this.updateStatus('CRASHED');136        else137            this.updateStatus('EXITED: ' + this.naclModule.exitStatus);138    };139    XSystem35.prototype.reply = function (data, value) {140        var result = { 'result': value,141            'naclmsg_id': data['naclmsg_id'] };142        this.postMessage({ 'naclmsg': result });143    };144    XSystem35.prototype.updateVolume = function () {145        this.postMessage({ 'setvolume': Math.round(this.volumeControl.volume() * 256) });146    };147    XSystem35.prototype.updateStatus = function (status) {148        $('.pnacl-status').textContent = status;149    };150    XSystem35.prototype.localtime = function (time_t) {151        var t = new Date(time_t * 1000);152        return [t.getSeconds(), t.getMinutes(), t.getHours(),153            t.getDate(), t.getMonth(), t.getFullYear() - 1900, t.getDay()];154    };155    XSystem35.prototype.setCaption = function (buf) {156        var decoder = new TextDecoder('euc-jp');157        var s = decoder.decode(new DataView(buf));158        var title = s.slice(s.indexOf(':') + 1);159        ga('send', 'event', 'play', 'gamestart', title);160        $('title').textContent = title + ' - 鬼çç on Chrome';161    };162    XSystem35.prototype.onNaclReady = function () {163        this.updateVolume();164    };165    XSystem35.prototype.inputString = function (data) {166        var decoder = new TextDecoder('euc-jp');167        var title = decoder.decode(new DataView(data.title)) + ' (å
¨è§' + data.maxlen + 'æåã¾ã§)';168        var oldstring = decoder.decode(new DataView(data.oldstring));169        var newstring = window.prompt(title, oldstring);170        if (newstring) {171            var encoder = new EucjpEncoder();172            var buf = encoder.encode(newstring.substr(0, data.maxlen));173            this.reply(data, buf || data.oldstring);174        }175        else {176            this.reply(data, data.oldstring);177        }178    };179    XSystem35.prototype.inputNumber = function (data) {180        var decoder = new TextDecoder('euc-jp');181        var title = decoder.decode(new DataView(data.title)) + ' [' + data.min + '-' + data.max + ']';182        var result = window.prompt(title, data.default + '');183        if (result)184            this.reply(data, parseInt(result));185        else186            this.reply(data, data.default);187    };188    return XSystem35;189}());190var ZoomManager = (function () {191    function ZoomManager() {192        this.nonFullScreenRatio = 1;193        var naclModule = $('#nacl_module');194        this.width = Number(naclModule.getAttribute('width'));195        this.height = Number(naclModule.getAttribute('height'));196        this.zoomSelect = $('#zoom');197        this.zoomSelect.addEventListener('change', this.handleZoom.bind(this));198        document.addEventListener('webkitfullscreenchange', this.onFullScreenChange.bind(this));199        if (navigator.userAgent.indexOf('Mac OS X') != -1) {200            var opt = $('#option-fullscreen');201            opt.parentElement.removeChild(opt);202        }203    }204    ZoomManager.prototype.init = function () {205        show(this.zoomSelect);206        var ratio = localStorage.getItem('zoom');207        if (ratio != 'full' && Number(ratio) < 1 || Number(ratio) > 3)208            ratio = null;209        if (ratio && ratio != '1') {210            this.zoomSelect.value = String(ratio);211            this.handleZoom();212        }213    };214    ZoomManager.prototype.setWindowSize = function (width, height) {215        this.width = width;216        this.height = height;217        this.handleZoom();218    };219    ZoomManager.prototype.onFullScreenChange = function () {220        if (!document.webkitFullscreenElement)221            this.zoomSelect.value = String(this.nonFullScreenRatio);222        this.handleZoom();223    };224    ZoomManager.prototype.handleZoom = function () {225        var naclModule = $('#nacl_module');226        var value = this.zoomSelect.value;227        localStorage.setItem('zoom', value);228        if (value == 'full') {229            if (!document.webkitFullscreenElement) {230                naclModule.webkitRequestFullScreen();231            }232            else {233                var ratio = Math.min(window.innerWidth / this.width, window.innerHeight / this.height);234                naclModule.setAttribute('width', String(this.width * ratio));235                naclModule.setAttribute('height', String(this.height * ratio));236            }237        }238        else {239            var ratio = Number(value);240            $('#contents').style.width = (this.width * ratio) + 'px';241            naclModule.setAttribute('width', String(this.width * ratio));242            naclModule.setAttribute('height', String(this.height * ratio));243            this.nonFullScreenRatio = ratio;244        }245    };246    return ZoomManager;247}());248var TouchState;249(function (TouchState) {250    TouchState[TouchState["Up"] = 0] = "Up";251    TouchState[TouchState["Down"] = 1] = "Down";252    TouchState[TouchState["Left"] = 2] = "Left";253    TouchState[TouchState["Right"] = 3] = "Right";254    TouchState[TouchState["Tap"] = 4] = "Tap";255})(TouchState || (TouchState = {}));256;257function setupTouchHandlers(element) {258    var touchState = TouchState.Up;259    var touchTimer;260    element.addEventListener('touchstart', onTouchStart);261    element.addEventListener('touchmove', onTouchMove);262    element.addEventListener('touchend', onTouchEnd);263    function onTouchStart(event) {264        if (event.touches.length != 1)265            return;266        event.preventDefault();267        var touch = event.touches[0];268        generateMouseEvent('mousemove', 0, touch);269        switch (touchState) {270            case TouchState.Tap:271                clearTimeout(touchTimer);272            case TouchState.Up:273                touchState = TouchState.Down;274                touchTimer = setTimeout(function () {275                    generateMouseEvent('mousedown', 2, touch);276                    touchState = TouchState.Right;277                }, 600);278                break;279        }280    }281    function onTouchMove(event) {282        if (event.touches.length != 1)283            return;284        event.preventDefault();285        var touch = event.touches[0];286        if (touchState === TouchState.Down) {287            clearTimeout(touchTimer);288            generateMouseEvent('mousedown', 0, touch);289            touchState = TouchState.Left;290        }291        generateMouseEvent('mousemove', 0, touch);292    }293    function onTouchEnd(event) {294        if (event.changedTouches.length != 1)295            return;296        event.preventDefault();297        var touch = event.changedTouches[0];298        switch (touchState) {299            case TouchState.Down:300                clearTimeout(touchTimer);301                generateMouseEvent('mousedown', 0, touch);302                touchState = TouchState.Tap;303                touchTimer = setTimeout(function () {304                    generateMouseEvent('mouseup', 0, touch);305                    touchState = TouchState.Up;306                }, 20);307                break;308            case TouchState.Left:309                generateMouseEvent('mouseup', 0, touch);310                touchState = TouchState.Up;311                break;312            case TouchState.Right:313                generateMouseEvent('mouseup', 2, touch);314                touchState = TouchState.Up;315                break;316        }317    }318    function generateMouseEvent(type, button, t) {319        var mouseEvent = document.createEvent('MouseEvents');320        mouseEvent.initMouseEvent(type, true, true, window, 0, t.screenX, t.screenY, t.clientX, t.clientY, false, false, false, false, button, null);321        element.dispatchEvent(mouseEvent);322    }323}324var VolumeControl = (function () {325    function VolumeControl() {326        this.vol = Number(localStorage.getItem('volume') || 1);327        this.muted = false;328        this.elem = document.getElementById('volume-control');329        this.icon = document.getElementById('volume-control-icon');330        this.slider = document.getElementById('volume-control-slider');331        this.slider.value = Math.round(this.vol * 100) + '';332        this.icon.addEventListener('click', this.onIconClicked.bind(this));333        this.slider.addEventListener('input', this.onSliderValueChanged.bind(this));334        this.slider.addEventListener('change', this.onSliderValueSettled.bind(this));335    }336    VolumeControl.prototype.init = function () {337        show(this.elem);338    };339    VolumeControl.prototype.volume = function () {340        return this.muted ? 0 : parseInt(this.slider.value) / 100;341    };342    VolumeControl.prototype.addEventListener = function (handler) {343        this.elem.addEventListener('volumechange', handler);344    };345    VolumeControl.prototype.onIconClicked = function (e) {346        this.muted = !this.muted;347        if (this.muted) {348            this.icon.classList.remove('fa-volume-up');349            this.icon.classList.add('fa-volume-off');350            this.slider.value = '0';351        }352        else {353            this.icon.classList.remove('fa-volume-off');354            this.icon.classList.add('fa-volume-up');355            this.slider.value = String(Math.round(this.vol * 100));356        }357        this.dispatchEvent();358    };359    VolumeControl.prototype.onSliderValueChanged = function (e) {360        this.vol = parseInt(this.slider.value) / 100;361        if (this.vol > 0 && this.muted) {362            this.muted = false;363            this.icon.classList.remove('fa-volume-off');364            this.icon.classList.add('fa-volume-up');365        }366        this.dispatchEvent();367    };368    VolumeControl.prototype.onSliderValueSettled = function (e) {369        localStorage.setItem('volume', this.vol + '');370    };371    VolumeControl.prototype.dispatchEvent = function () {372        var event = new CustomEvent('volumechange', { detail: this.volume() });373        this.elem.dispatchEvent(event);374    };375    return VolumeControl;376}());377var AudioPlayer = (function () {378    function AudioPlayer(bgmDir, volumeControl) {379        this.bgmDir = bgmDir;380        this.volumeControl = volumeControl;381        this.tracks = JSON.parse(localStorage.getItem('tracks') || '[]');382        volumeControl.addEventListener(this.onVolumeChanged.bind(this));383    }384    AudioPlayer.prototype.play = function (track, loop) {385        if (this.elem)386            this.stop();387        var audio = document.createElement('audio');388        audio.setAttribute('src', this.trackURL(track));389        audio.volume = this.volumeControl.volume();390        audio.loop = (loop != 0);391        document.getElementById('contents').appendChild(audio);392        audio.load();393        audio.play();394        this.elem = audio;395        this.currentTrack = track;396    };397    AudioPlayer.prototype.stop = function () {398        if (this.elem) {399            this.elem.pause();400            this.elem.parentNode.removeChild(this.elem);401            this.elem = null;402            this.currentTrack = 0;403        }404    };405    AudioPlayer.prototype.getPosition = function () {406        if (!this.elem || this.elem.ended)407            return 0;408        var time = Math.round(this.elem.currentTime * 75);409        return this.currentTrack | time << 8;410    };411    AudioPlayer.prototype.trackURL = function (n) {412        return this.bgmDir + (this.tracks[n] || 'track' + n + '.wav');413    };414    AudioPlayer.prototype.onVolumeChanged = function (evt) {415        if (this.elem)416            this.elem.volume = evt.detail;417    };418    return AudioPlayer;419}());420var MidiPlayer = (function () {421    function MidiPlayer(url, volumeControl) {422        this.volumeControl = volumeControl;423        this.worker = new Worker('js/midi-worker.js');424        this.iframe = document.createElement('iframe');425        this.worker.addEventListener('message', this.onMessageFromWorker.bind(this));426        window.addEventListener('message', this.onMessageFromIframe.bind(this));427        this.iframe.src = url;428        document.body.appendChild(this.iframe);429        volumeControl.addEventListener(this.onVolumeChanged.bind(this));430        this.worker.postMessage({ command: 'volume', value: volumeControl.volume() });431    }432    MidiPlayer.prototype.play = function (buf) {433        this.worker.postMessage({ command: 'play', smf: buf });434    };435    MidiPlayer.prototype.stop = function () {436        this.worker.postMessage({ command: 'stop' });437    };438    MidiPlayer.prototype.onMessageFromWorker = function (evt) {439        this.iframe.contentWindow.postMessage(evt.data, '*');440    };441    MidiPlayer.prototype.onMessageFromIframe = function (evt) {442        this.worker.postMessage(evt.data);443    };444    MidiPlayer.prototype.onVolumeChanged = function (evt) {445        this.worker.postMessage({ command: 'volume', value: evt.detail });446    };447    return MidiPlayer;448}());449var EucjpEncoder = (function () {450    function EucjpEncoder() {451        if (!EucjpEncoder.table)452            this.generateTable();453    }454    EucjpEncoder.prototype.encode = function (s) {455        var bytes = [];456        for (var i = 0; i < s.length; i++) {457            var euc = EucjpEncoder.table[s.charAt(i)];458            if (euc) {459                bytes.push(euc >> 8);460                bytes.push(euc & 0xff);461            }462            else {463                return null;464            }465        }466        return new Uint8Array(bytes).buffer;467    };468    EucjpEncoder.prototype.generateTable = function () {469        EucjpEncoder.table = {};470        var decoder = new TextDecoder('euc-jp');471        var buf = new Uint8Array(2);472        for (var c1 = 0xa1; c1 <= 0xfc; c1++) {473            buf[0] = c1;474            for (var c2 = 0xa1; c2 <= 0xfe; c2++) {475                buf[1] = c2;476                var s = decoder.decode(buf);477                if (s.length == 1 && s != '\uFFFD')478                    EucjpEncoder.table[s] = (c1 << 8) | c2;479            }480        }481    };482    return EucjpEncoder;483}());...index.d.ts
Source:index.d.ts  
1export * from './EUCJPDecoder';...Using AI Code Generation
1var wptools = require("wptools");2var eucjpEncoder = wptools.eucjpEncoder;3var str = "あいうえお";4var eucjpStr = eucjpEncoder(str);5console.log(eucjpStr);6Copyright (c) 2016 Shinnosuke WatanabeUsing AI Code Generation
1var wptools = require('wptools');2var eucjpEncoder = wptools.eucjpEncoder;3var eucjpDecoder = wptools.eucjpDecoder;4var text = 'こんにちは';5var encodedText = eucjpEncoder(text);6console.log('encodedText: ' + encodedText);7var decodedText = eucjpDecoder(encodedText);8console.log('decodedText: ' + decodedText);Using AI Code Generation
1var eucjpEncoder = new TextEncoder("euc-jp");2var eucjpArray = eucjpEncoder.encode("あいうえお");3console.log(eucjpArray);4var eucjpDecoder = new TextDecoder("euc-jp");5var eucjpString = eucjpDecoder.decode(eucjpArray);6console.log(eucjpString);7var utf8Encoder = new TextEncoder("utf-8");8var utf8Array = utf8Encoder.encode("あいうえお");9console.log(utf8Array);10var utf8Decoder = new TextDecoder("utf-8");11var utf8String = utf8Decoder.decode(utf8Array);12console.log(utf8String);13var sjisEncoder = new TextEncoder("shift_jis");14var sjisArray = sjisEncoder.encode("あいうえお");15console.log(sjisArray);16var sjisDecoder = new TextDecoder("shift_jis");17var sjisString = sjisDecoder.decode(sjisArray);18console.log(sjisString);19var utf16Encoder = new TextEncoder("utf-16");20var utf16Array = utf16Encoder.encode("あいうえお");21console.log(utf16Array);22var utf16Decoder = new TextDecoder("utf-16");23var utf16String = utf16Decoder.decode(utf16Array);24console.log(utf16String);25var utf16beEncoder = new TextEncoder("utf-16be");26var utf16beArray = utf16beEncoder.encode("あいうえお");27console.log(utf16beArray);28var utf16beDecoder = new TextDecoder("utf-16be");29var utf16beString = utf16beDecoder.decode(utf16beArray);30console.log(utfUsing AI Code Generation
1var enc = new TextEncoder('euc-jp');2var dec = new TextDecoder('euc-jp');3var str = 'こんにちは';4var eucjpEncoded = enc.encode(str);5var decoded = dec.decode(eucjpEncoded);6console.log(decoded);Using AI Code Generation
1var eucjpEncoder = new TextEncoder('euc-jp');2var eucjpString = eucjpEncoder.encode('こんにちは');3console.log(eucjpString);4var eucjpDecoder = new TextDecoder('euc-jp');5var decodedString = eucjpDecoder.decode(eucjpString);6console.log(decodedString);7Uint8Array(15) [ 129, 164, 129, 168, 129, 166, 129, 172, 129, 170, 129, 174, 129, 176, 129 ]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!!
