# 48 pieces of JavaScript code carefully collected, in just 30 seconds to understand

Source: Internet
Author: User

Original: Chalarangelo: IT168

Https://github.com/Chalarangelo/30-seconds-of-code#anagrams-of-string-with-duplicates

The project, which comes from GitHub user Chalarangelo, now has more than 5,000 star on GitHub and has carefully collected up to 48 useful JavaScript snippets, and the user's code allows programmers to understand these often in 30 seconds or less Use the underlying algorithm to see what these JavaScript code conveys!

Anagrams of string (with duplicates)

Use recursion. For each letter in a given string, create a crossword puzzle for the letter. Use map () to combine the letters with each part of the puzzle, and then use reduce () to combine all the crossword puzzles into an array, the most basic being the length of the string equals 2 or 1.

Const ANAGRAMS = str = = {

if (str.length <= 2) return str.length = = 2? [STR, str[1] + str[0]]: [STR];

Return Str.split ("). Reduce ((ACC, letter, i) = =

Acc.concat (anagrams (str.slice (0, I) + str.slice (i + 1)). Map (val = letter + val)), []);

};

Anagrams (' abc ')--[' ABC ', ' ACB ', ' bac ', ' BCA ', ' cab ', ' CBA ']

Array average

Use reduce () to add each value to the accumulator with an initial value of 0 and the sum divided by the array length.

Const AVERAGE = arr = Arr.reduce ((ACC, val) = = acc + val, 0)/arr.length;

Average ([2])

Capitalize the first letter of each word

Use replace () to match the first character of each word, and use toUpperCase () to capitalize it.

Const Capitalizeeveryword = str = = Str.replace (/\b[a-z]/g, char = Char.touppercase ());

Capitalizeeveryword (' Hello world! '), ' Hello world! '

Capitalize first letter

Use Slice (0,1) and touppercase () to capitalize the first letter, slice (1) to get the remainder of the string. Omit the lowerrest parameter to keep the rest of the string intact, or set it to true to convert to lowercase. (Note: This is not the same thing as the previous example)

Const CAPITALIZE = (str, lowerrest = false) = =

Str.slice (0, 1). toUpperCase () + (lowerrest? Str.slice (1). toLowerCase (): Str.slice (1));

Capitalize (' MyName ', true), ' MyName '

Check palindrome

Converts a string to toLowerCase () and uses replace () to remove non-alphabetic characters from it. It then converts it to toLowerCase (), Splits (") into individual characters, reverse (), Joins ("), compares it to the original non-inverted string, and converts it to toLowerCase ().

Const Palindrome = str = = {

Const S = str.tolowercase (). Replace (/[\w_]/g, ");

return s = = = S.split ("). Reverse (). Join (');

}

Palindrome (' Taco cat '), true

Count occurrences of values in an array

Use reduce () to increment the counter each time a specific value in the array is encountered.

Const Countoccurrences = (arr, value) = Arr.reduce ((A, v) = = = = = value, a + 1:a + 0, 0);

Countoccurrences ([1,1,2,1,2,3], 1), 3

Current URL

Use Window.location.href to get the current URL.

Const Currenturl = _ = = Window.location.href;

Curry

Use recursion. If the supplied parameter (args) is sufficient, the transfer function f is called, otherwise a curried function f is returned.

Const CURRY = (FN, arity = fn.length, ... args) = =

arity <= Args.length

? fn (.... args)

: Curry.bind (NULL, FN, arity, ... args);

Curry (Math.pow) (2) (1024)

Curry (Math.min, 3) (2) (2)

Deep Flatten Array

Using recursion, reduce () is used to get all elements that are not arrays, flatten each element is an array.

Const Deepflatten = arr =

Arr.reduce ((A, V) = A.concat (Array.isarray (v), Deepflatten (v): v), []);

Deepflatten ([1,[2],[[3],4],5]), [1,2,3,4,5]

The difference between arrays

Create a set from B, and then use Array.filter () on a to keep only the values not contained in B.

Const DIFFERENCE = (A, b) = = {Const S = new Set (b); return a.filter (x =!s.has (x));};

Difference ([3], [[+]])

Distance between two points

Use Math.hypot () to calculate Euclidean distance between two points.

Const DISTANCE = (x0, y0, x1, y1) = Math.hypot (x1-x0, y1-y0);

Distance (2,3), 2.23606797749979

Can be divisible by number

Use the modulo operator (%) to check if the remainder equals 0.

Const ISDIVISIBLE = (dividend, divisor) = dividend% divisor = = 0;

Isdivisible (6,3)-True

Escaping regular expressions

Use replace () to escape special characters.

Const ESCAPEREGEXP = str = = Str.replace (/[.*+?^\${} () |[ \]\\]/g, ' \\\$& ');

Escaperegexp (' (test) '), \ \ (test\\)

Even or odd

Use Math.Abs () to extend the logic to negative numbers and check using the modulo (%) operator. Returns true if the number is even, or false if the number is odd.

Const ISEVEN = num = num% 2 = = = 0;

IsEven (3), False

Factorial

Use recursion. If n is less than or equal to 1, 1 is returned. Otherwise, the product of the factorial of N and N-1 is returned.

const FACTORIAL = n + = n <= 1? 1:n * factorial (n-1);

Factorial (6)-720

Fibonacci Array Generator

Creates an empty array of a specific length, initializing the first two values (0 and 1). Use Array.reduce () to add a value to the array, followed by a number equal to the preceding two digits plus (except for the first two).

Const FIBONACCI = n =

Array (n). Fill (0). Reduce ((ACC, val, i) = Acc.concat (i > 1 acc[i-1] + acc[i-2]: i), []);

Fibonacci (5), [0,1,1,2,3]

Filter non-unique values in an array

Use Array.filter () for arrays that contain only unique values.

Const Filternonunique = arr = Arr.filter (i = arr.indexof (i) = = = Arr.lastindexof (i));

Filternonunique ([1,2,2,3,4,4,5]), [1,3,5]

Flatten array

Use reduce () to get all the elements in the array and use CONCAT () to make them flatten.

Const FLATTEN = arr = Arr.reduce ((A, V) = A.concat (v), []);

Flatten ([1,[2],3,4]), [1,2,3,4]

Get the maximum value from the array

Use Math.max () with the spread operator (...). ) together to get the maximum value in the array.

Const ARRAYMAX = arr. Math.max (... arr.);

ArrayMax ([1, 5]), 10

Get the minimum value from the array

Use Math.min () with the spread operator (...). ) to combine to get the minimum value in the array.

