diff --git a/README.md b/README.md index bddfc47cd..7e34acf9e 100644 --- a/README.md +++ b/README.md @@ -141,6 +141,7 @@ average(1, 2, 3); * [`none`](#none) * [`nthElement`](#nthelement) * [`partition`](#partition) +* [`permutations`](#permutations) * [`pull`](#pull) * [`pullAtIndex`](#pullatindex) * [`pullAtValue`](#pullatvalue) @@ -363,7 +364,6 @@ average(1, 2, 3);
View contents -* [`anagrams`](#anagrams) * [`byteSize`](#bytesize) * [`capitalize`](#capitalize) * [`capitalizeEveryWord`](#capitalizeeveryword) @@ -372,6 +372,7 @@ average(1, 2, 3); * [`escapeRegExp`](#escaperegexp) * [`fromCamelCase`](#fromcamelcase) * [`isAbsoluteURL`](#isabsoluteurl) +* [`isAnagram`](#isanagram) * [`isLowerCase`](#islowercase) * [`isUpperCase`](#isuppercase) * [`mask`](#mask) @@ -381,6 +382,7 @@ average(1, 2, 3); * [`reverseString`](#reversestring) * [`sortCharactersInString`](#sortcharactersinstring) * [`splitLines`](#splitlines) +* [`stringPermutations`](#stringpermutations) * [`stripHTMLTags`](#striphtmltags) * [`toCamelCase`](#tocamelcase) * [`toKebabCase`](#tokebabcase) @@ -1851,6 +1853,42 @@ partition(users, o => o.active); // [[{ 'user': 'fred', 'age': 40, 'active':
[⬆ Back to top](#table-of-contents) +### permutations + +⚠️ **WARNING**: This function's execution time increases exponentially with each array element. Anything more than 8 to 10 entries will cause your browser to hang as it tries to solve all the different combinations. + +Generates all permutations of an array's elements (contains duplicates). + +Use recursion. +For each element in the given array, create all the partial permutations for the rest of its elements. +Use `Array.map()` to combine the element with each partial permutation, then `Array.reduce()` to combine all permutations in one array. +Base cases are for array `length` equal to `2` or `1`. + +```js +const permutations = arr => { + if (arr.length <= 2) return arr.length === 2 ? [arr, [arr[1], arr[0]]] : arr; + return arr.reduce( + (acc, item, i) => + acc.concat( + permutations([...arr.slice(0, i), ...arr.slice(i + 1)]).map(val => [item, ...val]) + ), + [] + ); +}; +``` + +
+Examples + +```js +permutations([1, 33, 5]); // [ [ 1, 33, 5 ], [ 1, 5, 33 ], [ 33, 1, 5 ], [ 33, 5, 1 ], [ 5, 1, 33 ], [ 5, 33, 1 ] ] +``` + +
+ +
[⬆ Back to top](#table-of-contents) + + ### pull Mutates the original array to filter out the values specified. @@ -6549,42 +6587,6 @@ unflattenObject({ 'a.b.c': 1, d: 1 }); // { a: { b: { c: 1 } }, d: 1 } --- ## 📜 String -### anagrams - -⚠️ **WARNING**: This function's execution time increases exponentially with each character. Anything more than 8 to 10 characters will cause your browser to hang as it tries to solve all the different combinations. - -Generates all anagrams of a string (contains duplicates). - -Use recursion. -For each letter in the given string, create all the partial anagrams for the rest of its letters. -Use `Array.map()` to combine the letter with each partial anagram, then `Array.reduce()` to combine all anagrams in one array. -Base cases are for string `length` equal to `2` or `1`. - -```js -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)), - [] - ); -}; -``` - -
-Examples - -```js -anagrams('abc'); // ['abc','acb','bac','bca','cab','cba'] -``` - -
- -
[⬆ Back to top](#table-of-contents) - - ### byteSize Returns the length of a string in bytes. @@ -6788,6 +6790,37 @@ isAbsoluteURL('/foo/bar'); // false
[⬆ Back to top](#table-of-contents) +### isAnagram + +Checks if a string is an anagram of another string (case-insensitive, ignores spaces, punctuation and special characters). + +Use `String.toLowerCase()`, `String.replace()` with an appropriate regular expression to remove unnecessary characters, `String.split('')`, `Array.sort()` and `Array.join('')` on both strings to normalize them, then check if their normalized forms are equal. + +```js +const isAnagram = (str1, str2) => { + const normalize = str => + str + .toLowerCase() + .replace(/[^a-z0-9]/gi, '') + .split('') + .sort() + .join(''); + return normalize(str1) === normalize(str2); +}; +``` + +
+Examples + +```js +isAnagram('iceman', 'cinema'); // true +``` + +
+ +
[⬆ Back to top](#table-of-contents) + + ### isLowerCase Checks if a string is lower case. @@ -7023,6 +7056,42 @@ splitLines('This\nis a\nmultiline\nstring.\n'); // ['This', 'is a', 'multiline',
[⬆ Back to top](#table-of-contents) +### stringPermutations + +⚠️ **WARNING**: This function's execution time increases exponentially with each character. Anything more than 8 to 10 characters will cause your browser to hang as it tries to solve all the different combinations. + +Generates all permutations of a string (contains duplicates). + +Use recursion. +For each letter in the given string, create all the partial permutations for the rest of its letters. +Use `Array.map()` to combine the letter with each partial permutation, then `Array.reduce()` to combine all permutations in one array. +Base cases are for string `length` equal to `2` or `1`. + +```js +const stringPermutations = str => { + if (str.length <= 2) return str.length === 2 ? [str, str[1] + str[0]] : [str]; + return str + .split('') + .reduce( + (acc, letter, i) => + acc.concat(stringPermutations(str.slice(0, i) + str.slice(i + 1)).map(val => letter + val)), + [] + ); +}; +``` + +
+Examples + +```js +stringPermutations('abc'); // ['abc','acb','bac','bca','cab','cba'] +``` + +
+ +
[⬆ Back to top](#table-of-contents) + + ### stripHTMLTags Removes HTML/XML tags from string. diff --git a/docs/index.html b/docs/index.html index d8b48804d..cb0c65ff9 100644 --- a/docs/index.html +++ b/docs/index.html @@ -50,7 +50,7 @@ scrollToTop(); } }, false); - }

logo 30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.

 

Adapter

ary

Creates a function that accepts up to n arguments, ignoring any additional arguments.

Call the provided function, fn, with up to n arguments, using Array.slice(0,n) and the spread operator (...).

const ary = (fn, n) => (...args) => fn(...args.slice(0, n));
+      }

logo 30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.

 

Adapter

ary

Creates a function that accepts up to n arguments, ignoring any additional arguments.

Call the provided function, fn, with up to n arguments, using Array.slice(0,n) and the spread operator (...).

const ary = (fn, n) => (...args) => fn(...args.slice(0, n));
 
const firstTwoMax = ary(Math.max, 2);
 [[2, 6, 'a'], [8, 4, 6], [10]].map(x => firstTwoMax(...x)); // [6, 8, 10]
 

call

Given a key and a set of arguments, call them when given a context. Primarily useful in composition.

Use a closure to call a stored key with stored arguments.

const call = (key, ...args) => context => context[key](...args);
@@ -311,6 +311,17 @@ Object.assig
   );
 
const users = [{ user: 'barney', age: 36, active: false }, { user: 'fred', age: 40, active: true }];
 partition(users, o => o.active); // [[{ 'user': 'fred',    'age': 40, 'active': true }],[{ 'user': 'barney',  'age': 36, 'active': false }]]
+

permutations

⚠️ WARNING: This function's execution time increases exponentially with each array element. Anything more than 8 to 10 entries will cause your browser to hang as it tries to solve all the different combinations.

Generates all permutations of an array's elements (contains duplicates).

Use recursion. For each element in the given array, create all the partial permutations for the rest of its elements. Use Array.map() to combine the element with each partial permutation, then Array.reduce() to combine all permutations in one array. Base cases are for array length equal to 2 or 1.

const permutations = arr => {
+  if (arr.length <= 2) return arr.length === 2 ? [arr, [arr[1], arr[0]]] : arr;
+  return arr.reduce(
+    (acc, item, i) =>
+      acc.concat(
+        permutations([...arr.slice(0, i), ...arr.slice(i + 1)]).map(val => [item, ...val])
+      ),
+    []
+  );
+};
+
permutations([1, 33, 5]); // [ [ 1, 33, 5 ], [ 1, 5, 33 ], [ 33, 1, 5 ], [ 33, 5, 1 ], [ 5, 1, 33 ], [ 5, 33, 1 ] ]
 

pull

Mutates the original array to filter out the values specified.

Use Array.filter() and Array.includes() to pull out the values that are not needed. Use Array.length = 0 to mutate the passed in an array by resetting it's length to zero and Array.push() to re-populate it with only the pulled values.

(For a snippet that does not mutate the original array see without)

const pull = (arr, ...args) => {
   let argState = Array.isArray(args[0]) ? args[0] : args;
   let pulled = arr.filter((v, i) => !argState.includes(v));
@@ -1516,18 +1527,7 @@ Foo.prototypereturn acc;
   }, {});
 
unflattenObject({ 'a.b.c': 1, d: 1 }); // { a: { b: { c: 1 } }, d: 1 }
-

String

anagrams

⚠️ WARNING: This function's execution time increases exponentially with each character. Anything more than 8 to 10 characters will cause your browser to hang as it tries to solve all the different combinations.

Generates all anagrams of a string (contains duplicates).

Use recursion. For each letter in the given string, create all the partial anagrams for the rest of its letters. Use Array.map() to combine the letter with each partial anagram, then Array.reduce() to combine all anagrams in one array. Base cases are for string length equal to 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']
-

byteSize

Returns the length of a string in bytes.

Convert a given string to a Blob Object and find its size.

const byteSize = str => new Blob([str]).size;
+

String

byteSize

Returns the length of a string in bytes.

Convert a given string to a Blob Object and find its size.

const byteSize = str => new Blob([str]).size;
 
byteSize('😀'); // 4
 byteSize('Hello World'); // 11
 

capitalize

Capitalizes the first letter of a string.

Use array destructuring and String.toUpperCase() to capitalize first letter, ...rest to get array of characters after first letter and then Array.join('') to make it a string again. Omit the lowerRest parameter to keep the rest of the string intact, or set it to true to convert to lowercase.

const capitalize = ([first, ...rest], lowerRest = false) =>
@@ -1567,6 +1567,17 @@ Foo.prototypeShow examples
isAbsoluteURL('https://google.com'); // true
 isAbsoluteURL('ftp://www.myserver.net'); // true
 isAbsoluteURL('/foo/bar'); // false
+

isAnagram

Checks if a string is an anagram of another string (case-insensitive, ignores spaces, punctuation and special characters).

Use String.toLowerCase(), String.replace() with an appropriate regular expression to remove unnecessary characters, String.split(''), Array.sort() and Array.join('') on both strings to normalize them, then check if their normalized forms are equal.

const isAnagram = (str1, str2) => {
+  const normalize = str =>
+    str
+      .toLowerCase()
+      .replace(/[^a-z0-9]/gi, '')
+      .split('')
+      .sort()
+      .join('');
+  return normalize(str1) === normalize(str2);
+};
+
isAnagram('iceman', 'cinema'); // true
 

isLowerCase

Checks if a string is lower case.

Convert the given string to lower case, using String.toLowerCase() and compare it to the original.

const isLowerCase = str => str === str.toLowerCase();
 
isLowerCase('abc'); // true
 isLowerCase('a3@$'); // true
@@ -1616,6 +1627,17 @@ Foo.prototypeShow examples
sortCharactersInString('cabbage'); // 'aabbceg'
 

splitLines

Splits a multiline string into an array of lines.

Use String.split() and a regular expression to match line breaks and create an array.

const splitLines = str => str.split(/\r?\n/);
 
splitLines('This\nis a\nmultiline\nstring.\n'); // ['This', 'is a', 'multiline', 'string.' , '']
+

stringPermutations

⚠️ WARNING: This function's execution time increases exponentially with each character. Anything more than 8 to 10 characters will cause your browser to hang as it tries to solve all the different combinations.

Generates all permutations of a string (contains duplicates).

Use recursion. For each letter in the given string, create all the partial permutations for the rest of its letters. Use Array.map() to combine the letter with each partial permutation, then Array.reduce() to combine all permutations in one array. Base cases are for string length equal to 2 or 1.

const stringPermutations = str => {
+  if (str.length <= 2) return str.length === 2 ? [str, str[1] + str[0]] : [str];
+  return str
+    .split('')
+    .reduce(
+      (acc, letter, i) =>
+        acc.concat(stringPermutations(str.slice(0, i) + str.slice(i + 1)).map(val => letter + val)),
+      []
+    );
+};
+
stringPermutations('abc'); // ['abc','acb','bac','bca','cab','cba']
 

stripHTMLTags

Removes HTML/XML tags from string.

Use a regular expression to remove HTML/XML tags from a string.

const stripHTMLTags = str => str.replace(/<[^>]*>/g, '');
 
stripHTMLTags('<p><em>lorem</em> <strong>ipsum</strong></p>'); // 'lorem ipsum'
 

toCamelCase

Converts a string to camelcase.

Break the string into words and combine them capitalizing the first letter of each word, using a regexp.

const toCamelCase = str => {
diff --git a/snippets/isAnagram.md b/snippets/isAnagram.md
index 2cf9cc3cf..81045764a 100644
--- a/snippets/isAnagram.md
+++ b/snippets/isAnagram.md
@@ -6,7 +6,13 @@ Use `String.toLowerCase()`, `String.replace()` with an appropriate regular expre
 
 ```js
 const isAnagram = (str1, str2) => {
-  const normalize = str => str.toLowerCase().replace(/[^a-z0-9]/gi, '').split('').sort().join('');
+  const normalize = str =>
+    str
+      .toLowerCase()
+      .replace(/[^a-z0-9]/gi, '')
+      .split('')
+      .sort()
+      .join('');
   return normalize(str1) === normalize(str2);
 };
 ```
diff --git a/snippets/permutations.md b/snippets/permutations.md
index 42168724e..44ec508ce 100644
--- a/snippets/permutations.md
+++ b/snippets/permutations.md
@@ -15,10 +15,7 @@ const permutations = arr => {
   return arr.reduce(
     (acc, item, i) =>
       acc.concat(
-        permutations([...arr.slice(0, i), ...arr.slice(i + 1)]).map(val => [
-          item,
-          ...val,
-        ])
+        permutations([...arr.slice(0, i), ...arr.slice(i + 1)]).map(val => [item, ...val])
       ),
     []
   );
@@ -26,5 +23,5 @@ const permutations = arr => {
 ```
 
 ```js
-permutations([1, 33, 5]) // [ [ 1, 33, 5 ], [ 1, 5, 33 ], [ 33, 1, 5 ], [ 33, 5, 1 ], [ 5, 1, 33 ], [ 5, 33, 1 ] ]
+permutations([1, 33, 5]); // [ [ 1, 33, 5 ], [ 1, 5, 33 ], [ 33, 1, 5 ], [ 33, 5, 1 ], [ 5, 1, 33 ], [ 5, 33, 1 ] ]
 ```