精心收集的超实用的 JavaScript 代码片段(四)

501502次阅读
没有评论

共计 41488 个字符,预计需要花费 104 分钟才能阅读完成。

提醒:本文最后更新于2024-12-14 04:06,文中所关联的信息可能已发生改变,请知悉!

Node

View contents

Object

View contents

String

View contents

Node

atob

Decodes a string of data which has been encoded using base-64 encoding.

Create a Buffer for the given string with base-64 encoding and use Buffer.toString('binary') to return the decoded string.

const atob = str => Buffer.from(str, 'base64').toString('binary');
Examples
atob('Zm9vYmFy'); // 'foobar'

btoa

Creates a base-64 encoded ASCII string from a String object in which each character in the string is treated as a byte of binary data.

Create a Buffer for the given string with binary encoding and use Buffer.toString('base64') to return the encoded string.

const btoa = str => Buffer.from(str, 'binary').toString('base64');
Examples
btoa('foobar'); // 'Zm9vYmFy'

colorize

Add special characters to text to print in color in the console (combined with console.log()).

Use template literals and special characters to add the appropriate color code to the string output.
For background colors, add a special character that resets the background color at the end of the string.

const colorize = (...args) => ({
  black: `\x1b[30m${args.join(' ')}`,
  red: `\x1b[31m${args.join(' ')}`,
  green: `\x1b[32m${args.join(' ')}`,
  yellow: `\x1b[33m${args.join(' ')}`,
  blue: `\x1b[34m${args.join(' ')}`,
  magenta: `\x1b[35m${args.join(' ')}`,
  cyan: `\x1b[36m${args.join(' ')}`,
  white: `\x1b[37m${args.join(' ')}`,
  bgBlack: `\x1b[40m${args.join(' ')}\x1b[0m`,
  bgRed: `\x1b[41m${args.join(' ')}\x1b[0m`,
  bgGreen: `\x1b[42m${args.join(' ')}\x1b[0m`,
  bgYellow: `\x1b[43m${args.join(' ')}\x1b[0m`,
  bgBlue: `\x1b[44m${args.join(' ')}\x1b[0m`,
  bgMagenta: `\x1b[45m${args.join(' ')}\x1b[0m`,
  bgCyan: `\x1b[46m${args.join(' ')}\x1b[0m`,
  bgWhite: `\x1b[47m${args.join(' ')}\x1b[0m`
});
Examples
console.log(colorize('foo').red); // 'foo' (red letters)
console.log(colorize('foo', 'bar').bgBlue); // 'foo bar' (blue background)
console.log(colorize(colorize('foo').yellow, colorize('foo').green).bgWhite); // 'foo bar' (first word in yellow letters, second word in green letters, white background for both)

hasFlags

Check if the current process’s arguments contain the specified flags.

Use Array.prototype.every() and Array.prototype.includes() to check if process.argv contains all the specified flags.
Use a regular expression to test if the specified flags are prefixed with - or -- and prefix them accordingly.

const hasFlags = (...flags) =>
  flags.every(flag => process.argv.includes(/^-{1,2}/.test(flag) ? flag : '--' + flag));
Examples
// node myScript.js -s --test --cool=true
hasFlags('-s'); // true
hasFlags('--test', 'cool=true', '-s'); // true
hasFlags('special'); // false

hashNode

Creates a hash for a value using the SHA-256 algorithm. Returns a promise.

Use crypto API to create a hash for the given value.

const crypto = require('crypto');
const hashNode = val =>
  new Promise(resolve =>
    setTimeout(
      () =>
        resolve(
          crypto
            .createHash('sha256')
            .update(val)
            .digest('hex')
        ),
      0
    )
  );
Examples
hashNode(JSON.stringify({ a: 'a', b: [1, 2, 3, 4], foo: { c: 'bar' } })).then(console.log); // '04aa106279f5977f59f9067fa9712afc4aedc6f5862a8defc34552d8c7206393'

isDuplexStream

Checks if the given argument is a duplex (readable and writable) stream.

Check if the value is different from null, use typeof to check if a value is of type object and the pipe property is of type function.
Additionally check if the typeof the _read, _write and _readableState, _writableState properties are function and object respectively.

const isDuplexStream = val =>
  val !== null &&
  typeof val === 'object' &&
  typeof val.pipe === 'function' &&
  typeof val._read === 'function' &&
  typeof val._readableState === 'object' &&
  typeof val._write === 'function' &&
  typeof val._writableState === 'object';
Examples
const Stream = require('stream');
isDuplexStream(new Stream.Duplex()); // true

isReadableStream

Checks if the given argument is a readable stream.

Check if the value is different from null, use typeof to check if the value is of type object and the pipe property is of type function.
Additionally check if the typeof the _read and _readableState properties are function and object respectively.

const isReadableStream = val =>
  val !== null &&
  typeof val === 'object' &&
  typeof val.pipe === 'function' &&
  typeof val._read === 'function' &&
  typeof val._readableState === 'object';
Examples
const fs = require('fs');
isReadableStream(fs.createReadStream('test.txt')); // true

isStream

Checks if the given argument is a stream.

Check if the value is different from null, use typeof to check if the value is of type object and the pipe property is of type function.

const isStream = val => val !== null && typeof val === 'object' && typeof val.pipe === 'function';
Examples
const fs = require('fs');
isStream(fs.createReadStream('test.txt')); // true

isTravisCI

Checks if the current environment is Travis CI.

Checks if the current environment has the TRAVIS and CI environment variables (reference).

const isTravisCI = () => 'TRAVIS' in process.env && 'CI' in process.env;
Examples
isTravisCI(); // true (if code is running on Travis CI)

isWritableStream

Checks if the given argument is a writable stream.

Check if the value is different from null, use typeof to check if the value is of type object and the pipe property is of type function.
Additionally check if the typeof the _write and _writableState properties are function and object respectively.

