Recent Entries 10
- pattern minor 112d agoSlaying a dragon, the old-school wayIs the below program written in the most efficient way possible? I am new to Java Script and am just trying to make something basic so I can practice as I learn more. The way I wrote it the program does work (except it keeps wanting to run again after it's over?) but is there a better way I could have accomplished this? ``` var charName = prompt("Hello Lost Stranger, Tell us your name!"); alert("Welcome " + charName + " we have been waiting for someone who can challenge this dragon!"); alert("A rather small but still intimidating dragon appears; it does not look happy."); var charHP = 3000; var mobHP = 3000; var userAttack = "What type of attack will you use?(Choices: Sword, Charge, Spell)"; var diceOne = Math.floor(Math.random() * 100) + 1; var diceTwo = Math.floor(Math.random() * 100) + 1; var diceThree = Math.floor(Math.random() * 100) + 1; function report() { alert("You have " + charHP + " remaining and the dragon has " + mobHP + " remaining."); } function attack() { function report() { alert("You have " + charHP + " remaining and the dragon has " + mobHP + " remaining."); } var attackType = prompt(userAttack); function evaluateAttack() { if (attackType.toLowerCase() === "sword") { mobHP = mobHP - diceOne - diceTwo - diceThree; alert("You slash at the dragon three times drawing blood!"); } else if (attackType.toLowerCase() === "charge") { mobHP = mobHP - (3 * diceOne); alert("You charge the dragon at full speed drawing blood!"); } else if (attackType.toLowerCase() === "spell") { mobHP = mobHP - (4 * diceTwo); alert("You close your eyes and summon the fires of hell on the dragon"); } } if (mobHP > 0) { report(); evaluateAttack(); } else { alert("The dragon is dead! You have won!"); } } do { attack(); } while (mobHP > 0); ```
- pattern minor 112d agoJavaScript calculator with two inputs and four operationsi build a calc & want to a review that what i did wrong & what is right method to do. ` var inputIdFirst = "valueOfX",inputIdSecond = "valueOfY",outputId = "resultHere"; var getInputs = function(id) { return parseInt(document.getElementById(id).value); } var showOutput = function(outputValue, outputIdAsArg) { //if no argument is given then by default "outputId" taken document.getElementById(outputId).innerHTML = outputValue; } var manuplateAs = function(operationName, valueOfX, valueOfY) { if(operationName == 'add') return valueOfX + valueOfY; else if(operationName == 'sub') return valueOfX - valueOfY; else if(operationName == 'mul') return valueOfX * valueOfY; else if(operationName == 'div') return valueOfX / valueOfY; //can add as many as you wish } var operation = function(operationName){ x = getInputs(inputIdFirst); y = getInputs(inputIdSecond); output = manuplateAs(operationName, x, y); showOutput(output); console.log(x + " " + operationName + " " + y + " = " + output) //see console to understand this more console.log(this) }; Enter first number Enter second number Add Sub Mult Divi `
- pattern minor 112d agoFunction to find the shortest word in an array, where not every element is a stringI wrote a solution for a codeCamp exercise: Write a function called `findShortestWordAmongMixedElements`. Given an array, `findShortestWordAmongMixedElements` returns the shortest string within the given array. Notes: - If there are ties, it should return the first element to appear in the given array. - Expect the given array to have values other than strings. - If the given array is empty, it should return an empty string. - If the given array contains no strings, it should return an empty string. Right now I essentially break this function into two parts. The filtering method—to just get the strings—and then `reduce` to find the shortest one among them. ``` function findShortestWordAmongMixedElements(arr) { var containsStrings = function(arr){ return arr.every(function(cv){ return Object.prototype.toString.call(cv) !== '[object String]'; }); }, shortestWord; if ((!(arr.length)) || ((containsStrings(arr)))) return ''; arr = arr.filter(function(e, i, a){ if (typeof e == 'string') { return e; } }); shortestWord = arr.reduce(function(prev, next) { if (prev.length < next.length) { return prev; } else if (prev.length === next.length){ return prev; } else { return next; } }); return shortestWord; } ``` My take is this is certainly readable which I like and I LOVE the helper function I made for the initial check which uses the `every` method. Since (at first) I spent a lot of time trying to do all the operations within the body of the callback for the filter—I feel this take is like I used flat head screw driver for every screw instead of a phillips...
- pattern minor 112d agoJavascript FizzBuzz and Behavior-Driven Development Using Mocha and ChaiI am currently getting closely acquainted with Behavior-Driven Development. Could someone tell me how I am doing with the Fizzbuzz program below? I am interested in both improving the JavaScript code and the BDD prowess. Any help is appreciated. fizzbuzz.js ``` module.exports = function(word, value){ function sortNumber(a,b) { return a - b; } numbers = function(divisor, max){ var result = [] for(i=1;i<=max;i++){ if ((i % divisor) === 0) result.push(i) } return result } if (value <= 0) return ['error','nonpositive'] else { switch(word) { case 'fizz': return numbers(3, value) case 'buzz': return numbers(5,value) case 'fizzbuzz': return numbers(3,value).concat(numbers(5,value)).filter(function(elem,index,self){ return index == self.indexOf(elem) }).sort(sortNumber) default: return ['error','wrongword'] } } }; ``` test/fizzbuzz-spec.js: ``` var chai = require('chai'); expect = chai.expect, fizzbuzz = require('../lib/fizzbuzz'); describe('A fizzbuzz', function(){ describe('will return an error for invalid words: ', function(){ it('like fuss', function(){ expect(fizzbuzz('fuss', 10)).to.be.deep.equal(['error','wrongword']); }); it('like biss', function(){ expect(fizzbuzz('biss', 10)).to.be.deep.equal(['error','wrongword']); }); }); describe('will return an error when non-positive integer is passed', function(){ it('like 0', function(){ expect(fizzbuzz('buzz', 0)).to.be.deep.equal(['error','nonpositive']); }) it('like -2', function(){ expect(fizzbuzz('buzz', -2)).to.be.deep.equal(['error','nonpositive']); }) }) describe('wil
- pattern major 112d agoPartitioning an array based on a condition in JavascriptUsing the array.filter function, I can efficiently pull out all elements that do or do not meet a condition: ``` let large = [12, 5, 8, 130, 44].filter((x) => x > 10); let small = [12, 5, 8, 130, 44].filter((x) => !(x > 10)); ``` However, in the example above, I'm iterating over the array twice and performing the same test each time. Is there a simple way to generate both 'large' and 'small' in a single pass over the array? In particular, if the callback to evaluate whether an element should be kept is expensive, I'd like to avoid calling it twice.
- pattern minor 112d agoCalculate the sum at a level of a binary tree represented in a StringFair preface: This is an interview question I would like to improve my knowledge of. I got some rest, and re-solved the problem with a fresh/unpanicked mind. Given input of the type `(10(5(3)(12))(14(11)(17)))` which would represent the following tree ``` n=0 10 n=1 5 14 n=2 3 12 11 17 ``` My task is to find the summation of values at a particular tier, like \$5+14=19\$ which is the sum for \$n=1\$, or \$3+12+11+17=43\$ the sum for \$n=2\$. Considering this is a binary tree, a recursive function seems appropriate. My main utility functions are: - `stripFirstLastParen` – strips the first and last paren - `getCurrentVal` – retrieves the value of the current node - `getChildren` – retrieves the left and right nodes `var input = "(10(5(3)(12))(14(11)(17)))"; function stripFirstLastParen(input){ if(input[0] !== "(" || input[input.length - 1] !== ")"){ console.error("unbalanced parens") } else{ input = input.substr(1); input = input.substring(0, input.length - 1); } return input; } function getCurrentVal(input){ var val = ""; while(input[0] !== "(" && input[0] !== ")" && input.length){ val += input[0]; input = input.substr(1); } return { val, input } } function getChildren(input){ var val = ""; if(input.length == 0){ return { left: "", right: "" } } if(input[0] !== "("){ console.error("no open paren at start"); } val += input[0]; input = input.substr(1); var parenStack = 1; while(parenStack > 0){ if(input[0] == ")"){ parenStack--; } else if(input[0] == "("){ parenStack++; } val += input[0]; input = input.substr(1); } return { left: val, right: input } } function getValueForLevel(input, k){ var totalValue = 0; input = stripFirstLastParen(input); var currentValue = getCurrentVal(input); var children = getChildren(currentValue.input); if(k > 0){ if(children.left.leng
- pattern minor 112d agoA simple MP3 player with React.jsI've been learning React.js for the last few days and am working on a simple MP3 player. I have a few years experience with JavaScript, however, I am just trying to get used to the idea of components in React.js. I would also like to be following best practices as I may use the application/code as a portfolio piece. What I have made is working correctly. However, I was wondering if you can look through my code and see if I could do anything better/more efficiently. Also, I have the following specific questions: - In the `MusicPlayer` component I have an array of objects with information on different sounds. I am aware I have this "sounds" array set up as a "state" and I was wondering is there another way to incorporate this array perhaps as a property (seeing as it won't be changing state throughout the application). Or do you think it is ok, the way I have done it? - As you can see towards the end of the code I have this: ``` ReactDOM.render( , document.getElementById('app') ); ``` I was wondering is there a way to detect the HTML has finished being "rendered" so that I can use JavaScript `document.getElementById` on one of the elements. At the moment I am using `window.onload` for this. Full code: ``` var Sound = React.createClass({ //make a component for individual sounds //these will be html list items getInitialState: function () { return {isSelected: false} }, render: function () { return ( {this.props.soundTitle} {this.props.soundLength} ); } }); var MusicPlayer = React.createClass({ //this will be our main component i.e a parent to the Sound component and also the Controls component (defined below) getInitialState: function () { //return an object with an array of all of our sounds. The sounds array itself will not change state. //also retu
- pattern minor 112d agoTip Calculator in javascriptUpdate: revised code. I work at a Starbucks and one of the things that screams at me week after week for automation is the tedious calculation of the tip distribution. So here is my attempt to provide a simple tool for this. (Previous attempt required special software and special instruction to explain how it works.) It has fields for inputting the number of hours for each partner and the amount of money to be dispersed. Clicking "calculate" produces the output with blank lines to help orient the output with the input rows. As a javascript noob, I feel certain I've done some stupids in here I can learn from. ` Tip Calculator Tip Calculator Hours: Dividend: `
- pattern minor 112d agoCheck existence of matching key,value pairI recently was in an interview where I was asked to implement a snippet that finds the matching key:value pair among two JavaScript arrays in which each member is an object: ``` var a = [{color:'blue'},{color:'green'}, {color:'brown'}, {color:'black'}] var b = [{color:'white'},{color:'yellow'}, {color:'black'}, {color:'blue'}] var expectedOutput = [{color:'blue'}, {color:'black'}] ``` Here's my implementation: `var a = [{color:'blue'},{color:'green'}, {color:'brown'}, {color:'black'}] var b = [{color:'white'},{color:'yellow'}, {color:'black'}, {color:'blue'}] var expectedOutput = []; for(var i=0; i In the interview, I communicated that using `.hasOwnProperty()` provides \$O(1)\$ lookup for keys (but not for values) from array `b`, and unfortunately, I wasn't able to fully implement this as my mind wandered across other possibilities there might be, not to mention the pressure. I believe this still has \$O(n^2)\$ complexity as it simply checks the existence of child `.color` key as well as a supplementary check against values being equivalent. All in all, I suspect the interviewer was pointing me into this implementation for \$O(n)\$ complexity. Do you think otherwise? If you do, could you kindly explain why and how? If my question is unclear, how would you solve it in \$O(n)\$ time in JavaScript?
- snippet minor 112d agoJavaScript filter() on JSON object?I'm building a web interface for a home monitoring sensor array, and fetching JSON from the backend framework. I want to start putting statistics together for monitoring different areas of the home, inside and outside. Each thermal sensor provide the reading, in regular intervals, of temperature and time of day, so I end up with a JSON object looking like this: ``` { "sensor_1" : [ { "location" : "garage_east", "temp_f" : [{ "value" : "71.2", "timestamp" : "2017-05-01T08:15:00" }, { "value" : "70.8", "timestamp" : "2017-05-01T08:30:00" }, { "value" : "72.6", "timestamp" : "2017-05-01T08:45:00" } ]}], "sensor_2" : [{ "location" : "kitchen", "temp_f" : [{ "value" : "78.2", "timestamp" : "2017-05-01T08:15:00" }, { "value" : "78.8", "timestamp" : "2017-05-01T08:30:00" }, { "value" : "78.6", "timestamp" : "2017-05-01T08:45:00" }] }]} ``` and so on, with multiple sensors each displaying pretty large JSON objects for the reporting periods. I want to derive the highest and lowest temperatures around the house, and at what time they occurred, using JavaScript (with AngularJS). Currently, I'm looking to optimize this (which does work): ``` /* The entire array of data, within time frame set by the user * and for the sensors defined by the user * from the RESTful API (params) */ api.sensor_data.get(params, function(data){ $scope.sensorStats = { "kitchen" : {}, "garage" : {} } /* find the highest temperature for a single sensor */ let hightemp_kitchen = Math.max.apply(Math, data.sensor_1.temp_f.map(function(t){ retu