30-seconds / 30-seconds-of-code Goto Github PK
View Code? Open in Web Editor NEWShort code snippets for all your development needs
Home Page: https://30secondsofcode.org/
License: Creative Commons Attribution 4.0 International
Short code snippets for all your development needs
Home Page: https://30secondsofcode.org/
License: Creative Commons Attribution 4.0 International
Current:
const isArray = val => val && Array.isArray(val);
// isArray(null) -> null (not false)
Use:
const isArray = val => !!val && Array.isArray(val);
// isArray(null) -> false
Thanks for putting this together, i've personally used a few (that took me some serious stackoverflow thread search time).
I'm a terrible developer, but i'm a curious guy. Coming from a design background, i'm more of a visual learner. Sometimes the english description might not be enough to understand some examples of this repo, as I could not understand some terms π€·ββοΈ
So my current flow is more or less like this:
So in relevant cases, would it be helpful for anyone else to include a usecase commented bellow like the filter-out-non-unique-values-in-an-array exemple?
const unique = arr => arr.filter(i => arr.indexOf(i) === arr.lastIndexOf(i));
// unique([1,2,2,3,4,4,5]) -> [1,3,5]
Props for this π , I might even submit a PR with a snippet one these days, who knows?!
Hi!
First of, thanks for this! It looks amazing and really helpful! π
I am just wondering why the convention is to use _
for functions with no parameters, instead of the official ()
:)?
I would like to change it, I could make a push request to change all occurances of it, if I just get a yes :)
Cheers in advance,
Erik
What about this kind of curry?
const curry = (fn, ...args) =>
fn.length <= args.length
? fn(...args)
: curry.bind(null, fn, ...args)
In reference to #120, where do we stand on Node.js snippets? I think we should get the tagging and categories working first before we add Node.js snippets, to distinguish from browser-specific ones. What do you guys think?
I wanted to know if there's a specific reason for not using TDD. I believe a light weight testing library like tape can provide a lot of value when trying to test code snippets. Especially snippets that are unresponsive or break when they come across edge cases
I believe having tests automated can also help the community test each snippet more rigorously and consistently before and after each PR
This is not a function really. It's just a tip on how to swap values of 2 variables. However, it is really useful for someone who is new to ES6 syntax.
Both @Chalarangelo and me think that 30-seconds-of-code should be consistent and focus only on functions and with that in mind swap values of two variables
doesn't really fit in here.
What do you think about the whole situation with it? Should we keep it?
Original version of pull snippet does not work. The following version works but returns a new array.
const Pull = (a, ...args) => { const s = new Set(args); return a.filter(x => !s.has(x)); };
let a = ["I", "see", "the", "present", "and", "the", "past"];
let v = Pull(a, "the", "and"); // ["I", "see", "present", "past"]
The splice
and concat
in a loop introduce O(N^2) solution.
Also, the current implementation has tricky side-effects. I'll address both things in a PR.
Hey All ππ
I honestly think this Project is in desperate need for a naming guide/convention. With the project goal being able to provide learners far and wide a peak into the inner workings of popular used code snippets. I believe it's appropriate for the snippets to be consistent so the time spent isn't focused on finding the exact snippet they are looking for.
Example ES^~JavaScript & Lodash & Underscore Follow a type of rules That help them with categorizing and naming their methods
As you can see even though they both return 2 different things. An Object and a String. Since they both accept array as inputs. They are categorized as Array methods
The reason I bring this up is because after a few minutes going through the snippets I realized
Example:
Use Array.reduce()
to create and combine key-value pairs.
const objectFromPairs = arr => arr.reduce((a, v) => (a[v[0]] = v[1], a), {});
// objectFromPairs([['a',1],['b',2]]) -> {a: 1, b: 2}
Is categorized as an Object method / snippet. Yet it takes an arr as input and strays from the standard way of doing things. Which might be weird for other users.
Some of these snippet/ method names are way too long
@Chalarangelo Thoughts?
I have no idea where did you get that format "/Date(timestamp)/", but
new Date().toJSON()
returns an ISO representation like 2017-12-16T18:16:36.514Z
Also instead of manually formatting a date, you can use toLocaleDateString, which is supported literally in every browser in its basic form.
const qs = (
[p, ...xs],
lesser = xs.filter(_ => _ <= p),
greater = xs.filter(_ => _ > p)
) => p ? [...qs(lesser), p, ...qs(greater)] : []
// qsort([20, 11, 2, 7, 89, -9, 34, 14, 0, 20]) -> [-9, 2, 7, 11, 14, 20, 20, 34, 89]
I saw this question pop up in Gitter, and while Gitter is a great place to chat, a documented approach to the decision should be used for such a wide reaching impact.
As it stands the guidelines don't contain any rules for handling errors. We should make sure that contributions know what they should do with errors. As I see it there are two possible ways forward(that are also non exclusive):
Maybe
Monad), that it should let the error bubbleBest practices state:
Errors, unless obvious to be handled at that scope, should always bubble to the place that called the handler. It is up to the developer to make sure they know what errors can happen and what to do with them. Often times it is actually in best interest to let a program fail on an Error being thrown if it would put the program into an unknown state, and being safe is ALWAYS better than being "stable"
The contribution guidelines should be updated so that people don't try to submit Maybe Monad
s without knowing what they're doing.
For those that don't know what a Maybe Monad
is:
const Maybe = fn => ( ...args ) => { try{ fn( ..args ) }catch( e ){ return; } } // returning null is also seen as correct, however in many cases a null may be a sought after value
Hey @elderhsouza Thanks again for the awesome log suggestion π & Hey All π
Category
Legend
file-name.md
~ Means PR has been merged & snippet has been implementedNote If a snippet does not have a PR attached. That means a PR wasn't created or referenced
Here's a list of the following snippets so far with their respective PR. Remember if there isn't a PR ref attached to a snippet it means no one has gotten around to it yet π Which also means there's work to be done & contributions to be made π» π―
Don't be shy and give it a try. Fork, Clone, Contribute, & Submit a PR π
Also shout out to @Chalarangelo for starting such an awesome project π
Follow the guidelines in CONTRIBUTING.md
No copy-pasting. Let's just try to have a fun and educative experience
Function
throttle.md
debounce.md
rearg.md
overArgs.md
collectInto.md
partial.md
partialRight.md
delay.md
bindKey.md
bind.md
ary.md
unary.md
negate.md
times.md
times.md
spreadOver.md
flip.md
curry.md
pipe.md
Util
attempt.md
bindAll.md
compose.md
composeRight.md
nthArg.md
over.md
matches.md
UUIDGeneratorBrowser.md
& UUIDGeneratorNode.md
initializeArrayWithRange.md
initializeArrayWithRangeRight.md
select.md
Array
pullBy.md
sortedIndexBy.md
sortedLastIndexBy.md
takeRightWhile.md
takeWhile.md
dropRightWhile.md
dropWhile.md
sortedLastIndex.md
intersectionBy.md
intersectionWith.md
unzipWith.md
unzip.md
unionBy.md
unionWith.md
symmetricDifferenceBy.md
symmetricDifferenceWith.md
differenceBy.md
differenceWith .md
zipWith.md
symmetricDifference.md
pull.md
pullAtIndex.md
pull.md
remove.md
without.md
takeRight.md
zip.md
intersection.md
flatten-array-up-to-depth.md
nth-element-of-array.md
drop.md
flatten-array.md
deep-flatten-array.md
union.md
chunk.md
compact.md
difference.md
head.md
objectFromPairs.md
last.md
initial.md
tail.md
take.md
zipObject
is sufficient for most use-casesLang
castArray.md
deepClone.md
matches.md
matchesWith.md
isObjectLike.md
isEmpty.md
isPlainObject.md
isUndefined .md
is.md
is.md
is.md
is.md
isNil.md
is .md
is .md
is .md
is .md
is .md
is .md
is.md
toSafeInteger.md
isPrimitive.md
shallowClone.md
isArray.md
isBoolean.md
isFunction.md
isNumber.md
isString.md
isSymbol.md
Object
findKey.md
findLastKey.md
defaults.md
omitBy.md
pickBy.md
omit.md
get.md
merge.md
transform.md
functions.md
functions.md
mapKeys.md
mapValues.md
select.md
pick.md
invertKeyValues.md
invertKeyValues.md
objectToPairs.md
Collection
findLast.md
countBy.md
groupBy.md
forEachRight.md
groupBy.md
orderBy.md
sample.md
shuffle.md
orderBy.md
Math
maxBy.md
minBy.md
averageBy.md
sumBy.md
arraySum.md
arrayMax.md
arrayAverage.md
String
decapitalize.md
escapeHTML.md
unescapeHTML.md
toKebabCase.md
words.md
escapeRegExpmd
toCamelCase.md
capitalizeEveryWord.md
capitalize.md
truncate.md
Number
clampNumber.md
inRange.md
randomNumberInRange.md
Date
Why is factorial snippet handling negative numbers? I do not think factorial for negative numbers is defined.
Snippet from factorial.md :
const factorial = n => n <= 1 ? 1 : n * factorial(n - 1);
Why do we need that extra !!
?
[false, null, undefined, NaN, 0, ''].filter(Array.isArray)
is empty, no falsy value is considered as an array
Maybe, I can create a PR with several such small changes instead of writing about every separately?
@Chalarangelo suggested opening an issue for the wrong categorization so here it is! Let's discuss what functions need to switch categories.
Wanted to gauge interest before creating a PR. Would others consider this clear & useful?
const round = (n, decimals = 0) => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`)
Importantly the above works correctly with all floating point numbers.
// All of the following *should* return 1.01 but *actually* return 1
Number(1.005.toFixed(2))
Math.round(1.005 * 100) / 100
john wolfe filter x 137,953 ops/sec Β±0.65% (88 runs sampled)
current filter x 100,221 ops/sec Β±1.02% (86 runs sampled)
Fastest is john wolfe filter
The current snippets are designed to be short/brief, but at the cost of sacrificing legibility. For example, the first snippet is:
arrayMax
Returns the maximum value in an array.
Use Math.max() combined with the spread operator (...) to get the maximum value in the array.
const arrayMax = arr => Math.max(...arr);` // arrayMax([10, 1, 5]) -> 10
I noticed when copy/pasting, the comments kinda got in the way. Ideally, you'd want to separate the definition and the usage.
Additionally, the description is a bit lackluster. Why is the spread operator and Math.max() being used? If you know how it works, then it's obvious, but to new developers reading the code they probably don't know what's happening.
I suggest you keep the what
of the function at the top, then add a comprehensive how
beneath.
Returns the maximum value in an array.
const arrayMax = arr => Math.max(...arr);
arrayMax([10, 5, -2, 11, 0]); // 11
Math.max()
returns the largest value given to it, accepting each value as a separate argument. For example, Math.max(1, 5, 3, 0)
returns 5
. However, it doesn't take an array of values - they must be supplied as separate arguments.
To find the largest value of an array, we can use the spread ...
operator.
Math.max(...[1, 5, 3, 0])
is the same as Math.max(1, 5, 3, 0)
. The spread operator "spreads" the values of the array into the function as separate arguments, which returns the largest value, thus returning the largest value of an array.
The clear downside of this is decreased information density. Ideally you'd have the usage and explanation collapsed, only to be expanded if necessary, but that's not possible(?) with MD. But it seems like a perfect opportunity for the website. But then you have 2 different versions π
Thoughts/ideas?
Why array reduced is used?
const remove = (arr, func) => Array.isArray(arr) ? arr.filter(func).reduce((acc, val) => { arr.splice(arr.indexOf(val), 1); return acc.concat(val); }, []) : [];
as we can get the same result using this
const remove = (arr, func) => Array.isArray(arr) ? arr.filter(func) : [];
Can anyone please answer this?
console.log... ah how we both love an hate you.
Realistically you might not want to use console.log unless you want stdout/1
to see the text. There are other console channels that exist for that exact purpose on console. Since this is more of a debugging tool you'd want to remove from code before pushing, it might also be better to be able to bypass it.
Marking as an issue for coding later when I'm off work π
When the color value is 3 digits, incorrect results
const hexToRgb = hex => {
const h = parseInt(hex.slice(1), 16);
return `rgb(${h >> 16}, ${(h & 0x00ff00) >> 8}, ${h & 0x0000ff})`;
}
// hexToRgb('#27ae60') -> 'rgb(39, 174, 96)'
// hexToRgb('#acd') -> 'rgb(0, 10, 205)'
#acd
== #aaccdd
:
wrong: rgb(0, 10, 205)
correct: rgb(170, 208, 221)
const getRgb = hex => {
let _hex = hex.slice(1)
let h
if(_hex.length === 3) {
for (let i of _hex) {
h += i.repeat(2)
}
h = parseInt(h.slice(9), 16)
} else {
h = parseInt(_hex, 16)
}
return `rgb(${h >> 16}, ${(h & 0x00ff00) >> 8}, ${h & 0x0000ff})`
}
// getRgb('#acd') -> 'rgb(170, 208, 221)'
This snippet might fit into the list?
const promisify = func =>
(...args) =>
new Promise((resolve, reject) =>
func(...args, (err, result) =>
err
? reject(err)
: resolve(result))
)
Hey all!
The project is looking great! We now believe that the idea is trying to demistify and get really deep into the implementation of commonly used snippets.
We think that we can look to really popular libs like lodash for example and try to implement some of the utilities by hand, no copy-pasting, just to have a fun and educative experience.
Here's a list of suggestions of utilities we could implement next:
https://lodash.com/docs/4.17.4#groupBy
https://lodash.com/docs/4.17.4#orderBy
https://lodash.com/docs/4.17.4#pick
https://lodash.com/docs/4.17.4#endsWith
Flatten now works in O(N^2), because of constantly re-creating and copying already accumulated part.
const flatten = arr => [].concat(...arr)
is much faster on larger arrays.
This implementation is subjected to StackOverflow if original array contains tens of thousands items.
This is the snippet I created once, but someone has rewritten it wrongly.
extendHex(
03f)
should return #0033ff
, but currently returns #03f03f
.
The problem was here:
shortHex.slice(shortHex.startsWith('#') ? 1 : 0).split().map(x => x+x).join()
but should be
shortHex.slice(shortHex.startsWith('#') ? 1 : 0).split('').map(x => x+x).join('')
Is fixed in my PR #224
Value or default
when value is 0, this function will return default value
Should not the difference be verified on both sides?
// difference([1,2,3], [1,2]) -> [3]
// or
// difference([1,2], [1,2, 3]) -> [3]
With current implementation, the tail
function for a single value array will be empty []
instead of that single value array.
So I think it should be something like this maybe?
var tail = arr => arr.length > 1 ? arr.slice(1) : arr;
Day by day there are more snippets created which in future will led to unclassified structure. When user wants to search a snippet of specific area/category, then he/she would come across major data repository.
See there are many ways to categorize these snippets by looking code, we might think the main area which it lies in.
Provided Example :
This would lead to classified structure consisting all areas with their sub-repositories. When user comes to visit README.md
file, then it will be easy to search snippet falling in to respective category.
const ArrayConcat = (arr, ...args) => arr.concat(...args);
is useless in the sense that it's not doing any valuable work, it's wrapping a function, leaving the exact same behaviour. Array.concat()
doesn't mutate the array.
Also, the example result is wrong.
I can't create a pull atm, but I went through the README.
const deepFlatten = arr =>
arr.reduce( (a, v) => a.concat( Array.isArray(v) ? flatten(v) : v ), []);
flatten
should be deepFlatten
const last = arr => arr[arr.length - 1];
Why not use this instead of .slice(-1)[0]
?
const randomIntegerInRange = (min, max) =>
Math.floor(Math.random() * (max - min + 1)) + min;
const median = numbers => {
const midpoint = Math.floor(numbers.length / 2)
const sorted = numbers.sort((a, b) => a - b)
return numbers.length % 2
? sorted[midpoint]
: (sorted[midpoint - 1] + sorted[midpoint]) / 2
}
But it seems that I cant submit a pull request. Can I join the gang? ;)
"You may not have permission to access 30-seconds-of-code."
Some of you might have noticed, we now have a website on Github pages. It's far from complete, but I want to list here what needs to be added/done, so someone can start playing around with it.
First and foremost, as with the README file, never touch the index.html file, unless the changes in it come from a build process (described below). Modify its static parts or script.
Remember, that you can rebuild the website after applying changes to the script or static files, by running npm run webber
.
there is a error in the method of bottomVisible.
it should be document.body.clientHeight
, not document.documentElement.clientHeight
const bottomVisible = () => {
return (document.documentElement.clientHeight + window.scrollY) >= (document.documentElement.scrollHeight || document.body.clientHeight)}
```
Hi!
The compact() function can be written more simply, by using the Boolean
function.
const compact = (arr) => arr.filter(v => v);
const compact2 = (arr) => arr.filter(Boolean); // simpler
console.log(compact([0, 1, false, 2, '', 3, 'a', 'e'*23, NaN, 's', 34])) // [ 1, 2, 3, 'a', 's', 34 ]
console.log(compact2([0, 1, false, 2, '', 3, 'a', 'e'*23, NaN, 's', 34])) // [ 1, 2, 3, 'a', 's', 34 ]
doesn't appear to produce the results you intended:
https://jsfiddle.net/8tdu8q5p/
We could maybe consider that if we call capitalize on a string, we expect the first letter to be uppercase but the rest to be in lowercase ?
I suggest we could add it as follows:
var capitalize = str => str[0].toUpperCase() + str.slice(1).toLowerCase();
or with a default option as follows:
var capitalize = (str, lowerRest=true) => str[0].toUpperCase() + (lowerRest ? str.slice(1).toLowerCase() : str.slice(1));
Object.assign({},objToClone)
ES6 allows easy shallow cloning objects with Object.assign which also allows for MULTIPLE combining
Object.assing({}, null, a,b,c) // object with props from a, b, and c
Should be put in a more robust version?
const shallowClone = (...objs) => Object.assign({}, ...objs)
Or remove it since now it's part of spec?
(''+[1,[2],[[3],4],5]).split(',').map(x=>+x)
-->[1, 2, 3, 4, 5]
Validate number
Use !isNaN in combination with parseFloat() to check if the argument is a number. Use isFinite() to check if the number is finite.
const validateNumber = n => !isNaN(parseFloat(n)) && isFinite(n);
// validateNumber('10') -> true
According to the MDN documentation, isFinite()
returns "false
if the argument is positive or negative Infinity
or NaN
; otherwise, true
".
isFinite(Infinity); // false
isFinite(NaN); // false
isFinite(-Infinity); // false
isFinite(0); // true
isFinite(2e64); // true
isFinite(910); // true
isFinite(null); // true, would've been false with the
// more robust Number.isFinite(null)
isFinite('0'); // true, would've been false with the
// more robust Number.isFinite("0")
So technically, the !isNan()
isn't required and you could shorten your validateNumber
:
const validateNumber = n => isFinite(n);
// validateNumber('10') -> true
I think that enforcing a coding standard would benefit this project by bringing consistency and readability of the project.
I believe using a syntax enforcer such as XO or even custom ESLint settings would bring consistency to the scripts before pull requests. Another option would simply be to use a syntax formatted such as Prettier to format all code when building. It would also help readability since newlines etc. would be formalised.
For example, var
is usually discouraged when writing ES6. When only one parameter is used in an arrow function, it is sometimes recommended to be written as x => f(x)
and not (x) => f(x)
etc.
The simplest option is using a formatter, since it would only need a change in builder.js
and wonβt require contributors to follow the wanted format. XO or ESLint however would rather aid the contributors to follow a certain format and perhaps teach them a thing or two about following a coding standard.
Are these thoughts solely my own or is this something that others think would help the project?
The array method of dropElements seems that can not get correct result as the array is unordered.
like this: dropElements([4, 2, 3, 4, 5], n=> n>=3) -> [4,2,3,4,5 ]
so
const dropElements = (arr, func) => {
arr.sort();
....
}```
is better
Right now there are inconsistencies when referencing Array
methods, like reduce()
, in snippet descriptions. Sometimes they are referenced as Array.reduce()
and other times as reduce()
. The preferred option would be to refer to them as Array.reduce()
, so if anyone can get to that and fix it, I would appreciate it.
(Methods that need to be dealt with right not are sort()
, map()
, reduce()
- I think these are all, but I might be forgetting something).
I tested, the correct string is ([^?=&]+)(=([^&])), no ([^?=&]+)(=([^&]))?
Am i wrong?
First, thanks for your share, I have a question about Array concatenation
.
When i run it in chrome console:
const ArrayConcat = (arr, ...args) => [...arr,...args];
ArrayConcat([1], [1, 2, 3, [4]])
// The answer is => [1, [1, 2, 3, [4]]];
// This is different from the document. -_-
// see the print
const AC = (arr, ...args) => {
console.log(arr, args);
};
AC([1], [1, 2, 3, [4]]); // [1] [[1, 2, 3, [4]]]
AC([1], [1, 2, 3, [4]], [5, 6]); // [1] [[1, 2, 3, [4]], [5, 6]]
Is anything wrong with me?
https://github.com/Chalarangelo/30-seconds-of-code#number-to-array-of-digits
//first code
const digitize = n => (''+n).split('').map(i => parseInt(i));
// digitize(2334) -> (4) [2, 3, 3, 4]
//second code
const digitize = n => (''+n).split('').map(i => parseInt(i));
// digitize(2,3,3,4) -> [2] 0:2
So here's the bug where user wants to input in separated manner with ',' then function will not work. Also in first code, user wants to insert multiple values which has more than two digits then,
digitize(23,232,3424);
//(4) [2, 3, 3, 4]
So definitely depends how user inputs. So we should write in desc. that user should enter input in specific manner so that it returns as pure
This is potentially a serious problem.
While talking with @Chalarangelo, we agreed that naming should be consistent. The main idea behind this issue is to fix naming across the whole project. Let me explain the idea:
Most of the functions have the different name than their .md file has. For example initial()
is located inside the initial-of-list.md
. We need to use the same name for both function name and snippet.md name.
Most of the functions have names that don't precisely describe what they do and that should be changed. In my opinion, loadash has good naming for their functions. You can exactly tell what each function does just by looking at the name of that function.
Before changing the naming of snippet files, change the function names first to the name that describes more precisely what it does. Later on, someone will PR all snippet names that need change.
[].fill([1,2,3,4],'8',1,3)
A declarative, efficient, and flexible JavaScript library for building user interfaces.
π Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. πππ
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google β€οΈ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.