const isWritableStream = val =>
  val !== null &&
  typeof val === 'object' &&
  typeof val.pipe === 'function' &&
  typeof val._write === 'function' &&
  typeof val._writableState === 'object';
Examples
const fs = require('fs');
isWritableStream(fs.createWriteStream('test.txt')); // true

JSONToFile

Writes a JSON object to a file.

Use fs.writeFile(), template literals and JSON.stringify() to write a json object to a .json file.

const fs = require('fs');
const JSONToFile = (obj, filename) =>
  fs.writeFile(`${filename}.json`, JSON.stringify(obj, null, 2));
Examples
JSONToFile({ test: 'is passed' }, 'testJsonFile'); // writes the object to 'testJsonFile.json'

readFileLines

Returns an array of lines from the specified file.

Use readFileSync function in fs node package to create a Buffer from a file.
convert buffer to string using toString(encoding) function.
creating an array from contents of file by spliting file content line by line (each \n).

const fs = require('fs');
const readFileLines = filename =>
  fs
    .readFileSync(filename)
    .toString('UTF8')
    .split('\n');
Examples
/*
contents of test.txt :
  line1
  line2
  line3
  ___________________________
*/
let arr = readFileLines('test.txt');
console.log(arr); // ['line1', 'line2', 'line3']

untildify

Converts a tilde path to an absolute path.

Use String.prototype.replace() with a regular expression and OS.homedir() to replace the ~ in the start of the path with the home directory.

const untildify = str => str.replace(/^~($|\/|\\)/, `${require('os').homedir()}$1`);
Examples
untildify('~/node'); // '/Users/aUser/node'

UUIDGeneratorNode

Generates a UUID in Node.JS.

Use crypto API to generate a UUID, compliant with RFC4122 version 4.

const crypto = require('crypto');
const UUIDGeneratorNode = () =>
  ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
    (c ^ (crypto.randomBytes(1)[0] & (15 >> (c / 4)))).toString(16)
  );
Examples
UUIDGeneratorNode(); // '79c7c136-60ee-40a2-beb2-856f1feabefc'

Object

bindAll

Binds methods of an object to the object itself, overwriting the existing method.

Use Array.prototype.forEach() to return a function that uses Function.prototype.apply() to apply the given context (obj) to fn for each function specified.

const bindAll = (obj, ...fns) =>
  fns.forEach(
    fn => (
      (f = obj[fn]),
      (obj[fn] = function() {
        return f.apply(obj);
      })
    )
  );
Examples
var view = {
  label: 'docs',
  click: function() {
    console.log('clicked ' + this.label);
  }
};
bindAll(view, 'click');
jQuery(element).on('click', view.click); // Logs 'clicked docs' when clicked.

deepClone

Creates a deep clone of an object.

Use recursion.
Use Object.assign() and an empty object ({}) to create a shallow clone of the original.
Use Object.keys() and Array.prototype.forEach() to determine which key-value pairs need to be deep cloned.

const deepClone = obj => {
  let clone = Object.assign({}, obj);
  Object.keys(clone).forEach(
    key => (clone[key] = typeof obj[key] === 'object' ? deepClone(obj[key]) : obj[key])
  );
  return Array.isArray(obj) ? (clone.length = obj.length) && Array.from(clone) : clone;
};
Examples
const a = { foo: 'bar', obj: { a: 1, b: 2 } };
const b = deepClone(a); // a !== b, a.obj !== b.obj

deepFreeze

Deep freezes an object.

Calls Object.freeze(obj) recursively on all unfrozen properties of passed object that are instanceof object.

const deepFreeze = obj =>
  Object.keys(obj).forEach(
    prop =>
      !(obj[prop] instanceof Object) || Object.isFrozen(obj[prop]) ? null : deepFreeze(obj[prop])
  ) || Object.freeze(obj);
Examples
'use strict';

const o = deepFreeze([1, [2, 3]]);

o[0] = 3; // not allowed
o[1][0] = 4; // not allowed as well

defaults

Assigns default values for all properties in an object that are undefined.

Use Object.assign() to create a new empty object and copy the original one to maintain key order, use Array.prototype.reverse() and the spread operator ... to combine the default values from left to right, finally use obj again to overwrite properties that originally had a value.

const defaults = (obj, ...defs) => Object.assign({}, obj, ...defs.reverse(), obj);
Examples
defaults({ a: 1 }, { b: 2 }, { b: 6 }, { a: 3 }); // { a: 1, b: 2 }

dig

Returns the target value in a nested JSON object, based on the given key.

Use the in operator to check if target exists in obj.
If found, return the value of obj[target], otherwise use Object.values(obj) and Array.prototype.reduce() to recursively call dig on each nested object until the first matching key/value pair is found.

const dig = (obj, target) =>
  target in obj
    ? obj[target]
    : Object.values(obj).reduce((acc, val) => {
      if (acc !== undefined) return acc;
      if (typeof val === 'object') return dig(val, target);
    }, undefined);
Examples
const data = {
  level1: {
    level2: {
      level3: 'some data'
    }
  }
};
dig(data, 'level3'); // 'some data'
dig(data, 'level4'); // undefined

equals

Performs a deep comparison between two values to determine if they are equivalent.

Check if the two values are identical, if they are both Date objects with the same time, using Date.getTime() or if they are both non-object values with an equivalent value (strict comparison).
Check if only one value is null or undefined or if their prototypes differ.
If none of the above conditions are met, use Object.keys() to check if both values have the same number of keys, then use Array.prototype.every() to check if every key in the first value exists in the second one and if they are equivalent by calling this method recursively.

const equals = (a, b) => {
  if (a === b) return true;
  if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();
  if (!a || !b || (typeof a !== 'object' && typeof b !== 'object')) return a === b;
  if (a === null || a === undefined || b === null || b === undefined) return false;
  if (a.prototype !== b.prototype) return false;
  let keys = Object.keys(a);
  if (keys.length !== Object.keys(b).length) return false;
  return keys.every(k => equals(a[k], b[k]));
};
Examples
equals({ a: [2, { e: 3 }], b: [4], c: 'foo' }, { a: [2, { e: 3 }], b: [4], c: 'foo' }); // true

