Loading...
More JavaScript Posts
class DoublyLinkedList {constructor() {this.nodes = [];}get size() {return this.nodes.length;}get head() {return this.size ? this.nodes[0] : null;}get tail() {return this.size ? this.nodes[this.size - 1] : null;}insertAt(index, value) {const previousNode = this.nodes[index - 1] || null;const nextNode = this.nodes[index] || null;const node = { value, next: nextNode, previous: previousNode };if (previousNode) previousNode.next = node;if (nextNode) nextNode.previous = node;this.nodes.splice(index, 0, node);}insertFirst(value) {this.insertAt(0, value);}insertLast(value) {this.insertAt(this.size, value);}getAt(index) {return this.nodes[index];}removeAt(index) {const previousNode = this.nodes[index - 1] || null;const nextNode = this.nodes[index + 1] || null;if (previousNode) previousNode.next = nextNode;if (nextNode) nextNode.previous = previousNode;return this.nodes.splice(index, 1);}clear() {this.nodes = [];}reverse() {this.nodes = this.nodes.reduce((acc, { value }) => {const nextNode = acc[0] || null;const node = { value, next: nextNode, previous: null };if (nextNode) nextNode.previous = node;return [node, ...acc];}, []);}*[Symbol.iterator]() {yield* this.nodes;}}const list = new DoublyLinkedList();list.insertFirst(1);list.insertFirst(2);list.insertFirst(3);list.insertLast(4);list.insertAt(3, 5);list.size; // 5list.head.value; // 3list.head.next.value; // 2list.tail.value; // 4list.tail.previous.value; // 5[...list.map(e => e.value)]; // [3, 2, 1, 5, 4]list.removeAt(1); // 2list.getAt(1).value; // 1list.head.next.value; // 1[...list.map(e => e.value)]; // [3, 1, 5, 4]list.reverse();[...list.map(e => e.value)]; // [4, 5, 1, 3]list.clear();list.size; // 0
function sortNumbers(arr) {return arr.slice().sort((a, b) => a - b);}const unsortedArray = [4, 1, 9, 6, 3, 5];const sortedArray = sortNumbers(unsortedArray);console.log("Unsorted Numbers:", unsortedArray);console.log("\n");console.log("Sorted Numbers:", sortedArray);
const getURLParameters = url =>(url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce((a, v) => ((a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a),{});
//JavaScript program to swap two variables//take input from the userslet a = prompt('Enter the first variable: ');let b = prompt('Enter the second variable: ');//using destructuring assignment[a, b] = [b, a];console.log(`The value of a after swapping: ${a}`);console.log(`The value of b after swapping: ${b}`);
/*** @param {number[]} nums* @return {number[]}*/var productExceptSelf = function(nums) {var output = [];var leftMult = 1;var rightMult = 1;for (var i=nums.length - 1; i >= 0; i--) {output[i] = rightMult;rightMult *= nums[i];console.log({output: JSON.stringify(output), i})}for (var j=0; j < nums.length; j++) {output[j] *= leftMult;leftMult *= nums[j];console.log({output: JSON.stringify(output), j})}return output;};console.log(productExceptSelf([1, 2, 3, 4]))
new StringBuilder(hi).reverse().toString()