Const ARRAYMIN = arr. Math.min (... arr.);

Arraymin ([1, 5]), 1

Get scroll position

If defined, use Pagexoffset and pageYOffset, otherwise use scrollleft and scrolltop to omit the El to use the default value of window.

Const GETSCROLLPOS = (el = window) = =

({x: (el.pagexoffset!== undefined)? El.pageXOffset:el.scrollLeft,

Y: (el.pageyoffset!== undefined)? EL.PAGEYOFFSET:EL.SCROLLTOP});

GetScrollPos (), {x:0, y:200}

Greatest common divisor (GCD)

Use recursion. The basic situation is when y equals 0 o'clock. In this case, the x is returned. Otherwise, returns the GCD of Y and the remainder of the X/I.

Const GCD = (x, y) = =!y? X:GCD (y, x% y);

GCD (8, 4)

Back to Arr[0]

Const HEAD = arr = arr[0];

List initialization

Back to Arr.slice (0,-1)

Const INITIAL = arr = Arr.slice (0,-1);

Initial ([+])

Initialize an array with range

Use Array (End-start) to create an array of the desired length, use map () to populate the desired values in the range, and omit start using the default value of 0.

Const Initializearrayrange = (end, start = 0) = =

Array.apply (NULL, Array (End-start)). Map ((v, i) = + i + start);

Initializearrayrange (5), [0,1,2,3,4]

Initializing an array with values

Use Array (n) to create an array of the desired length, fill (v) to fill the desired value, and omit value using the default value of 0.

Const InitializeArray = (n, value = 0) = = Array (n). Fill (value);

InitializeArray (5, 2), [2,2,2,2,2]

The last of the list

Back to Arr.slice (-1) [0]

Const LAST = arr = Arr.slice (-1) [0];

Last ([3])

The time it takes to test the feature

Use Performance.now () to get the start and end time of the function, and the time it takes to Console.log (). The first argument is the function name, and subsequent arguments are passed to the function.

Const Timetaken = callback = {

Console.time (' Timetaken ');

Const R = callback ();

Console.timeend (' Timetaken ');

return R;

};

Timetaken (() = Math.pow (2, 1024)

(logged): timetaken:0.02099609375ms

Objects from key-value pairs

Use Array.reduce () to create and combine key-value pairs.

Const OBJECTFROMPAIRS = arr = Arr.reduce ((A, V) = (a[v[0]] = v[1], a), {});

Objectfrompairs ([[' A ', 1],[' B ', 2]]), {a:1, b:2}

Pipeline

Use Array.reduce () to pass a value through a function.

Const PIPE = (... funcs) = arg = Funcs.reduce (ACC, func) = Func (ACC), ARG);

Pipe (btoa, x = X.touppercase ()) ("Test"), "vgvzda=="

Powerset

Use reduce () to combine with map () to iterate through the elements and combine them into an array that contains all the combinations.

Const POWERSET = arr =

Arr.reduce ((A, V) = A.concat (A.map (r = = [V].concat (r))), [[]]);

Powerset [[]], [[], [1], [2], [2,1]]

Random integers in the range

Use Math.random () to generate a random number and map it to the desired range, using Math.floor () to make it an integer.

Const Randomintegerinrange = (min, max) = Math.floor (Math.random () * (Max-min + 1)) + min;