findKey

Returns the first key that satisfies the provided testing function. Otherwise undefined is returned.

Use Object.keys(obj) to get all the properties of the object, Array.prototype.find() to test the provided function for each key-value pair. The callback receives three arguments – the value, the key and the object.

const findKey = (obj, fn) => Object.keys(obj).find(key => fn(obj[key], key, obj));
Examples
findKey(
  {
    barney: { age: 36, active: true },
    fred: { age: 40, active: false },
    pebbles: { age: 1, active: true }
  },
  o => o['active']
); // 'barney'

findLastKey

Returns the last key that satisfies the provided testing function.
Otherwise undefined is returned.

Use Object.keys(obj) to get all the properties of the object, Array.prototype.reverse() to reverse their order and Array.prototype.find() to test the provided function for each key-value pair.
The callback receives three arguments – the value, the key and the object.

const findLastKey = (obj, fn) =>
  Object.keys(obj)
    .reverse()
    .find(key => fn(obj[key], key, obj));
Examples
findLastKey(
  {
    barney: { age: 36, active: true },
    fred: { age: 40, active: false },
    pebbles: { age: 1, active: true }
  },
  o => o['active']
); // 'pebbles'

flattenObject

Flatten an object with the paths for keys.

Use recursion.
Use Object.keys(obj) combined with Array.prototype.reduce() to convert every leaf node to a flattened path node.
If the value of a key is an object, the function calls itself with the appropriate prefix to create the path using Object.assign().
Otherwise, it adds the appropriate prefixed key-value pair to the accumulator object.
You should always omit the second argument, prefix, unless you want every key to have a prefix.

const flattenObject = (obj, prefix = '') =>
  Object.keys(obj).reduce((acc, k) => {
    const pre = prefix.length ? prefix + '.' : '';
    if (typeof obj[k] === 'object') Object.assign(acc, flattenObject(obj[k], pre + k));
    else acc[pre + k] = obj[k];
    return acc;
  }, {});
Examples
flattenObject({ a: { b: { c: 1 } }, d: 1 }); // { 'a.b.c': 1, d: 1 }

forOwn

Iterates over all own properties of an object, running a callback for each one.

Use Object.keys(obj) to get all the properties of the object, Array.prototype.forEach() to run the provided function for each key-value pair. The callback receives three arguments – the value, the key and the object.

const forOwn = (obj, fn) => Object.keys(obj).forEach(key => fn(obj[key], key, obj));
Examples
forOwn({ foo: 'bar', a: 1 }, v => console.log(v)); // 'bar', 1

forOwnRight

Iterates over all own properties of an object in reverse, running a callback for each one.

Use Object.keys(obj) to get all the properties of the object, Array.prototype.reverse() to reverse their order and Array.prototype.forEach() to run the provided function for each key-value pair. The callback receives three arguments – the value, the key and the object.

const forOwnRight = (obj, fn) =>
  Object.keys(obj)
    .reverse()
    .forEach(key => fn(obj[key], key, obj));
Examples
forOwnRight({ foo: 'bar', a: 1 }, v => console.log(v)); // 1, 'bar'

functions

Returns an array of function property names from own (and optionally inherited) enumerable properties of an object.

Use Object.keys(obj) to iterate over the object’s own properties.
If inherited is true, use Object.get.PrototypeOf(obj) to also get the object’s inherited properties.
Use Array.prototype.filter() to keep only those properties that are functions.
Omit the second argument, inherited, to not include inherited properties by default.

const functions = (obj, inherited = false) =>
  (inherited
    ? [...Object.keys(obj), ...Object.keys(Object.getPrototypeOf(obj))]
    : Object.keys(obj)
  ).filter(key => typeof obj[key] === 'function');
Examples
function Foo() {
  this.a = () => 1;
  this.b = () => 2;
}
Foo.prototype.c = () => 3;
functions(new Foo()); // ['a', 'b']
functions(new Foo(), true); // ['a', 'b', 'c']

get

Retrieve a set of properties indicated by the given selectors from an object.

Use Array.prototype.map() for each selector, String.prototype.replace() to replace square brackets with dots, String.prototype.split('.') to split each selector, Array.prototype.filter() to remove empty values and Array.prototype.reduce() to get the value indicated by it.

const get = (from, ...selectors) =>
  [...selectors].map(s =>
    s
      .replace(/\[([^\[\]]*)\]/g, '.$1.')
      .split('.')
      .filter(t => t !== '')
      .reduce((prev, cur) => prev && prev[cur], from)
  );
Examples
const obj = { selector: { to: { val: 'val to select' } }, target: [1, 2, { a: 'test' }] };
get(obj, 'selector.to.val', 'target[0]', 'target[2].a'); // ['val to select', 1, 'test']

invertKeyValues

Inverts the key-value pairs of an object, without mutating it. The corresponding inverted value of each inverted key is an array of keys responsible for generating the inverted value. If a function is supplied, it is applied to each inverted key.

Use Object.keys() and Array.prototype.reduce() to invert the key-value pairs of an object and apply the function provided (if any).
Omit the second argument, fn, to get the inverted keys without applying a function to them.

const invertKeyValues = (obj, fn) =>
  Object.keys(obj).reduce((acc, key) => {
    const val = fn ? fn(obj[key]) : obj[key];
    acc[val] = acc[val] || [];
    acc[val].push(key);
    return acc;
  }, {});
Examples
invertKeyValues({ a: 1, b: 2, c: 1 }); // { 1: [ 'a', 'c' ], 2: [ 'b' ] }
invertKeyValues({ a: 1, b: 2, c: 1 }, value => 'group' + value); // { group1: [ 'a', 'c' ], group2: [ 'b' ] }

