A JavaScript cheat sheet

1. slice() The splice() method adds/removes items to/from an array, and returns the removed item(s). [code language="js"] const words: string[] = ['abc', 'xyz', '123', 'the', 'cat', 'sat', 'on', 'the', 'mat']; const splicedWords = words.splice(3); console.log('Spliced array: ' + splicedWords); console.log('Original array: ' + words); [/code] Output: [code language="text"] Spliced array: the,cat,sat,on,the,mat Original array: abc,xyz,123 [/code] Note that on using splice() the original array is impacted. The contents of the original array can be modified by adding or removing elements too, such as in the following example. Remove the word 'the' from the selected index index in the list and insert the words ['this', 'other'] instead: [code language="js"] const words: string[] = ['the', 'cat', 'sat', 'on', 'the', 'mat']; words.splice(4, 1, 'this', 'other'); console.log('Words: ' + words); [/code] Output: [code language="text"] Words: the,cat,sat,on,this,other,mat [/code] 2. map() Think of map() as a kind of for loop for transforming values. Some examples of map() can also be found here. In this example we use map() to create an array of word lengths: [code language="js"] const materials : string[] = [ 'Hydrogen', 'Helium', 'Lithium', 'Beryllium' ]; const wordLengths : number[] = materials.map(material => material.length); console.log('Word lengths: ' + wordLengths); [/code] Output: [code language="text"] Word lengths: 8,6,7,9 [/code] You can use map() to transform values in order to return an array of object literals, such as in this example to return a set of objects containing squares and doubles: [code language="js"] const squaresDoubles = [1, 2, 3, 4, 5].map(val => ({ square: val * val, double: val * 2})); console.log(squaresDoubles); [/code] Output: [code language="text"] 0: {square: 1, double: 2} 1: {square: 4, double: 4} 2: {square: 9, double: 6} 3: {square: 16, double: 8} 4: {square: 25, double: 10} [/code] Another example of using map() to return an array of object literals containing upper and lower case renditions of words: [code language="js"] var texts = ["aBc", "Xyz"]; var result: { lowercase: string; uppercase: string }[] = texts.map( text => ({ lowercase: text.toLowerCase(), uppercase: text.toUpperCase() }) ); console.log(result); [/code] Output: [code language="text"] 0: lowercase: "abc" uppercase: "ABC" 1: lowercase: "xyz" uppercase: "XYZ" [/code] 3. Correct way of cloning arrays Use = [...myArray] Arrays in JavaScript are reference values, so when you try to copy it using a simple assignment ('=') it copies the reference to the original array and not the value of the array. To create a real copy of an array, copy over the value of the array under a new value variable. That way this new array does not reference to the old array address in memory. [code language="js"] const array: string[] = ["1", "2", "3", "4"]; const clone1 = array; console.log(clone1); console.log(clone1 === array); const clone2 = [...array]; console.log(clone2); console.log(clone2 === array); [/code] 4. Using object literals Using object literals in place of switch statements. Object literals are a great way of replacing switch statements with code looks a lot cleaner and more concise. A function containing a switch statement to determine a particular outcome might look as follows: [code language="js"] private getChosenValueText(value: string) { let returnText: string = ""; switch (value) { case "apples": { returnText = "apples chosen"; break; } case "oranges": { returnText = "oranges chosen"; break; } case "pears": { returnText = "pears chosen"; break; } } return returnText; } console.log(this.getChosenValueText("apples")); [/code] Output: [code language="text"] apples chosen [/code] Replaced with the more concise object literal: [code language="js"] private getChosenValueTextObjectLiteral(value: string) { return { apples: "apples chosen", oranges: "oranges chosen", pears: "pears chosen" }[value]; } console.log(this.getChosenValueTextObjectLiteral("apples")); [/code] Output: [code language="text"] apples chosen [/code] GREAT piece of code to convert an array into a map object: https://medium.com/dailyjs/rewriting-javascript-converting-an-array-of-objects-to-an-object-ec579cafbfc7 [code language="js"] const arrayToObject = (arr: Tab[], keyField: string) => Object.assign({}, ...arr.map(item => ({ [item[keyField]]: item }))); console.log(arrayToObject(tabs, "name")); [/code] Where Tab is a class containing fields "name", "other", "offsetWidth" Output: [code language="text"] {one: Tab, two: Tab, three: Tab} one: Tab {offsetWidth: 1, name: "one", other: "one2"} three: Tab {offsetWidth: 111, name: "three", other: "three2"} two: Tab {offsetWidth: 11, name: "two", other: "two2"} [/code] Iterating over object literals - stack overflow link. [code language="js"] var obj = { 'foo': 1, 'bar': 2 }; for (var key in obj) { console.log(obj[key]); } [/code] Output: [code language="text"] 1 2 [/code] 5. Using callbacks A simple example to execute a function that takes a message string and a callback function as arguments. The callback function itself can also take arguments using the bind methods: [code language="js"] private doStuff(message: string, callback: (args?: any) => void): void { alert(message); callback(); } private alertFinished(message: string): void { alert(message); } execute(length: number): void { this.doStuff( "Doing stuff...", this.alertFinished.bind(this, "Finished doing stuff") ); } [/code] Output: [code language="text"] Doing stuff... Finished doing stuff. [/code] You can initialise a callback and call it at any time: [code language="js"] callback: (args?: any) => void = () => { console.log("Hello"); }; ... someFunction() : void { callback(); } [/code] And also the same example but with a string argument passed to it: [code language="js"] callback: (args?: any) => void = val => { console.log(val as string); }; ... someFunction() : void { callback('hello'); } [/code] Another example of passing a callback as a function parameter. This time as a parameter passed to the some() function for determining if an item in a list satifies a logical condition. [code language="js"] const callbackGreaterThanValue : (item: number, value : number) => boolean = (item, value) => { return item > value; } const items : number[] = [1, 2, 3, 4, 5, 6, 7, 8, 9]; console.log(items.some(item => callbackGreaterThanValue(item, 2)) ? 'Yes' : 'No'); console.log(items.some(item => callbackGreaterThanValue(item, 200)) ? 'Yes' : 'No'); [/code] Output: [code language="text"] Yes No [/code] 6. Template literals (previously Template strings) Template literals are string literals allowing embedded expressions Example: [code language="js"] const flag: boolean = true; console.log(`${flag ? "ON" : "OFF"}`); [/code] Output: [code language="text"] ON [/code] 7. Using reduce() Executes a reducer function that you provide on each array element, resulting in a single output value. Two different approaches, either using a private function or directly. Both give the same output. [code language="js"] private getSum(total: number, num: number) { return total + num; } var numbers = [15.5, 2.3, 1.1, 4.7]; const total1 = numbers.reduce(this.getSum, 0); // total - defaults to zero, num is each value in the array const total2 = numbers.reduce((total, num) => total + num); console.log(total1); console.log(total2); [/code] Output: [code language="text"] 23.6 23.6 [/code] To find the total of a property within an object array: [code language="js"] const tabs: Tab[] = [new Tab(1), new Tab(11), new Tab(111)]; const totalWidths: number = tabs.reduce( (total, tab) => total + tab.offsetWidth, 0 ); console.log(totalWidths); [/code] Output: [code language="text"] 123 [/code] 8. Using replace() Pass it an argument representing the string to be replaced, or a regular expression. Simple replace - replaces 1st occurrence only [code language="js"] console.log("123,321,456,789,456,432".replace(/,/, " ")); [/code] Output: [code language="text"] 123 321,456,789,456,432 [/code] Global replace - all occurrences [code language="js"] console.log("123,321,456,789,456,432".replace(/,/g, " ")); [/code] Output: [code language="text"] 123 321 456 789 456 432 [/code] Global replace - all occurrences, including repeated occurrences [code language="js"] console.log("123,,321,456,789,,,,,456,432".replace(/,+/g, " ")); [/code] Output: [code language="text"] 123 321 456 789 456 432 [/code] Global replace - all words ending with (case insensitive) "at" including whitespaces after it, if any, with an empty string, [code language="js"] const replace: string = "the cAt Sat on the mat".replace( /[A-Za-z]at[ ]{0,1}/gi, "" ); console.log(replace); [/code] Output: [code language="text"] the on the [/code] 9. Using split() Splits a string into an array of sub-strings using the delimiting string passed to it. [code language="js"] const texts: string[] = "123 345 222 47 999".split(" "); console.log(texts); [/code] Output: [code language="text"] 0: "123" 1: "345" 2: "222" 3: "47" 4: "999" [/code] 10. Using repeat() Builds a new string according to the specified number of copies of the string on which this function has been called. [code language="js"] const text: string = "abracadabra".repeat(2); console.log(text); [/code] Output: [code language="text"] abracadabraabracadabra [/code] 11. Using join() Joins the elements of an array into a single string. An optional separator string can be used, which if omitted, separates the elements with comma. [code language="js"] const texts: string[] = ["1", "11", "111", "1111", "11111"]; const text: string = texts.join(); console.log(text); [/code] Output: [code language="text"] 1,11,111,1111,11111 [/code] 12. Using filter() To check if array contains object with specific attribute value: Hat-tip: https://stackoverflow.com/questions/8217419/how-to-determine-if-javascript-array-contains-an-object-with-an-attribute-that-e [code language="js"] const vendors = [ { Name: 'Jeff', ID: 'ABC' }, { Name: 'Peter', ID: 'DEF' } //and so on goes array... ]; [/code] Just use the filter function to obtain those elements matching the attribute value: [code language="js"] vendors.filter(vendor => vendor.Name === "Jeff"); [/code] To obtain objects whose 'name' property exists in a given string array. Use the filter function to obtain those elements whose 'name' property is included in the 'maleSet' string array. [code language="js"] const maleSet : string[] = ['bill', 'john', 'dave']; const totalSet : { id: string, name: string }[] = [{id: '1', name: 'xyz'}, {id : '2', name: 'julie'}, {id: '3', name: 'meghan'}, {id : '4', name: 'bill'}, {id: '5', name: 'john'}, {id:'6', name: 'dave'}]; const filteredSet : any = totalSet.filter(item => maleSet.includes(item.name)); console.log(filteredSet) [/code] Output: [code language="text"] [LOG]: [{ "id": "4", "name": "bill" }, { "id": "5", "name": "john" }, { "id": "6", "name": "dave" }] [/code] 13. Using some() to test whether at least one element in the array satisfies a boolean condition In this example we use some() to return if any of the value in the array of numbers is greater than a given value: [code language="js"] const items : number[] = [1, 2, 3, 4, 5, 6, 7, 8, 9]; const hasItems : boolean = hasItemsGreaterThanValue(items, 200); console.log(hasItems ? 'Yes' : 'No'); function hasItemsGreaterThanValue(items : number[], value: number) : boolean { return items.some(item => item > value); } [/code] Output: [code language="text"] 'No' [/code]

Comments

Popular posts from this blog

Using the Supervisor Controller Pattern to access View controls in MVVM

Getting started with client-server applications in C++

How to send an e-mail via Google SMTP using C#