python |
Pythonタグが付けられた新着投稿 - Qiita |
ガウス過程 from Scratch MCMCと勾配法によるハイパーパラメータ最適化 |
https://qiita.com/meltyyyyy/items/5a058ecc81e010876a39
|
fromscratch |
2022-07-24 13:59:53 |
python |
Pythonタグが付けられた新着投稿 - Qiita |
Python:Numbaを使って処理を高速化する |
https://qiita.com/smoriuchi/items/da0cc91ae4c86bb2e48a
|
pythonnumba |
2022-07-24 13:59:26 |
python |
Pythonタグが付けられた新着投稿 - Qiita |
ABC246 D Dif:1148 『AtCoder ABC226~250 ARC129~139 灰・茶・緑問題 超詳細解説』サンプル |
https://qiita.com/sano192/items/a22aadde99945bfb01a8
|
kindle |
2022-07-24 13:57:46 |
python |
Pythonタグが付けられた新着投稿 - Qiita |
ABC226 C Dif:539 『AtCoder ABC226~250 ARC129~139 灰・茶・緑問題 超詳細解説』サンプル |
https://qiita.com/sano192/items/3aa26373ca6cfcb3ef0f
|
kindle |
2022-07-24 13:57:13 |
Ruby |
Rubyタグが付けられた新着投稿 - Qiita |
Rails4からRails5へのアップデート手順(Rails4.2.11→Rails5.2.6.2) |
https://qiita.com/t_mapico/items/ddf423113225ac45b033
|
railsrails |
2022-07-24 13:01:48 |
AWS |
AWSタグが付けられた新着投稿 - Qiita |
CognitoのTooManyRequestsException対策 |
https://qiita.com/kyabaria/items/5bd8fb17e8a2545181d2
|
cognito |
2022-07-24 13:25:20 |
Ruby |
Railsタグが付けられた新着投稿 - Qiita |
Rails4からRails5へのアップデート手順(Rails4.2.11→Rails5.2.6.2) |
https://qiita.com/t_mapico/items/ddf423113225ac45b033
|
railsrails |
2022-07-24 13:01:48 |
海外TECH |
DEV Community |
150+ Typescript one-liners [code snippets]. |
https://dev.to/chrisciokler/150-typescript-one-liners-code-snippets-4l51
|
Typescript one liners code snippets OneLinersOneLiners are short snippets of code that are used in many places in the codebase This is a collection of one liners written in typescript Table of content Array one linersDate one linersFunctions one linersMath one linersMisc one linersObjects one linersString one linersHope you like this post let s get down to business Array one liners ️ Cast a value as an array export const castArray lt T gt value T T T gt Array isArray value value value castArray castArray Check if an array is emptyexport const isEmpty lt T gt arr T boolean gt Array isArray arr amp amp arr length isEmpty true isEmpty false Clone an arrayexport const clone lt T gt arr T T gt arr clone Compare two arraysexport const isEqual lt T gt a T b T boolean gt JSON stringify a JSON stringify b isEqual true isEqual false Compare two arrays regardless of orderexport const isEqualWithoutOrder lt T gt a T b T boolean gt JSON stringify new Set a sort JSON stringify new Set b sort isEqualWithoutOrder true isEqualWithoutOrder true isEqualWithoutOrder false Convert an array of objects to a single objectexport const toObject lt T extends Record lt string any gt K extends keyof T gt arr T key K Record lt string T gt gt arr reduce a b gt a b key b toObject id name Alpha gender Male id name Bravo gender Male id name Charlie gender Female id id name Alpha gender Male id name Bravo gender Male id name Charlie gender Female Convert an array of strings to numbersexport const toNumbers arr string number gt arr map Number toNumbers Count by the properties of an array of objectsexport const countBy lt T extends Record lt string string gt K extends keyof T gt arr T prop K Record lt string number gt gt arr reduce prev curr gt prev curr prop prev curr prop prev as Record lt string number gt countBy branch audi model q year branch audi model rs year branch ford model mustang year branch ford model explorer year branch bmw model x year branch audi ford bmw Count the occurrences of a value in an arrayexport const countOccurrences lt T gt arr T val T number gt arr reduce a v gt v val a a countOccurrences Count the occurrences of array elementsexport const countOccurrencesElements lt T extends string number gt arr T Record lt T number gt gt arr reduce prev curr gt prev curr prev curr prev as Record lt T number gt countOccurrencesElements Create an array of cumulative sumexport const accumulate arr number number gt arr reduce a b i gt i b a b a i accumulate Create an array of numbers in the given rangeexport const range min number max number number gt Array max min keys map i gt i min range Find the closest number from an arrayexport const closest arr number n number number gt arr sort a b gt Math abs a n Math abs b n closest Find the index of the last matching item of an arrayexport const lastIndex lt T gt arr T predicate a T gt boolean number gt arr map item gt predicate item lastIndexOf true lastIndex i gt i lastIndex i gt i gt Find the index of the maximum item of an arrayexport const indexOfMax arr number number gt arr reduce prev curr i a gt curr gt a prev i prev indexOfMax indexOfMax Find the index of the minimum item of an arrayexport const indexOfMin arr number number gt arr reduce prev curr i a gt curr lt a prev i prev indexOfMin indexOfMin Find the length of the longest string in an arrayexport const findLongest words string number gt Math max words map el gt el length findLongest always look on the bright side of life Find the maximum item of an array by given keyexport const maxBy lt T extends Record lt string any gt K extends keyof T gt arr T key K T gt arr reduce a b gt a key gt b key a b as T const people name Bar age name Baz age name Foo age name Fuzz age maxBy people age name Foo age Find the maximum item of an arrayexport const max arr number number gt Math max arr max Find the minimum item of an array by given keyexport const minBy lt T extends Record lt string any gt K extends keyof T gt arr T key K T gt arr reduce a b gt a key lt b key a b as T const people name Bar age name Baz age name Foo age name Fuzz age minBy people age name Bar age Find the minimum item of an arrayexport const min arr number number gt Math min arr min Get all arrays of consecutive elementsexport const getConsecutiveArrays lt T gt arr T size number T gt size gt arr length arr slice size map i gt arr slice i size i getConsecutiveArrays getConsecutiveArrays getConsecutiveArrays Get all n th items of an arrayexport const getNthItems lt T gt arr T nth number T gt arr filter i gt i nth nth getNthItems getNthItems Get indices of a value in an arrayexport const indices lt T gt arr T value T number gt arr reduce acc v i gt v value acc i acc as number indices h e l l o l indices h e l l o w Get the average of an arrayexport const average arr number number gt arr reduce a b gt a b arr length average Get the intersection of arraysexport const getIntersection lt T gt a T arr T T gt new Set a filter v gt arr every b gt b includes v getIntersection getIntersection Get the rank of an array of numbersexport const ranking arr number number gt arr map x y z gt z filter w gt w gt x length ranking ranking ranking Get the sum of an array of numbersexport const sum arr number number gt arr reduce a b gt a b sun Get the unique values of an arrayexport const unique lt T gt arr T T gt new Set arr unique Get union of arraysexport const union lt T gt arr T T gt new Set arr flat union Group an array of objects by a keyexport const groupBy lt T extends Record lt string any gt K extends keyof T gt arr T key K Record lt string T gt gt arr reduce acc item gt acc item key acc item key item acc as Record lt string T gt groupBy branch audi model q year branch audi model rs year branch ford model mustang year branch ford model explorer year branch bmw model x year branch audi branch audi model q year branch audi model rs year bmw branch bmw model x year ford branch ford model mustang year branch ford model explorer year Intersperse element between elementsexport const intersperse lt T gt a T s T T gt Array a length map i gt i s a i intersperse A B C A B C intersperse lt li gt A lt li gt lt li gt B lt li gt lt li gt C lt li gt lt li gt lt li gt lt li gt A lt li gt lt li gt lt li gt lt li gt B lt li gt lt li gt lt li gt lt li gt C lt li gt Merge two arraysexport const merge lt T gt a T b T T gt a b merge Partition an array based on a condition export const partition lt T gt arr T criteria a T gt boolean T gt arr reduce acc i gt acc criteria i push i acc partition n gt n Remove duplicate values in an arrayexport const removeDuplicate lt T gt arr T T gt arr filter i gt arr indexOf i arr lastIndexOf i removeDuplicate h e l l o w o r l d h e w r d Remove falsy values from arrayexport const removeFalsy lt T gt arr T T gt arr filter Boolean a string true another string Repeat an arrayexport const repeat lt T gt arr T n number T gt Array n fill arr flat repeat Shuffle an arrayexport const shuffle lt T gt arr T T gt arr map a gt sort Math random value a sort a b gt a sort b sort map a gt a value shuffle Sort an array of items by given keyexport const sortBy lt T extends Record lt string any gt K extends keyof T gt arr T k K T gt arr concat sort a b gt a k gt b k a k lt b k const people name Foo age name Bar age name Fuzz age name Baz age sortBy people age name Bar age name Baz age name Fuzz age name Foo age Sort an array of numbersexport const sort arr number number gt arr sort a b gt a b sort Split an array into chunksexport const chunk lt T gt arr T size number T gt arr reduce acc e i gt i size acc acc length push e acc push e acc as T chunk chunk Swap the rows and columns of a matrixexport const transpose lt T gt matrix T T gt matrix map col i gt matrix map row gt row i transpose Swap two array itemsexport const swapItems lt T gt a T i number j number T gt a i amp amp a j amp amp a slice i a j a slice i j a i a slice j a swapItems Get all subsets of an arrayexport const getSubsets lt T gt arr T T gt arr reduce prev curr gt prev concat prev map k gt k concat curr as T getSubsets getSubsets Date one liners ️ Add AM PM suffix to an hourexport const suffixAmPm h number string gt h h h lt am pm suffixAmPm am suffixAmPm am suffixAmPm pm suffixAmPm pm suffixAmPm pm Calculate the number of difference days between two datesexport const diffDays date Date otherDate Date number gt Math ceil Math abs date valueOf otherDate valueOf diffDays new Date new Date Calculate the number of months between two datesexport const monthDiff startDate Date endDate Date number gt Math max endDate getFullYear startDate getFullYear startDate getMonth endDate getMonth monthDiff new Date new Date Compare two datesexport const compare a Date b Date boolean gt a getTime gt b getTime compare new Date new Date true Convert a date to YYYY MM DD formatexport const formatYmd date Date string gt date toISOString slice formatYmd new Date Convert a date to YYYY MM DD HH MM SS formatexport const formatYmdHis date Date string gt date toISOString slice formatYmdHis new Date T Z Convert seconds to hh mm ss formatexport const formatSeconds s number string gt new Date s toISOString substr formatSeconds formatSeconds Extract year month day hour minute second and millisecond from a dateexport const extract date Date string gt date toISOString split slice extract new Date Format a date for the given localeexport const format date Date locale string string gt new Intl DateTimeFormat locale format date format new Date pt BR Get the current quarter of a dateexport const getQuarter d new Date number gt Math ceil d getMonth getQuarter new Date Get the current timestamp in secondsexport const tseconds number gt Math floor new Date getTime ts Get the day of the year from a dateexport const dayOfYear date Date number gt Math floor date valueOf new Date date getFullYear valueOf dayOfYear new Date Get the first date in the month of a dateexport const getFirstDate d new Date Date gt new Date d getFullYear d getMonth getFirstDate new Date Get the last date in the month of a dateexport const getLastDate d new Date Date gt new Date d getFullYear d getMonth getLastDate new Date Get the month name of a dateexport const getMonthName date Date string gt January February March April May June July August September October November December date getmonth getMonthName new Date January Get the number of days in given monthexport const daysInMonth month number year number number gt new Date year month getDate daysInMonth Get the timezone stringexport const getTimezone string gt Intl DateTimeFormat resolvedOptions timeZone getTimezone Asia Saigon Get the tomorrow dateexport const tomorrow Date d gt new Date d setDate d getDate new Date tomorrow Get the total number of days in a yearexport const numberOfDays year number number gt new Date year getDate numberOfDays Get the weekday of a dateexport const getWeekday date Date string gt Sunday Monday Tuesday Wednesday Thursday Friday Saturday date getday getWeekday new Date Sunday Get the yesterday dateexport const yesterday Date d gt new Date d setDate d getDate new Date yesterday Initialize the current date but set time to midnightexport const midnightOfToday Date gt new Date new Date setHours midnightOfToday T Z Sort an array of datesexport const sortDescending arr Date Date gt arr sort a b gt a getTime b getTime sortDescending new Date new Date new Date new Date export const sortAscending arr Date Date gt arr sort a b gt b getTime a getTime sortAscending new Date new Date new Date new Date Functions one liners ️ Box handlerexport const boxHandler x any next f any gt any done f any gt any gt next f any gt boxHandler f x done f any gt f x const getMoney price gt Number parseFloat price replace const getPercent percent gt Number parseFloat percent replace const getDiscountPrice price discount gt boxHandler getMoney price done cents gt boxHandler getPercent discount next save gt cents cents save done res gt res getDiscountPrice Check if a value is a functionexport const isFunction v any boolean gt object Function object GeneratorFunction object AsyncFunction object Promise includes Object prototype toString call v isFunction function true isFunction function true isFunction async function true Check if a value is a generator functionexport const isGeneratorFunction v any boolean gt Object prototype toString call v object GeneratorFunction isGeneratorFunction function false isGeneratorFunction function true Check if a value is an async functionexport const isAsyncFunction v any boolean gt Object prototype toString call v object AsyncFunction isAsyncFunction function false isAsyncFunction function false isAsyncFunction async function true Compose functions from left to rightexport const pipe fns any gt x any gt fns reduce y f gt f y x const lowercase str gt str toLowerCase const capitalize str gt str charAt toUpperCase str slice const reverse str gt str split reverse join const fn pipe lowercase capitalize reverse We will execute lowercase capitalize and reverse in order fn Hello World dlrow olleH Compose functions from right to leftexport const compose fns any gt x any gt fns reduceRight y f gt f y x const lowercase str gt str toLowerCase const capitalize str gt str charAt toUpperCase str slice const reverse str gt str split reverse join const fn compose reverse capitalize lowercase We will execute lowercase capitalize and reverse in order fn Hello World dlrow olleH Curry a functionexport const curry fn any args any any gt fn length lt args length fn args curry bind null fn args const sum a b c gt a b c curry sum curry sum curry sum curry sum curry sum curry sum Memoize a functionexport const memoize fn any gt cache Object create null gt arg any gt cache arg cache arg fn arg Calculate Fibonacci numbers const fibo memoize n number gt n lt fibo n fibo n fibo fibo fibo fibo fibo fibo Math one liners ️ Calculate the angle of a line defined by two pointsinterface Point x number y number export const radiansAngle p Point p Point number gt Math atan p y p y p x p x radiansAngle x y x y export const degreesAngle p Point p Point number gt Math atan p y p y p x p x Math PI degreesAngle x y x y Calculate the distance between two pointsinterface Point x number y number export const distance p Point p Point number gt Math sqrt Math pow p x p x Math pow p y p y distance x y x y Calculate the linear interpolation between two numbersexport const lerp a number b number amount number number gt amount a amount b lerp Calculate the midpoint between two pointsinterface Point x number y number export const midpoint p Point p Point number gt p x p x p y p y midpoint x y x y Calculate the slope between two pointsinterface Point x number y number export const slope p Point p Point number gt p y p y p x p x slope x y x y Calculate the perpendicular slope between two pointsinterface Point x number y number export const perpendicularSlope p Point p Point number gt slope p p perpendicularSlope x y x y Check if a point is inside a rectangleinterface Point x number y number interface Rect bottom number left number top number right number export const isInside point Point rect Rect boolean gt point x gt rect left amp amp point x lt rect right amp amp point y gt rect top amp amp point y lt rect bottom isInside x y left top right bottom true Check if a point is inside a circleinterface Point x number y number export const isInsideCircle point Point center Point radius number boolean gt const distance Math sqrt Math pow point x center x Math pow point y center y return distance lt radius isInsideCircle x y x y true Check if a rectangle contains other oneinterface Rect x number x number y number y number export const contains a Rect b Rect boolean gt a x lt b x amp amp a y lt b y amp amp a x gt b x amp amp a y gt b y contains x y x y x y x y true Check if a rectangle overlaps another oneinterface Rect x number x number y number y number export const overlaps a Rect b Rect boolean gt a x lt b x a x gt b x a y lt b y a y gt b y overlaps x y x y x y x y true Check if a rectangle is inside another oneinterface Rect x number x number y number y number export const isInsideRect a Rect b Rect boolean gt a x gt b x amp amp a y gt b y amp amp a x lt b x amp amp a y lt b y isInsideRect x y x y x y x y true Check if a rectangle is outside another oneinterface Rect x number x number y number y number export const isOutsideRect a Rect b Rect boolean gt a x lt b x a y lt b y a x gt b x a y gt b y isOutsideRect x y x y x y x y true Check if a rectangle is touching another oneinterface Rect x number x number y number y number export const isTouchingRect a Rect b Rect boolean gt a x b x a x b x a y b y a y b y isTouchingRect x y x y x y x y true Convert degrees to radiansexport const degsToRads deg number number gt deg Math PI degsToRads Convert radians to degreesexport const radsToDegs rad number number gt rad Math PI radsToDegs Normalize the ratio of a number in a rangeexport const normalizeRatio value number min number max number number gt value min max min normalizeRatio Round a number to the nearest multiple of a given valueexport const roundNearest value number nearest number number gt Math round value nearest nearest roundNearest roundNearest roundNearest Round a number to a given number of decimal placesexport const roundToDecimal value number decimals number number gt const factor Math pow decimals return Math round value factor factor roundToDecimal Calculate the average of argumentsexport const average args number number gt args reduce a b gt a b args length average Calculate the division of argumentsexport const division args number number gt args reduce a b gt a b division Calculate the factorial of a numberexport const factorial n number number gt n lt n factorial n factorial factorial factorial factorial factorial Calculate the mod of collection indexexport const mod a number b number number gt a b b b mod mod mod Calculate the remainder of division of argumentsexport const remainder args number number gt args reduce a b gt a b remainder Calculate the sum of argumentsexport const sum args number number gt args reduce a b gt a b sum Clamp a number between two valuesexport const clamp val number min number max number number gt Math max min Math min max val clamp Compute the greatest common divisor between two numbersexport const gcd a number b number number gt b a gcd b a b gcd Compute the least common multiple between two numbersexport const lcm a number b number number gt a b gcd a b lcm Compute the median of a collection of numbersexport const median args number number gt const sorted args sort a b gt a b const mid Math floor sorted length return sorted length sorted mid sorted mid sorted mid median Multiply argumentsexport const mul args number number gt args reduce a b gt a b mul Subtract argumentsexport const subtract args number number gt args reduce a b gt a b subtract Misc one liners ️ Check if the code is running in Jestexport const isRunningInJest boolean typeof process undefined amp amp process env JEST WORKER ID undefined isRunningInJest true Check if the code is running in NodeJSexport const isNode boolean typeof process undefined amp amp process versions null amp amp process versions node null isNode true Check if the code is running in the browserexport const isBrowser boolean typeof window object amp amp typeof document object isBrowser true Clear all cookiesexport const clearCookies void gt document cookie split forEach c gt document cookie c replace replace expires new Date toUTCString path clearCookies Convert digits color to digits colorexport const toFullHexColor color string string gt color startsWith color slice color split map c gt c c join toFullHexColor toFullHexColor toFullHexColor abc aabbcc Convert Celsius to Fahrenheitexport const celsiusToFahrenheit celsius number number gt celsius celsiusToFahrenheit celsiusToFahrenheit celsiusToFahrenheit Convert Fahrenheit to Celsiusexport const fahrenheitToCelsius fahrenheit number number gt fahrenheit fahrenheitToCelsius Convert Celsius to Kelvinexport const celsiusToKelvin celsius number number gt celsius celsiusToKelvin celsiusToKelvin Convert Fahrenheit to Kelvinexport const fahrenheitToKelvin fahrenheit number number gt fahrenheit fahrenheitToKelvin Convert Kelvin to Celsiusexport const kelvinToCelsius kelvin number number gt kelvin kelvinToCelsius kelvinToCelsius Convert Kelvin to Fahrenheitexport const kelvinToFahrenheit kelvin number number gt kelvin kelvinToFahrenheit kelvinToFahrenheit Convert rgb color to hexexport const rgbToHex red number green number blue number string gt red green blue map v gt v toString padStart join rgbToHex ffff Convert hex color to rgbexport const hexToRgb hex string number number number gt const r g b hex slice split map c gt parseInt c c return r g b hexToRgb ffff Convert URL parameters to objectexport const getUrlParams query string Record lt string string gt gt Array from new URLSearchParams query reduce p k v gt Object assign p k p k Array isArray p k p k p k concat v v as Record lt string string gt getUrlParams location search Get the parameters of the current URL getUrlParams foo Foo amp bar Bar foo Foo bar Bar Duplicate key getUrlParams foo Foo amp foo Fuzz amp bar Bar foo Foo Fuzz bar Bar Convert object to URL parametersexport const toUrlParams obj Record lt string string string gt string gt const params new URLSearchParams Object entries obj forEach k v gt if Array isArray v v forEach val gt params append k val else params append k v params toString return params toString toUrlParams foo Foo bar Bar foo Foo amp bar Bar Decode a JWT tokenexport const decodeJwt token string Record lt string string gt gt const payload token split return JSON parse atob payload decodeJwt eyJhbGciOiJIUzINiIsInRcCIIkpXVCJ eyJzdWIiOiIxMjMNTYODkwIiwibmFtZSIIkpvaGgRGlIiwiaWFIjoxNTEMjMMDIyfQ SflKxwRJSMeKKFQTfwpMeJfPOkyJV adQsswc sub name John Doe iat Encode a JWT tokenexport const encodeJwt obj Record lt string string gt string gt const payload JSON stringify obj const basePayload btoa payload const baseHeader btoa JSON stringify alg none typ JWT return baseHeader basePayload encodeJwt sub name John Doe iat eyJhbGciOiJIUzINiIsInRcCIIkpXVCJ eyJzdWIiOiIxMjMNTYODkwIiwibmFtZSIIkpvaGgRGlIiwiaWFIjoxNTEMjMMDIyfQ Detect dark modeexport const isDarkMode boolean window matchMedia amp amp window matchMedia prefers color scheme dark matches isDarkMode true Easing functionsexport const linear t number number gt t export const easeInQuad t number number gt t t export const easeOutQuad t number number gt t t export const easeInOutQuad t number number gt t lt t t t t export const easeInCubic t number number gt t t t export const easeOutCubic t number number gt t t t export const easeInOutCubic t number number gt t lt t t t t t t export const easeInQuart t number number gt t t t t export const easeOutQuart t number number gt t t t t export const easeInOutQuart t number number gt t lt t t t t t t t t export const easeInQuint t number number gt t t t t t export const easeOutQuint t number number gt t t t t t export const easeInOutQuint t number number gt t lt t t t t t t t t t t export const easeInSine t number number gt Math sin Math PI t Math PI export const easeOutSine t number number gt Math sin Math PI t export const easeInOutSine t number number gt Math sin Math PI t Math PI export const easeInElastic t number number gt t Math sin t export const easeOutElastic t number number gt t t Math sin t export const easeInOutElastic t number number gt t lt t Math sin t t Math sin t Emulate a dice throwexport const throwdice number gt Math random throwdice throwdice throwdice Emulate a coin flipexport const flipcoin boolean gt Math random lt flipcoin true Encode a URLexport const encode url string string gt encodeURIComponent url replace g replace g E replace g A replace g replace g replace g replace g encode https A F Fwww google com F Decode a URLexport const decode url string string gt decodeURIComponent url replace g decode https A F Fwww google com F Get the current URLexport const getUrl string gt window location href getUrl Get the first defined and non null argumentexport const coalesce args any any gt args find item gt undefined null includes item coalesce undefined null helloworld NaN helloworld Get the value of a param from a URLexport const getParam url string param string string null gt new URLSearchParams new URL url search get param getParam message hello message hello Get type of a variable in stringexport const getTypeOf obj any string gt Object prototype toString call obj match object as string getTypeOf hello world String getTypeOf Number getTypeOf Infinity Number getTypeOf true Boolean getTypeOf Symbol Symbol getTypeOf null Null getTypeOf undefined Undefined getTypeOf Object getTypeOf Array getTypeOf a z g RegExp getTypeOf new Date Date getTypeOf new Error Error getTypeOf function Function getTypeOf a b gt a b Function getTypeOf async gt AsyncFunction getTypeOf document HTMLDocument Redirect the page to HTTPS if it is in HTTPexport const redirectHttps string gt location protocol https location protocol https Run Promises in sequenceexport const run promises Promise lt any gt Promise lt any gt gt promises reduce p c gt p then rp gt c then rc gt rp rc Promise resolve run promises then results gt results is an array of promise results in the same order Run Promises in parallelexport const runParallel promises Promise lt any gt Promise lt any gt gt Promise all promises runParallel promises then results gt results is an array of promise results in the same order Run Promises in parallel and return the results in the same orderexport const runParallelOrder promises Promise lt any gt Promise lt any gt gt Promise all promises then results gt results reduce p c gt p c runParallelOrder promises then results gt results is an array of promise results in the same order Wait for an amount of timeexport const wait async milliseconds number gt new Promise resolve gt setTimeout resolve milliseconds wait then gt console log done Add an ordinal suffix to a numberexport const addOrdinal n number string gt n st nd rd n gt gt amp amp n th addOrdinal st addOrdinal nd addOrdinal rd addOrdinal th addOrdinal th addOrdinal th Convert a number to equivalent charactersexport const toChars n number string gt n gt toChars Math floor n ABCDEFGHIJKLMNOPQRSTUVWXYZ n toChars A toChars B toChars Z toChars AA toChars AB toChars AZ Objects one liners ️ Check if multiple objects are equalexport const isEqual objects object boolean gt objects every obj gt JSON stringify obj JSON stringify objects isEqual foo bar foo bar true isEqual foo bar bar foo false Extract values of a property from an array of objectsexport const pluck objs any property any gt objs map obj gt obj property pluck name John age name Smith age name Peter age name John Smith Peter Get the value at given path of an objectexport const getValue path string obj any gt path split reduce acc c gt acc amp amp acc c obj getValue a b a b Hello World Hello World Remove all null and undefined properties from an objectexport const removeNullUndefined obj Object gt Object fromEntries Object entries obj filter v gt v null removeNullUndefined foo null bar undefined fuzz fuzz Shallow clone an objectexport const shallowCopy obj Object Object gt obj Sort an object by its propertiesexport const sort obj any gt Object keys obj sort reduce p any c string gt p c obj c p const colors white ffffff black red ff green blue ff sort colors black blue ff green red ff white ffffff String one liners ️ Capitalize a stringexport const capitalize str string string gt str charAt toUpperCase str slice capitalize hello world Hello world Check if a path is relativeexport const isRelative path string boolean gt a z i test path isRelative foo bar baz false isRelative C foo bar baz false isRelative foo bar baz txt true isRelative foo md true Check if a string consists of a repeated character sequenceexport const consistsRepeatedSubstring str string boolean gt str str indexOf str str length consistsRepeatedSubstring aa true consistsRepeatedSubstring aaa true consistsRepeatedSubstring ababab true consistsRepeatedSubstring abc false Check if a URL is absoluteexport const isAbsoluteUrl url string boolean gt a z a z test url isAbsoluteUrl true isAbsoluteUrl true isAbsoluteUrl loc dev false isAbsoluteUrl loc dev false Check if two strings are anagramexport const areAnagram str string str string boolean gt str toLowerCase split sort join str toLowerCase split sort join areAnagram listen silent true areAnagram they see the eyes true areAnagram node deno true Convert a base encoded string to an uint arrayexport const baseToUint str string UintArray gt UintArray from atob str c gt c charCodeAt baseToUint SGVsbGgVybGQ UintArray Convert a letter to associate emojiexport const letterToEmoji c string string gt String fromCodePoint c toLowerCase charCodeAt letterToEmoji a letterToEmoji b Convert a string to camelCaseexport const toCamelCase str string string gt str trim replace s g c gt c c toUpperCase toCamelCase background color backgroundColor toCamelCase webkit scrollbar thumb WebkitScrollbarThumb toCamelCase hello world HelloWorld toCamelCase hello world helloWorld Convert a string to PascalCaseexport const toPascalCase str string string gt str match a zA Z g map w gt w charAt toUpperCase w slice join toPascalCase hello world HelloWorld toPascalCase hello world HelloWorld toPascalCase foo bar baz FooBarBaz Convert a string to URL slugexport const slugify str string string gt str toLowerCase replace s g replace w g slugify Chapter One Once upon a time chapter one once upon a time Convert a Windows file path to Unix pathexport const toUnixPath path string string gt path replace g replace a zA Z toUnixPath foo bar baz foo bar baz toUnixPath C foo bar baz foo bar baz Convert an uint array to a base encoded stringexport const uintToBase arr UintArray string gt Buffer from arr toString base uintToBase UintArray from SGVsbGgVybGQ Convert camelCase to kebab case and vice versaexport const kebabToCamel str string string gt str replace g m gt m toUpperCase kebabToCamel background color backgroundColor export const camelToKebab str string string gt str replace a z A Z g toLowerCase camelToKebab backgroundColor background color Convert snake case to camelCaseexport const snakeToCamel str string string gt str toLowerCase replace w g m gt m toUpperCase substr snakeToCamel HELLO world helloWorld Count the occurrences of a character in a stringexport const countOccurrences str string char string number gt str filter item gt item char length countOccurrences a b c d e Format a stringexport const format str string vals string string gt vals reduce s v i gt s replace new RegExp i g v str const template My name is and I am years old format template John My name is John and I am years old format template Jane My name is Jane and I am years old Generate a hash of a stringexport const hash str string number gt str split reduce prev curr gt Math imul prev curr charCodeAt hash hello Get the base URL without any parametersexport const baseUrl url string string gt url split baseUrl hello world Get the number of a character in a stringexport const characterCount str string char string number gt str split char length characterCount characterCount star wars s Replace the first given number of characters of a string with another characterexport const mask str string num number mask string string gt str slice num padStart str length mask mask Uppercase the first character of each word in a stringexport const uppercaseWords str string string gt str replace s g c gt c toUpperCase uppercaseWords hello world Hello World |
2022-07-24 04:51:04 |
ニュース |
BBC News - Home |
Dover and Eurotunnel queues: Travellers warned of third day of delays |
https://www.bbc.co.uk/news/uk-62281443?at_medium=RSS&at_campaign=KARANGA
|
delaysanother |
2022-07-24 04:51:13 |
ニュース |
BBC News - Home |
World Athletics Championships: New-look GB team wins 4x100m relay bronze |
https://www.bbc.co.uk/sport/athletics/62281317?at_medium=RSS&at_campaign=KARANGA
|
World Athletics Championships New look GB team wins xm relay bronzeJona Efoloko and Reece Prescod help Britain to a spot on the podium in the xm relay final at the World Championships in Eugene |
2022-07-24 04:10:17 |
ニュース |
BBC News - Home |
Comic-Con: Boseman honoured as Black Panther: Wakanda Forever trailer unveiled |
https://www.bbc.co.uk/news/entertainment-arts-62281395?at_medium=RSS&at_campaign=KARANGA
|
black |
2022-07-24 04:09:32 |
北海道 |
北海道新聞 |
女子5000m、田中は12位 世界陸上、男子リレー決勝進出 |
https://www.hokkaido-np.co.jp/article/709536/
|
世界選手権 |
2022-07-24 13:37:00 |
北海道 |
北海道新聞 |
<筋トレで体いきいき>階段1段上り かがまずお尻伸ばす |
https://www.hokkaido-np.co.jp/article/709531/
|
階段 |
2022-07-24 13:10:00 |
コメント
コメントを投稿