lowercaseKeys

Creates a new object from the specified object, where all the keys are in lowercase.

Use Object.keys() and Array.prototype.reduce() to create a new object from the specified object.
Convert each key in the original object to lowercase, using String.toLowerCase().

const lowercaseKeys = obj =>
  Object.keys(obj).reduce((acc, key) => {
    acc[key.toLowerCase()] = obj[key];
    return acc;
  }, {});
Examples
const myObj = { Name: 'Adam', sUrnAME: 'Smith' };
const myObjLower = lowercaseKeys(myObj); // {name: 'Adam', surname: 'Smith'};

mapKeys

Creates an object with keys generated by running the provided function for each key and the same values as the provided object.

Use Object.keys(obj) to iterate over the object’s keys.
Use Array.prototype.reduce() to create a new object with the same values and mapped keys using fn.

const mapKeys = (obj, fn) =>
  Object.keys(obj).reduce((acc, k) => {
    acc[fn(obj[k], k, obj)] = obj[k];
    return acc;
  }, {});
Examples
mapKeys({ a: 1, b: 2 }, (val, key) => key + val); // { a1: 1, b2: 2 }

mapValues

Creates an object with the same keys as the provided object and values generated by running the provided function for each value.

Use Object.keys(obj) to iterate over the object’s keys.
Use Array.prototype.reduce() to create a new object with the same keys and mapped values using fn.

const mapValues = (obj, fn) =>
  Object.keys(obj).reduce((acc, k) => {
    acc[k] = fn(obj[k], k, obj);
    return acc;
  }, {});
Examples
const users = {
  fred: { user: 'fred', age: 40 },
  pebbles: { user: 'pebbles', age: 1 }
};
mapValues(users, u => u.age); // { fred: 40, pebbles: 1 }

matches

Compares two objects to determine if the first one contains equivalent property values to the second one.

Use Object.keys(source) to get all the keys of the second object, then Array.prototype.every(), Object.hasOwnProperty() and strict comparison to determine if all keys exist in the first object and have the same values.

const matches = (obj, source) =>
  Object.keys(source).every(key => obj.hasOwnProperty(key) && obj[key] === source[key]);
Examples
matches({ age: 25, hair: 'long', beard: true }, { hair: 'long', beard: true }); // true
matches({ hair: 'long', beard: true }, { age: 25, hair: 'long', beard: true }); // false

matchesWith

Compares two objects to determine if the first one contains equivalent property values to the second one, based on a provided function.

Use Object.keys(source) to get all the keys of the second object, then Array.prototype.every(), Object.hasOwnProperty() and the provided function to determine if all keys exist in the first object and have equivalent values.
If no function is provided, the values will be compared using the equality operator.

const matchesWith = (obj, source, fn) =>
  Object.keys(source).every(
    key =>
      obj.hasOwnProperty(key) && fn
        ? fn(obj[key], source[key], key, obj, source)
        : obj[key] == source[key]
  );
Examples
const isGreeting = val => /^h(?:i|ello)$/.test(val);
matchesWith(
  { greeting: 'hello' },
  { greeting: 'hi' },
  (oV, sV) => isGreeting(oV) && isGreeting(sV)
); // true

merge

Creates a new object from the combination of two or more objects.

Use Array.prototype.reduce() combined with Object.keys(obj) to iterate over all objects and keys.
Use hasOwnProperty() and Array.prototype.concat() to append values for keys existing in multiple objects.

const merge = (...objs) =>
  [...objs].reduce(
    (acc, obj) =>
      Object.keys(obj).reduce((a, k) => {
        acc[k] = acc.hasOwnProperty(k) ? [].concat(acc[k]).concat(obj[k]) : obj[k];
        return acc;
      }, {}),
    {}
  );
Examples
const object = {
  a: [{ x: 2 }, { y: 4 }],
  b: 1
};
const other = {
  a: { z: 3 },
  b: [2, 3],
  c: 'foo'
};
merge(object, other); // { a: [ { x: 2 }, { y: 4 }, { z: 3 } ], b: [ 1, 2, 3 ], c: 'foo' }

nest

Given a flat array of objects linked to one another, it will nest them recursively.
Useful for nesting comments, such as the ones on reddit.com.

Use recursion.
Use Array.prototype.filter() to filter the items where the id matches the link, then Array.prototype.map() to map each one to a new object that has a children property which recursively nests the items based on which ones are children of the current item.
Omit the second argument, id, to default to null which indicates the object is not linked to another one (i.e. it is a top level object).
Omit the third argument, link, to use 'parent_id' as the default property which links the object to another one by its id.

const nest = (items, id = null, link = 'parent_id') =>
  items
    .filter(item => item[link] === id)
    .map(item => ({ ...item, children: nest(items, item.id) }));
Examples
// One top level comment
const comments = [
  { id: 1, parent_id: null },
  { id: 2, parent_id: 1 },
  { id: 3, parent_id: 1 },
  { id: 4, parent_id: 2 },
  { id: 5, parent_id: 4 }
];
const nestedComments = nest(comments); // [{ id: 1, parent_id: null, children: [...] }]

objectFromPairs

Creates an object from the given key-value pairs.

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

const objectFromPairs = arr => arr.reduce((a, [key, val]) => ((a[key] = val), a), {});
Examples
objectFromPairs([['a', 1], ['b', 2]]); // {a: 1, b: 2}

objectToPairs

Creates an array of key-value pair arrays from an object.

Use Object.keys() and Array.prototype.map() to iterate over the object’s keys and produce an array with key-value pairs.

const objectToPairs = obj => Object.keys(obj).map(k => [k, obj[k]]);
Examples
objectToPairs({ a: 1, b: 2 }); // [ ['a', 1], ['b', 2] ]

omit

Omits the key-value pairs corresponding to the given keys from an object.

