In generally you should convert input string into the array, do the necessary transformation (filter, map, reduce) and join all elements into resulting string.
How to reverse a string
const input = 'reverse me'
const reversed = [...input].reverse().join('')
How to truncate long text
const input = 'long text...'
const truncated = input.split(' ').slice(0, 25).join(' ')
How to replace multiple substrings
let str = "I have a cat, a dog, and a goat.";
const map = {
cat: "dog",
dog: "goat",
goat: "cat"
};
const re = new RegExp(`\b(?:${Object.keys(map).join('|')})\b`, 'gi')
str = str.replace(re, matched => map[matched]);
How to get random element from array
const element = array[Math.floor(Math.random() * array.length)]
How to get only unique items from array
const values = [1, 2, 2, 3, 3, 3]
const unique = [...new Set(values)]
const values = [1, 2, 2, 3, 3, 3]
const unique = values.filter((value, idx) => values.indexOf(value) === idx))
How to transpose an array (turn columns into rows)
function transpose(a) {
for(let i = 0; i < a.length; i++){
for(let j = 0; j < i; j++) {
// The XOR swap algorithm to avoid using temporary variable
// https://en.wikipedia.org/wiki/XOR_swap_algorithm
a[i][j] ^= a[j][i]
a[j][i] ^= a[i][j]
a[i][j] ^= a[j][i]
}
}
return a
}
/*
input:
[[1,2,3],
[4,5,6],
[7,8,9]]
output:
[[1,4,7],
[2,5,8],
[3,6,9]]
*/
How to rotate an array (clockwise)
rotate(a) {
transpose(a)
for(let i in a) {
a[i].reverse()
}
}
/*
input:
[[1,2,3],
[4,5,6],
[7,8,9]]
output:
[[7,4,1],
[8,5,2],
[9,6,3]]
*/
How to loop the slider
const slides = [1,2,3] // slides.length is 3
let currentIndex = 0
const prevIndex = (currentIndex - 1 + slides.length) % slides.length // 2
currentIndex = 2
const nextIndex = (currentIndex + 1) % slides.length // 0
How to initialize locale date time object
new Date() // date and time that depends on system's regional and timezone settings
How to initialize Date with a datetime string
// with UTC time (internally everything is stored in UTC time)
new Date('2022-05-09T11:45:00Z') // 2022-05-09T11:45:00.000Z
// with time for a specific timezone (https://www.timeanddate.com/time/map/)
new Date('2022-05-09 11:45:00-05:00') // 2022-05-09T16:45:00.000Z
// with locale time
new Date('2022-05-09 11:45:00') // 2022-05-09T06:45:00.000Z
How to initialize Date with an epoch time (https://www.epochconverter.com/)
new Date(1652114700000) // 2022-05-09T16:45:00.000Z
How to print date and time
new Date('2022-05-09T11:45:00Z').toLocaleString() // date and time that depends on system's regional settings
new Date('2022-05-09T11:45:00Z').toLocaleString('en-US') // date and time that depends on system's timezone settings
new Date('2022-05-09T11:45:00Z').toLocaleString('en-US', { hour: '2-digit', minute: '2-digit', hour12: false, timeZone: 'America/Mexico_City' }) // '06:45'
Properties of the Symbol:
// local
Symbol('foo') === Symbol('foo') // false
// global
Symbol.for('foo') === Symbol.for('foo') // true
Symbol.keyFor(Symbol.for('foo')) === 'foo' // true
Create an unique property on object:
const count = Symbol('count') // 'count' variable contains the unique value
const dictionary = {[count]: 0}
const add = (key, value) => {
if (dict[key]) throw Error(`The key "${key}" is already exist`)
dictionary[key] = value
dictionary[count]++
}
add('name', 'Jhon')
console.log(Object.keys(dict)) // ['name']
console.log(dict[count]) // 1
There are well-known Symbols. For example, we can make a custom output of the Object.prototype.toString
function that looks for the Symbol.toStringTag
property of the object internally:
const user = {name: 'Jhon', get [Symbol.toStringTag]() { return 'User'}}
console.log(user) // {name: 'Jhon'}
console.log(user.toString()) // [object User]
How to round the float value to the required precision
const value = 1,9032334
const fixedValue = Math.round(value * 1e5) / 1e5
How to deep freeze an object
function isObject(value) {
return value !== null && typeof value === "object";
}
function deepFreeze(value) {
const workSet = new Set([value]);
workSet.forEach(obj => {
if (!isObject(obj)) {
return
}
if (!Object.isFrozen(obj)) {
Object.freeze(obj);
}
Object.getOwnPropertyNames(obj).forEach(name => {
if (isObject(obj[name])) {
workSet.add(obj[name]);
}
});
});
return value;
}
// Alternatively, we could use recursion to avoid creating a Set of all frozen objects
function deepFreeze(obj) {
const freeze = (value) => {
if (!isObject(value)) {
return
}
if (!Object.isFrozen(value)) {
Object.freeze(value);
}
Object.getOwnPropertyNames(value).forEach(name => {
freeze(value[name]);
});
}
freeze(obj)
return obj
}