Randomintegerinrange (0, 5)--2

Random number in the range

Use Math.random () to generate a random value and use multiplication to map it to the desired range.

Const Randominrange = (min, max) = = Math.random () * (max-min) + min;

Randominrange (2,10), 6.0211363285087005

Order of the randomized array

Use sort () to reorder elements, using math.random () to randomly sort.

Const SHUFFLE = arr = Arr.sort (() = Math.random ()-0.5);

Shuffle ([+]) [2,3,1]

Redirect to URL

Use Window.location.href or Window.location.replace () to redirect to the URL. Pass the second parameter to simulate a link click (true-default) or HTTP redirect (false).

Const REDIRECT = (URL, Aslink = true) = =

Reverses a string

Use array deconstruction and array.reverse () to reverse the order of characters in a string. Merges characters to get a string using join (').

Const ReverseString = str = = [... str].reverse (). Join (');

ReverseString (' Foobar '), ' raboof '

Use the bitwise Left shift operator (<<) and ToString (16), and then Padstart (6, "0") to convert the given RGB parameter to a hexadecimal string to obtain a 6-bit hexadecimal value.

Const RGBTOHEX = (r, g, B) = ((R << +) + (g << 8) + B). ToString (+). Padstart (6, ' 0 ');

Rgbtohex (255, 165, 1), ' ffa501 '

Scroll to Top

Use Document.documentElement.scrollTop or Document.body.scrollTop to get to the top of the distance.

Scroll a small portion of the distance from the top.

Use Window.requestanimationframe () to scroll.

Const Scrolltotop = _ = = {

Const C = Document.documentElement.scrollTop | | Document.body.scrollTop;

if (C > 0) {

Window.requestanimationframe (Scrolltotop);

Window.scrollto (0, c-c/8);

}

};

Scrolltotop ()

Random array values

Use Array.map () and Math.random () to create an array of random values. Use Array.Sort () to sort the elements of the original array based on random values.

Similarity between arrays

Use filter () to remove a portion of the value that is not values, using includes () to determine.

Const SIMILARITY = (arr, values) = = Arr.filter (v = values.includes (v));

Similarity ([[+] [1,2,4])

Sort by string (in alphabetical order)

Use Split (') to split the string, sort () using Localecompare (), and using join (') to regroup.

Const Sortcharactersinstring = str = =

Str.split ("). Sort ((A, B) = A.localecompare (b)). Join (');

sortcharactersinstring (' cabbage '), ' Aabbceg '

Array sum

Use reduce () to add each value to the accumulator with an initialization value of 0.

Const SUM = arr = Arr.reduce ((ACC, val) = + acc + val, 0);

SUM ([1,2,3,4]), 10

Exchange values for two variables

Use array deconstruction to exchange values between two variables.

[VarA, Varb] = [Varb, VarA];

[x, Y] = [y, X]

List of tail

Back to Arr.slice (1)

Const TAIL = arr = arr.length > 1? Arr.slice (1): arr;

Tail ([+]) [2,3]

Tail ([1]), [1]

Array unique values

Use the ES6 set and the ... rest operator to remove all duplicate values.

Const UNIQUE = arr = = [... new Set (arr)];

Unique ([1,2,2,3,4,4,5]), [1,2,3,4,5]

URL parameters

Use Match () with the appropriate regular expression to get all the key-value pairs, the appropriate map (). Use the object.assign () and spread operators (...). ) combines all key-value pairs into an object, passing location.search as an argument to the current URL.

Const Geturlparameters = URL = =

Url.match (/([^?=&]+) (= ([^&]*))/g). Reduce (

(A, V) = (a[v.slice (0, v.indexof (' = '))] = V.slice (v.indexof (' = ') + 1), a), {}

);

Geturlparameters (' Http://url.com/page?name=Adam&surname=Smith ') {name: ' Adam ', surname: ' Smith '}

UUID Generator

Use the Crypto API to generate a UUID that complies with RFC4122 version 4.

Const UUID = _ = =

([1e7] + -1e3 + -4e3 + -8e3 + -1e11). Replace (/[018]/g, C =

(c ^ crypto.getrandomvalues (new Uint8array (1)) [0] & >> C/4). toString (16)

);

UUID (), ' 7982fcfe-5721-4632-bede-6000885be57d '

Verifying numbers

Use! isNaN and parsefloat () to check if the parameter is a number, use Isfinite () to check if the number is finite.

Const VALIDATENUMBER = n =!isnan (parsefloat (n)) && isfinite (n) && number (n) = = n;

ValidateNumber (' ten ')-True

Translation is a lot of inaccuracies, interested programmers can go to GitHub on their own to view the original English.

48 pieces of JavaScript code carefully collected, in just 30 seconds to understand

Related Keywords:
Related Article

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

## A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

• #### Sales Support

1 on 1 presale consultation

• #### After-Sales Support

24/7 Technical Support 6 Free Tickets per Quarter Faster Response

• Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.