Use Object.keys(obj), Array.prototype.filter() and Array.prototype.includes() to remove the provided keys.
Use Array.prototype.reduce() to convert the filtered keys back to an object with the corresponding key-value pairs.

const omit = (obj, arr) =>
  Object.keys(obj)
    .filter(k => !arr.includes(k))
    .reduce((acc, key) => ((acc[key] = obj[key]), acc), {});
Examples
omit({ a: 1, b: '2', c: 3 }, ['b']); // { 'a': 1, 'c': 3 }

omitBy

Creates an object composed of the properties the given function returns falsey for. The function is invoked with two arguments: (value, key).

Use Object.keys(obj) and Array.prototype.filter()to remove the keys for which fn returns a truthy value.
Use Array.prototype.reduce() to convert the filtered keys back to an object with the corresponding key-value pairs.

const omitBy = (obj, fn) =>
  Object.keys(obj)
    .filter(k => !fn(obj[k], k))
    .reduce((acc, key) => ((acc[key] = obj[key]), acc), {});
Examples
omitBy({ a: 1, b: '2', c: 3 }, x => typeof x === 'number'); // { b: '2' }

orderBy

Returns a sorted array of objects ordered by properties and orders.

Uses Array.prototype.sort(), Array.prototype.reduce() on the props array with a default value of 0, use array destructuring to swap the properties position depending on the order passed.
If no orders array is passed it sort by 'asc' by default.

const orderBy = (arr, props, orders) =>
  [...arr].sort((a, b) =>
    props.reduce((acc, prop, i) => {
      if (acc === 0) {
        const [p1, p2] = orders && orders[i] === 'desc' ? [b[prop], a[prop]] : [a[prop], b[prop]];
        acc = p1 > p2 ? 1 : p1 < p2 ? -1 : 0;
      }
      return acc;
    }, 0)
  );
Examples
const users = [{ name: 'fred', age: 48 }, { name: 'barney', age: 36 }, { name: 'fred', age: 40 }];
orderBy(users, ['name', 'age'], ['asc', 'desc']); // [{name: 'barney', age: 36}, {name: 'fred', age: 48}, {name: 'fred', age: 40}]
orderBy(users, ['name', 'age']); // [{name: 'barney', age: 36}, {name: 'fred', age: 40}, {name: 'fred', age: 48}]

pick

Picks the key-value pairs corresponding to the given keys from an object.

Use Array.prototype.reduce() to convert the filtered/picked keys back to an object with the corresponding key-value pairs if the key exists in the object.

const pick = (obj, arr) =>
  arr.reduce((acc, curr) => (curr in obj && (acc[curr] = obj[curr]), acc), {});
Examples
pick({ a: 1, b: '2', c: 3 }, ['a', 'c']); // { 'a': 1, 'c': 3 }

pickBy

Creates an object composed of the properties the given function returns truthy for. The function is invoked with two arguments: (value, key).

Use Object.keys(obj) and Array.prototype.filter()to remove the keys for which fn returns a falsey value.
Use Array.prototype.reduce() to convert the filtered keys back to an object with the corresponding key-value pairs.

const pickBy = (obj, fn) =>
  Object.keys(obj)
    .filter(k => fn(obj[k], k))
    .reduce((acc, key) => ((acc[key] = obj[key]), acc), {});
Examples
pickBy({ a: 1, b: '2', c: 3 }, x => typeof x === 'number'); // { 'a': 1, 'c': 3 }

renameKeys

Replaces the names of multiple object keys with the values provided.

Use Object.keys() in combination with Array.prototype.reduce() and the spread operator (...) to get the object’s keys and rename them according to keysMap.

const renameKeys = (keysMap, obj) =>
  Object.keys(obj).reduce(
    (acc, key) => ({
      ...acc,
      ...{ [keysMap[key] || key]: obj[key] }
    }),
    {}
  );
Examples
const obj = { name: 'Bobo', job: 'Front-End Master', shoeSize: 100 };
renameKeys({ name: 'firstName', job: 'passion' }, obj); // { firstName: 'Bobo', passion: 'Front-End Master', shoeSize: 100 }

shallowClone

Creates a shallow clone of an object.

Use Object.assign() and an empty object ({}) to create a shallow clone of the original.

const shallowClone = obj => Object.assign({}, obj);
Examples
const a = { x: true, y: 1 };
const b = shallowClone(a); // a !== b

size

Get size of arrays, objects or strings.

Get type of val (array, object or string).
Use length property for arrays.
Use length or size value if available or number of keys for objects.
Use size of a Blob object created from val for strings.

Split strings into array of characters with split('') and return its length.

const size = val =>
  Array.isArray(val)
    ? val.length
    : val && typeof val === 'object'
      ? val.size || val.length || Object.keys(val).length
      : typeof val === 'string'
        ? new Blob([val]).size
        : 0;
Examples
size([1, 2, 3, 4, 5]); // 5
size('size'); // 4
size({ one: 1, two: 2, three: 3 }); // 3

transform

Applies a function against an accumulator and each key in the object (from left to right).

Use Object.keys(obj) to iterate over each key in the object, Array.prototype.reduce() to call the apply the specified function against the given accumulator.

const transform = (obj, fn, acc) => Object.keys(obj).reduce((a, k) => fn(a, obj[k], k, obj), acc);
Examples
transform(
  { a: 1, b: 2, c: 1 },
  (r, v, k) => {
    (r[v] || (r[v] = [])).push(k);
    return r;
  },
  {}
); // { '1': ['a', 'c'], '2': ['b'] }

truthCheckCollection

Checks if the predicate (second argument) is truthy on all elements of a collection (first argument).

Use Array.prototype.every() to check if each passed object has the specified property and if it returns a truthy value.

const truthCheckCollection = (collection, pre) => collection.every(obj => obj[pre]);
Examples
truthCheckCollection([{ user: 'Tinky-Winky', sex: 'male' }, { user: 'Dipsy', sex: 'male' }], 'sex'); // true

unflattenObject

