Monday, October 12, 2020

Javascript: for-of loops

for...of iterates arrays, array-like objects, and generally any iterable (maps, sets, DOM collections). You can destructure the iterated item in place. On top of that, for...of has a short syntax.

const fruits = ['oranges', 'apples'];

for (const fruit of fruits) {  
   console.log(fruit);
}

// 'oranges'
// 'apples'

Note that in for-of loops you can use const. Think of it as a new const declaration being executed each time in a fresh scope.

The array method entries() can be used to access the index of the iterated item. The method returns at each iteration a pair of [index, item].

const arr = ['oranges', 'apples'];

for (const [index, elem] of arr.entries()) {
  console.log(`${index} -> ${elem}`);
}

// 0 -> oranges
// 1 -> apples

At each iteration arr.entries() returns a pair of index and value, which is destructured by const [index, elem] expression.

Iterating over an array of objects

Example 1:

const person = {
  name: 'John Smith',
  job: 'agent'
};

for (const [prop, value] of Object.entries(person)) {
  console.log(prop, value);
}

// 'name', 'John Smith'
// 'job', 'agent'

where Object.entries(person) returns an array of key and value tuples.

Example 2:

const persons = [
  { name: 'John Smith' },
  { name: 'Jane Doe' }
];

for (const { name } of persons) {  
   console.log(name);
}

// 'John Smith'
// 'Jane Doe'

The cycle for (const { name } of persons) iterates the objects of persons array, but also destructures the person object in place { name }.

Maps and Sets iteration

const names = new Map();
names.set(1, 'one');
names.set(2, 'two');

for (const [number, name] of names) {  
   console.log(number, name);
}


const colors = new Set(['white', 'blue', 'red', 'white']);

for (color of colors) {
   console.log(color);
}

String characters iteration

const message = 'hello';

for (const character of message) {  
   console.log(character);
}

// 'h'
// 'e'
// 'l'
// 'l'
// 'o'
Share This:    Facebook Twitter

Saturday, October 10, 2020

Javascript: In-Place Out-Of-Place Algorithms

In an in-place function, the changes made by the function remain after the call completes. In-place algorithms are sometimes called destructive, since the original input is modified during the function call.

"In-place" does not mean "without creating any additional variables!" Rather, it means "without creating a new copy of the input." In general, an in-place function will only create additional variables that are O(1) space.

An out-of-place function doesn't make any changes that are visible to other functions. Usually, those functions copy any data structures or objects before manipulating and changing them.

Here are two functions that do the same operation on an array, except one is in-place and the other is out-of-place:

function squareArrayInPlace(intArray) {

  intArray.forEach((int, index) => {
    intArray[index] *= int;
  });

  // NOTE: no need to return anything - we modified intArray in place
}


function squareArrayOutOfPlace(intArray) {

  // We allocate a new array that we'll fill in with the new values
  const squaredArray = [];

  intArray.forEach((int, index) => {
    squaredArray[index] = Math.pow(int, 2);
  });

  return squaredArray;
}

Working in-place is a good way to save time and space. An in-place algorithm avoids the cost of initializing or copying data structures, and it usually has an O(1) space cost.

But be careful: an in-place algorithm can cause side effects. Your input is altered, which can affect code outside of your function.

Generally, out-of-place algorithms are considered safer because they avoid side effects. You should only use an in-place algorithm if you're space constrained or you're positive you don't need the original input anymore, even for debugging.

Share This:    Facebook Twitter

Total Pageviews

My Social Profiles

View Sonal's profile on LinkedIn

Tags

__proto__ $Browser Access Grants Accessor properties Admin Ajax AllowsCallouts Apex Apex Map Apex Sharing AssignmentRuleHeader AsyncApexJob Asynchronous Auth Provider AWS Callbacks Connected app constructor Cookie CPU Time CSP Trusted Sites CSS Custom settings CustomLabels Data properties Database.Batchable Database.BatchableContext Database.query Describe Result Destructuring Dynamic Apex Dynamic SOQL Einstein Analytics enqueueJob Enterprise Territory Management Enumeration escapeSingleQuotes featured Flows geolocation getGlobalDescribe getOrgDefaults() getPicklistValues getRecordTypeId() getRecordTypeInfosByName() getURLParameters Google Maps Governor Limits hasOwnProperty() Heap Heap Size IIFE Immediately Invoked Function Expression Interview questions isCustom() Javascript Javascript Array jsForce Lightning Lightning Components Lightning Events lightning-record-edit-form lightning:combobox lightning:icon lightning:input lightning:select LockerService Lookup LWC Manual Sharing Map Modal Module Pattern Named Credentials NodeJS OAuth Object.freeze() Object.keys() Object.preventExtensions() Object.seal() Organization Wide Defaults Override PDF Reader Performance performance.now() Permission Sets Picklist Platform events Popup Postman Primitive Types Profiles Promise propertyIsEnumerable() prototype Query Selectivity Queueable Record types Reference Types Regex Regular Expressions Relationships Rest API Rest Operator Revealing Module Pattern Role Hierarchy Salesforce Salesforce Security Schema.DescribeFieldResult Schema.DescribeSObjectResult Schema.PicklistEntry Schema.SObjectField Schema.SObjectType Security Service Components Shadow DOM Sharing Sharing Rules Singleton Slots SOAP API SOAP Web Services SOQL SOQL injection Spread Operator Star Rating stripInaccessible svg svgIcon Synchronous this Token Triggers uiObjectInfoApi Upload Files VSCode Web Services XHR
Scroll To Top