Loading...
More JavaScript Posts
function Clock(props) {return (<div><h1>Hello, world!</h1><h2>It is {props.date.toLocaleTimeString()}.</h2></div>);}function tick() {ReactDOM.render(<Clock date={new Date()} />,document.getElementById('root'));}setInterval(tick, 1000);
const quickSort = arr => {const a = [...arr];if (a.length < 2) return a;const pivotIndex = Math.floor(arr.length / 2);const pivot = a[pivotIndex];const [lo, hi] = a.reduce((acc, val, i) => {if (val < pivot || (val === pivot && i != pivotIndex)) {acc[0].push(val);} else if (val > pivot) {acc[1].push(val);}return acc;},[[], []]);return [...quickSort(lo), pivot, ...quickSort(hi)];};quickSort([1, 6, 1, 5, 3, 2, 1, 4]); // [1, 1, 1, 2, 3, 4, 5, 6]
const union = (...arr) => [...new Set(arr.flat())];// Exampleunion([1, 2], [2, 3], [3]); // [1, 2, 3]
class LinkedList {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 };if (previousNode) previousNode.next = 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];const nextNode = this.nodes[index + 1] || null;if (previousNode) previousNode.next = nextNode;return this.nodes.splice(index, 1);}clear() {this.nodes = [];}reverse() {this.nodes = this.nodes.reduce((acc, { value }) => [{ value, next: acc[0] || null }, ...acc],[]);}*[Symbol.iterator]() {yield* this.nodes;}}const list = new LinkedList();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; // 4[...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
let nums = [1,2,3,1]var containsDuplicate = function(nums) {let obj = {};for(let i =0; i< nums.length; i++){if(obj[nums[i]]){obj[nums[i]] += 1;return true;}else{obj[nums[i]] = 1;}}return false;};console.log(containsDuplicate(nums));
// Orconst randomColor = () => `#${(~~(Math.random()*(1<<24))).toString(16)}`;console.log(randomColor);