Unflatten an object with the paths for keys.

Use Object.keys(obj) combined with Array.prototype.reduce() to convert flattened path node to a leaf node.
If the value of a key contains a dot delimiter (.), use Array.prototype.split('.'), string transformations and JSON.parse() to create an object, then Object.assign() to create the leaf node.
Otherwise, add the appropriate key-value pair to the accumulator object.

const unflattenObject = obj =>
  Object.keys(obj).reduce((acc, k) => {
    if (k.indexOf('.') !== -1) {
      const keys = k.split('.');
      Object.assign(
        acc,
        JSON.parse(
          '{' +
            keys.map((v, i) => (i !== keys.length - 1 ? `"${v}":{` : `"${v}":`)).join('') +
            obj[k] +
            '}'.repeat(keys.length)
        )
      );
    } else acc[k] = obj[k];
    return acc;
  }, {});
Examples
unflattenObject({ 'a.b.c': 1, d: 1 }); // { a: { b: { c: 1 } }, d: 1 }

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;
Examples
byteSize('emoji'); // 4
byteSize('Hello World'); // 11

capitalize

Capitalizes the first letter of a string.

Use array destructuring and String.prototype.toUpperCase() to capitalize first letter, ...rest to get array of characters after first letter and then Array.prototype.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) =>
  first.toUpperCase() + (lowerRest ? rest.join('').toLowerCase() : rest.join(''));
Examples
capitalize('fooBar'); // 'FooBar'
capitalize('fooBar', true); // 'Foobar'

capitalizeEveryWord

Capitalizes the first letter of every word in a string.

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

const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase());
Examples
capitalizeEveryWord('hello world!'); // 'Hello World!'

CSVToArray

Converts a comma-separated values (CSV) string to a 2D array.

Use Array.prototype.slice() and Array.prototype.indexOf('\n') to remove the first row (title row) if omitFirstRow is true.
Use String.prototype.split('\n') to create a string for each row, then String.prototype.split(delimiter) to separate the values in each row.
Omit the second argument, delimiter, to use a default delimiter of ,.
Omit the third argument, omitFirstRow, to include the first row (title row) of the CSV string.

const CSVToArray = (data, delimiter = ',', omitFirstRow = false) =>
  data
    .slice(omitFirstRow ? data.indexOf('\n') + 1 : 0)
    .split('\n')
    .map(v => v.split(delimiter));
Examples
CSVToArray('a,b\nc,d'); // [['a','b'],['c','d']];
CSVToArray('a;b\nc;d', ';'); // [['a','b'],['c','d']];
CSVToArray('col1,col2\na,b\nc,d', ',', true); // [['a','b'],['c','d']];

CSVToJSON

Converts a comma-separated values (CSV) string to a 2D array of objects.
The first row of the string is used as the title row.

Use Array.prototype.slice() and Array.prototype.indexOf('\n') and String.prototype.split(delimiter) to separate the first row (title row) into values.
Use String.prototype.split('\n') to create a string for each row, then Array.prototype.map() and String.prototype.split(delimiter) to separate the values in each row.
Use Array.prototype.reduce() to create an object for each row’s values, with the keys parsed from the title row.
Omit the second argument, delimiter, to use a default delimiter of ,.

const CSVToJSON = (data, delimiter = ',') => {
  const titles = data.slice(0, data.indexOf('\n')).split(delimiter);
  return data
    .slice(data.indexOf('\n') + 1)
    .split('\n')
    .map(v => {
      const values = v.split(delimiter);
      return titles.reduce((obj, title, index) => ((obj[title] = values[index]), obj), {});
    });
};
Examples
CSVToJSON('col1,col2\na,b\nc,d'); // [{'col1': 'a', 'col2': 'b'}, {'col1': 'c', 'col2': 'd'}];
CSVToJSON('col1;col2\na;b\nc;d', ';'); // [{'col1': 'a', 'col2': 'b'}, {'col1': 'c', 'col2': 'd'}];

decapitalize

Decapitalizes the first letter of a string.

Use array destructuring and String.toLowerCase() to decapitalize first letter, ...rest to get array of characters after first letter and then Array.prototype.join('') to make it a string again.
Omit the upperRest parameter to keep the rest of the string intact, or set it to true to convert to uppercase.

const decapitalize = ([first, ...rest], upperRest = false) =>
  first.toLowerCase() + (upperRest ? rest.join('').toUpperCase() : rest.join(''));
Examples
decapitalize('FooBar'); // 'fooBar'
decapitalize('FooBar', true); // 'fOOBAR'

escapeHTML

Escapes a string for use in HTML.

Use String.prototype.replace() with a regexp that matches the characters that need to be escaped, using a callback function to replace each character instance with its associated escaped character using a dictionary (object).

const escapeHTML = str =>
  str.replace(
    /[&<>'"]/g,
    tag =>
      ({
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        "'": '&#39;',
        '"': '&quot;'
      }[tag] || tag)
  );
Examples
escapeHTML('<a href="#">Me & you</a>'); // '&lt;a href=&quot;#&quot;&gt;Me &amp; you&lt;/a&gt;'

escapeRegExp

Escapes a string to use in a regular expression.

Use String.prototype.replace() to escape special characters.

const escapeRegExp = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
Examples
escapeRegExp('(test)'); // \\(test\\)

fromCamelCase

Converts a string from camelcase.

Use String.prototype.replace() to remove underscores, hyphens, and spaces and convert words to camelcase.
Omit the second argument to use a default separator of _.

const fromCamelCase = (str, separator = '_') =>
  str
    .replace(/([a-z\d])([A-Z])/g, '$1' + separator + '$2')
    .replace(/([A-Z]+)([A-Z][a-z\d]+)/g, '$1' + separator + '$2')
    .toLowerCase();
Examples
fromCamelCase('someDatabaseFieldName', ' '); // 'some database field name'
fromCamelCase('someLabelThatNeedsToBeCamelized', '-'); // 'some-label-that-needs-to-be-camelized'
fromCamelCase('someJavascriptProperty', '_'); // 'some_javascript_property'

indentString

Indents each line in the provided string.

Use String.replace and a regular expression to add the character specified by indent count times at the start of each line.
Omit the third parameter, indent, to use a default indentation character of ' '.

const indentString = (str, count, indent = ' ') => str.replace(/^/gm, indent.repeat(count));
Examples
indentString('Lorem\nIpsum', 2); // '  Lorem\n  Ipsum'
indentString('Lorem\nIpsum', 2, '_'); // '__Lorem\n__Ipsum'

isAbsoluteURL

Returns true if the given string is an absolute URL, false otherwise.

Use a regular expression to test if the string is an absolute URL.

const isAbsoluteURL = str => /^[a-z][a-z0-9+.-]*:/.test(str);
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.prototype.replace() with an appropriate regular expression to remove unnecessary characters, String.prototype.split(''), Array.prototype.sort() and Array.prototype.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);
};
Examples
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();
Examples
isLowerCase('abc'); // true
isLowerCase('a3@$'); // true
isLowerCase('Ab4'); // false

isUpperCase

Checks if a string is upper case.

Convert the given string to upper case, using String.prototype.toUpperCase() and compare it to the original.

const isUpperCase = str => str === str.toUpperCase();
Examples
isUpperCase('ABC'); // true
isLowerCase('A3@$'); // true
isLowerCase('aB4'); // false

mapString

Creates a new string with the results of calling a provided function on every character in the calling string.

Use String.prototype.split('') and Array.prototype.map() to call the provided function, fn, for each character in str.
Use Array.prototype.join('') to recombine the array of characters into a string.
The callback function, fn, takes three arguments (the current character, the index of the current character and the string mapString was called upon).

const mapString = (str, fn) =>
  str
    .split('')
    .map((c, i) => fn(c, i, str))
    .join('');
Examples
mapString('lorem ipsum', c => c.toUpperCase()); // 'LOREM IPSUM'

mask

Replaces all but the last num of characters with the specified mask character.

Use String.prototype.slice() to grab the portion of the characters that will remain unmasked and use String.padStart() to fill the beginning of the string with the mask character up to the original length.
Omit the second argument, num, to keep a default of 4 characters unmasked. If num is negative, the unmasked characters will be at the start of the string.
Omit the third argument, mask, to use a default character of '*' for the mask.

const mask = (cc, num = 4, mask = '*') => `${cc}`.slice(-num).padStart(`${cc}`.length, mask);
Examples
mask(1234567890); // '******7890'
mask(1234567890, 3); // '*******890'
mask(1234567890, -4, '$'); // '$$$$567890'

pad

Pads a string on both sides with the specified character, if it’s shorter than the specified length.

Use String.padStart() and String.padEnd() to pad both sides of the given string.
Omit the third argument, char, to use the whitespace character as the default padding character.

const pad = (str, length, char = ' ') =>
  str.padStart((str.length + length) / 2, char).padEnd(length, char);
Examples
pad('cat', 8); // '  cat   '
pad(String(42), 6, '0'); // '004200'
pad('foobar', 3); // 'foobar'

palindrome

Returns true if the given string is a palindrome, false otherwise.

Convert the string to String.prototype.toLowerCase() and use String.prototype.replace() to remove non-alphanumeric characters from it.
Then, use the spread operator (...) to split the string into individual characters, Array.prototype.reverse(), String.prototype.join('') and compare it to the original, unreversed string, after converting it to String.prototype.toLowerCase().

const palindrome = str => {
  const s = str.toLowerCase().replace(/[\W_]/g, '');
  return s === [...s].reverse().join('');
};
Examples
palindrome('taco cat'); // true

pluralize

Returns the singular or plural form of the word based on the input number. If the first argument is an object, it will use a closure by returning a function that can auto-pluralize words that don’t simply end in s if the supplied dictionary contains the word.

If num is either -1 or 1, return the singular form of the word. If num is any other number, return the plural form. Omit the third argument to use the default of the singular word + s, or supply a custom pluralized word when necessary. If the first argument is an object, utilize a closure by returning a function which can use the supplied dictionary to resolve the correct plural form of the word.

const pluralize = (val, word, plural = word + 's') => {
  const _pluralize = (num, word, plural = word + 's') =>
    [1, -1].includes(Number(num)) ? word : plural;
  if (typeof val === 'object') return (num, word) => _pluralize(num, word, val[word]);
  return _pluralize(val, word, plural);
};
Examples
pluralize(0, 'apple'); // 'apples'
pluralize(1, 'apple'); // 'apple'
pluralize(2, 'apple'); // 'apples'
pluralize(2, 'person', 'people'); // 'people'

const PLURALS = {
  person: 'people',
  radius: 'radii'
};
const autoPluralize = pluralize(PLURALS);
autoPluralize(2, 'person'); // 'people'

removeNonASCII

Removes non-printable ASCII characters.

Use a regular expression to remove non-printable ASCII characters.

const removeNonASCII = str => str.replace(/[^\x20-\x7E]/g, '');
Examples
removeNonASCII('äÄçÇéÉêlorem-ipsumöÖÐþúÚ'); // 'lorem-ipsum'

reverseString

Reverses a string.

Use the spread operator (...) and Array.prototype.reverse() to reverse the order of the characters in the string.
Combine characters to get a string using String.prototype.join('').

const reverseString = str => [...str].reverse().join('');
Examples
reverseString('foobar'); // 'raboof'

sortCharactersInString

Alphabetically sorts the characters in a string.

Use the spread operator (...), Array.prototype.sort() and String.localeCompare() to sort the characters in str, recombine using String.prototype.join('').

const sortCharactersInString = str => [...str].sort((a, b) => a.localeCompare(b)).join('');
Examples
sortCharactersInString('cabbage'); // 'aabbceg'

splitLines

Splits a multiline string into an array of lines.

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

const splitLines = str => str.split(/\r?\n/);
Examples
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.prototype.map() to combine the letter with each partial permutation, then Array.prototype.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)),
      []
    );
};
Examples
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, '');
Examples
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 => {
  let s =
    str &&
    str
      .match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)
      .map(x => x.slice(0, 1).toUpperCase() + x.slice(1).toLowerCase())
      .join('');
  return s.slice(0, 1).toLowerCase() + s.slice(1);
};
Examples
toCamelCase('some_database_field_name'); // 'someDatabaseFieldName'
toCamelCase('Some label that needs to be camelized'); // 'someLabelThatNeedsToBeCamelized'
toCamelCase('some-javascript-property'); // 'someJavascriptProperty'
toCamelCase('some-mixed_string with spaces_underscores-and-hyphens'); // 'someMixedStringWithSpacesUnderscoresAndHyphens'

toKebabCase

Converts a string to kebab case.

Break the string into words and combine them adding - as a separator, using a regexp.

const toKebabCase = str =>
  str &&
  str
    .match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)
    .map(x => x.toLowerCase())
    .join('-');
Examples
toKebabCase('camelCase'); // 'camel-case'
toKebabCase('some text'); // 'some-text'
toKebabCase('some-mixed_string With spaces_underscores-and-hyphens'); // 'some-mixed-string-with-spaces-underscores-and-hyphens'
toKebabCase('AllThe-small Things'); // "all-the-small-things"
toKebabCase('IAmListeningToFMWhileLoadingDifferentURLOnMyBrowserAndAlsoEditingSomeXMLAndHTML'); // "i-am-listening-to-fm-while-loading-different-url-on-my-browser-and-also-editing-xml-and-html"

toSnakeCase

Converts a string to snake case.

Break the string into words and combine them adding _ as a separator, using a regexp.

const toSnakeCase = str =>
  str &&
  str
    .match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)
    .map(x => x.toLowerCase())
    .join('_');
Examples
toSnakeCase('camelCase'); // 'camel_case'
toSnakeCase('some text'); // 'some_text'
toSnakeCase('some-mixed_string With spaces_underscores-and-hyphens'); // 'some_mixed_string_with_spaces_underscores_and_hyphens'
toSnakeCase('AllThe-small Things'); // "all_the_smal_things"
toSnakeCase('IAmListeningToFMWhileLoadingDifferentURLOnMyBrowserAndAlsoEditingSomeXMLAndHTML'); // "i_am_listening_to_fm_while_loading_different_url_on_my_browser_and_also_editing_some_xml_and_html"

toTitleCase

Converts a string to title case.

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

const toTitleCase = str =>
  str
    .match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)
    .map(x => x.charAt(0).toUpperCase() + x.slice(1))
    .join(' ');
Examples
toTitleCase('some_database_field_name'); // 'Some Database Field Name'
toTitleCase('Some label that needs to be title-cased'); // 'Some Label That Needs To Be Title Cased'
toTitleCase('some-package-name'); // 'Some Package Name'
toTitleCase('some-mixed_string with spaces_underscores-and-hyphens'); // 'Some Mixed String With Spaces Underscores And Hyphens'

truncateString

Truncates a string up to a specified length.

Determine if the string’s length is greater than num.
Return the string truncated to the desired length, with '...' appended to the end or the original string.

const truncateString = (str, num) =>
  str.length > num ? str.slice(0, num > 3 ? num - 3 : num) + '...' : str;
Examples
truncateString('boomerang', 7); // 'boom...'

unescapeHTML

Unescapes escaped HTML characters.

Use String.prototype.replace() with a regex that matches the characters that need to be unescaped, using a callback function to replace each escaped character instance with its associated unescaped character using a dictionary (object).

const unescapeHTML = str =>
  str.replace(
    /&amp;|&lt;|&gt;|&#39;|&quot;/g,
    tag =>
      ({
        '&amp;': '&',
        '&lt;': '<',
        '&gt;': '>',
        '&#39;': "'",
        '&quot;': '"'
      }[tag] || tag)
  );
Examples
unescapeHTML('&lt;a href=&quot;#&quot;&gt;Me &amp; you&lt;/a&gt;'); // '<a href="#">Me & you</a>'

URLJoin

Joins all given URL segments together, then normalizes the resulting URL.

Use String.prototype.join('/') to combine URL segments, then a series of String.prototype.replace() calls with various regexps to normalize the resulting URL (remove double slashes, add proper slashes for protocol, remove slashes before parameters, combine parameters with '&' and normalize first parameter delimiter).

const URLJoin = (...args) =>
  args
    .join('/')
    .replace(/[\/]+/g, '/')
    .replace(/^(.+):\//, '$1://')
    .replace(/^file:/, 'file:/')
    .replace(/\/(\?|&|#[^!])/g, '$1')
    .replace(/\?/g, '&')
    .replace('&', '?');
Examples
URLJoin('http://www.google.com', 'a', '/b/cd', '?foo=123', '?bar=foo'); // 'http://www.google.com/a/b/cd?foo=123&bar=foo'

words

Converts a given string into an array of words.

Use String.prototype.split() with a supplied pattern (defaults to non-alpha as a regexp) to convert to an array of strings. Use Array.prototype.filter() to remove any empty strings.
Omit the second argument to use the default regexp.

const words = (str, pattern = /[^a-zA-Z-]+/) => str.split(pattern).filter(Boolean);
Examples
words('I love javaScript!!'); // ["I", "love", "javaScript"]
words('python, javaScript & coffee'); // ["python", "javaScript", "coffee"]

参考的文档:
https://github.com/Chalarangelo/30-seconds-of-code
30SofCode Api

正文完
 2
Chou Neil
版权声明:本文于2020-05-20转载自30 seconds of code,共计41488字。
转载提示:此文章非本站原创文章,若需转载请联系原作者获得转载授权。