1677653700
プロのようにコーディングするのに役立つ 15 以上の JavaScript ワンライナーについて学びます。生産性を高め、コードのデバッグに役立つ JavaScript に関するいくつかのすばらしいヒントとコツ。
JavaScript は、最も人気のあるプログラミング言語の 1 つです。Web サイト、Web アプリケーション、Web サーバー、ゲーム、モバイル アプリなどの開発に使用されます。JavaScript の構文、特に匿名関数とアロー関数により、簡潔なコードが可能になります。たった 1 行のコードで多くのことを実現できます。このチュートリアルでは、プロのようにコーディングするのに役立つ 15 以上の JavaScript ワンライナーについて学習します。
この関数は、Math.random() メソッドを使用してブール値 (true または false) を返します。Math.random は 0 と 1 の間の乱数を作成し、その後、0.5 より大きいか小さいかを確認します。つまり、true または false になる確率は 50/50 です。
const getRandomBoolean = () => Math.random() >= 0.5;
console.log(getRandomBoolean());
// a 50/50 chance of returning true or false
この機能により、指定された日付が平日か週末かを確認できます。
const isWeekend = (date) => [0, 6].indexOf(date.getDay()) !== -1;
console.log(isWeekend(new Date(2021, 4, 14)));
// false (Friday)
console.log(isWeekend(new Date(2021, 4, 15)));
// true (Saturday)
数値が偶数か奇数かを調べる単純なユーティリティ関数。
const isEven = (num) => num % 2 === 0;
console.log(isEven(5));
// false
console.log(isEven(4));
// true
配列からすべての重複値を削除する非常に簡単な方法。この関数は、配列を Set に変換してから配列に戻します。
const uniqueArr = (arr) => [...new Set(arr)];
console.log(uniqueArr([1, 2, 3, 1, 2, 3, 4, 5]));
// [1, 2, 3, 4, 5]
変数が配列かどうかを確認するクリーンで簡単な方法。
まあ、他の方法もあるかもしれませんね😉
const isArray = (arr) => Array.isArray(arr);
console.log(isArray([1, 2, 3]));
// true
console.log(isArray({ name: 'Ovi' }));
// false
console.log(isArray('Hello World'));
// false
これはパラメータとして 2 つの数値を取り、それらの 2 つの数値の間で乱数を生成します!
const random = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);
console.log(random(1, 50));
// could be anything from 1 - 50
何かのために一時的な一意の ID を作成する必要があるかもしれません。外出先でランダムな文字列を生成するために使用できるトリックを次に示します。
const randomString = () => Math.random().toString(36).slice(2);
console.log(randomString());
// could be anything!!!
window.scrollTo ()メソッドは、スクロール先のx座標とy座標を取ります。これらをゼロとゼロに設定すると、ページの上部までスクロールします。
const scrollToTop = () => window.scrollTo(0, 0);
scrollToTop();
ブール値の切り替えは、さまざまな方法で解決できる非常に基本的なプログラミングの問題の 1 つです。if ステートメントを使用してブール値を設定する値を決定する代わりに、関数を使用して、! 「ない」演算子。
// bool is stored somewhere in the upperscope
const toggleBool = () => (bool = !bool);
以下のコードは、3 番目の変数を使用せずに 1 行のコードで 2 つの変数を交換する簡単な方法の 1 つです。
[foo, bar] = [bar, foo];
2 つの日付間の日数を計算するには、まず 2 つの日付間の絶対値を求め、それを 1 日のミリ秒に等しい 86400000 で割ります。最後に、結果を四捨五入して返します。
const daysDiff = (date, date2) => Math.ceil(Math.abs(date - date2) / 86400000);
console.log(daysDiff(new Date('2021-05-10'), new Date('2021-11-25')));
// 199
PS: navigator.clipboard.writeText が存在するかどうかを確認するチェックを追加する必要がある場合があります
const copyTextToClipboard = async (text) => {
await navigator.clipboard.writeText(text);
};
配列をマージするには、いくつかの方法があります。それらの 1 つは、「concat」メソッドを使用することです。もう 1 つは、拡散演算子 ("...") を使用しています。
PS: 「Set」オブジェクトを使用して、最終的な配列から複製することもできます。
// Merge but don't remove the duplications
const merge = (a, b) => a.concat(b);
// Or
const merge = (a, b) => [...a, ...b];
// Merge and remove the duplications
const merge = [...new Set(a.concat(b))];
// Or
const merge = [...new Set([...a, ...b])];
JavaScript で何かの実際の型を見つけるためにライブラリを使用することがありますが、この小さなトリックにより、時間 (およびコード サイズ) を節約できます。
const trueTypeOf = (obj) => {
return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();
};
console.log(trueTypeOf(''));
// string
console.log(trueTypeOf(0));
// number
console.log(trueTypeOf());
// undefined
console.log(trueTypeOf(null));
// null
console.log(trueTypeOf({}));
// object
console.log(trueTypeOf([]));
// array
console.log(trueTypeOf(0));
// number
console.log(trueTypeOf(() => {}));
// function
文字列を最後から切り詰める必要がありますが、問題ありません!
const truncateString = (string, length) => {
return string.length < length ? string : `${string.slice(0, length - 3)}...`;
};
console.log(
truncateString('Hi, I should be truncated because I am too loooong!', 36),
);
// Hi, I should be truncated because...
文字列を途中から切り捨てたらどうですか?
この関数は、最初のパラメーターとして文字列を受け取り、次に必要な文字列のサイズを 2 番目の引数として受け取り、3 番目と 4 番目のパラメーターで最初と最後から必要な文字数を受け取ります。
const truncateStringMiddle = (string, length, start, end) => {
return `${string.slice(0, start)}...${string.slice(string.length - end)}`;
};
console.log(
truncateStringMiddle(
'A long story goes here but then eventually ends!', // string
25, // total size needed
13, // chars to keep from start
17, // chars to keep from end
),
);
// A long story ... eventually ends!
残念ながら、JavaScript には文字列を大文字にする組み込み関数がありませんが、この回避策を使用すると目的を達成できます。
const capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1);
console.log(capitalize('hello world'));
// Hello world
この単純なヘルパー メソッドは、タブがビュー/フォーカスされているかどうかに応じて true または false を返します。
const isTabInView = () => !document.hidden; // Not hidden
isTabInView();
// true/false
ユーザーがAppleデバイスを使用している場合、これはtrueを返します
const isAppleDevice = () => /Mac|iPod|iPhone|iPad/.test(navigator.platform);
console.log(isAppleDevice);
// true/false
これは、 if..elseステートメントを 1 行で記述したい場合に、コードを大幅に節約します。
// Longhand
const age = 18;
let greetings;
if (age < 18) {
greetings = 'You are not old enough';
} else {
greetings = 'You are young!';
}
// Shorthand
const greetings = age < 18 ? 'You are not old enough' : 'You are young!';
変数値を別の変数に代入する場合、ソース変数が null、未定義、または空でないことを確認したい場合があります。複数の条件付きの長いifステートメントを記述するか、短絡評価を使用することができます。
// Longhand
if (name !== null || name !== undefined || name !== '') {
let fullName = name;
}
// Shorthand
const fullName = name || 'buddy';
#javascript
1622207074
Who invented JavaScript, how it works, as we have given information about Programming language in our previous article ( What is PHP ), but today we will talk about what is JavaScript, why JavaScript is used The Answers to all such questions and much other information about JavaScript, you are going to get here today. Hope this information will work for you.
JavaScript language was invented by Brendan Eich in 1995. JavaScript is inspired by Java Programming Language. The first name of JavaScript was Mocha which was named by Marc Andreessen, Marc Andreessen is the founder of Netscape and in the same year Mocha was renamed LiveScript, and later in December 1995, it was renamed JavaScript which is still in trend.
JavaScript is a client-side scripting language used with HTML (Hypertext Markup Language). JavaScript is an Interpreted / Oriented language called JS in programming language JavaScript code can be run on any normal web browser. To run the code of JavaScript, we have to enable JavaScript of Web Browser. But some web browsers already have JavaScript enabled.
Today almost all websites are using it as web technology, mind is that there is maximum scope in JavaScript in the coming time, so if you want to become a programmer, then you can be very beneficial to learn JavaScript.
In JavaScript, ‘document.write‘ is used to represent a string on a browser.
<script type="text/javascript">
document.write("Hello World!");
</script>
<script type="text/javascript">
//single line comment
/* document.write("Hello"); */
</script>
#javascript #javascript code #javascript hello world #what is javascript #who invented javascript
1616670795
It is said that a digital resource a business has must be interactive in nature, so the website or the business app should be interactive. How do you make the app interactive? With the use of JavaScript.
Does your business need an interactive website or app?
Hire Dedicated JavaScript Developer from WebClues Infotech as the developer we offer is highly skilled and expert in what they do. Our developers are collaborative in nature and work with complete transparency with the customers.
The technology used to develop the overall app by the developers from WebClues Infotech is at par with the latest available technology.
Get your business app with JavaScript
For more inquiry click here https://bit.ly/31eZyDZ
Book Free Interview: https://bit.ly/3dDShFg
#hire dedicated javascript developers #hire javascript developers #top javascript developers for hire #hire javascript developer #hire a freelancer for javascript developer #hire the best javascript developers
1589255577
As a JavaScript developer of any level, you need to understand its foundational concepts and some of the new ideas that help us developing code. In this article, we are going to review 16 basic concepts. So without further ado, let’s get to it.
#javascript-interview #javascript-development #javascript-fundamental #javascript #javascript-tips
1626321063
PixelCrayons: Our JavaScript web development service offers you a feature-packed & dynamic web application that effectively caters to your business challenges and provide you the best RoI. Our JavaScript web development company works on all major frameworks & libraries like Angular, React, Nodejs, Vue.js, to name a few.
With 15+ years of domain expertise, we have successfully delivered 13800+ projects and have successfully garnered 6800+ happy customers with 97%+ client retention rate.
Looking for professional JavaScript web app development services? We provide custom JavaScript development services applying latest version frameworks and libraries to propel businesses to the next level. Our well-defined and manageable JS development processes are balanced between cost, time and quality along with clear communication.
Our JavaScript development companies offers you strict NDA, 100% money back guarantee and agile/DevOps approach.
#javascript development company #javascript development services #javascript web development #javascript development #javascript web development services #javascript web development company
1670062320
I’m a huge fan of automation when the scenario allows for it. Maybe you need to keep track of guest information when they RSVP to your event, or maybe you need to monitor and react to feeds of data. These are two of many possible scenarios where you probably wouldn’t want to do things manually.
There are quite a few tools that are designed to automate your life. Some of the popular tools include IFTTT, Zapier, and Automate. The idea behind these services is that given a trigger, you can do a series of events.
In this tutorial, we’re going to see how to collect Twitter data with Zapier, store it in MongoDB using a Realm webhook function, and then run aggregations on it using the MongoDB query language (MQL).
There are a few requirements that must be met prior to starting this tutorial:
There is a Zapier free tier, but because we plan to use webhooks, which are premium in Zapier, a paid account is necessary. To consume data from Twitter in Zapier, a Twitter account is necessary, even if we plan to consume data that isn’t related to our account. This data will be stored in MongoDB, so a cluster with properly configured IP access and user permissions is required.
You can get started with MongoDB Atlas by launching a free M0 cluster, no credit card required.
While not necessary to create a database and collection prior to use, we’ll be using a zapier database and a tweets collection throughout the scope of this tutorial.
Since the plan is to store tweets from Twitter within MongoDB and then create queries to make sense of it, we should probably get an understanding of the data prior to trying to work with it.
We’ll be using the “Search Mention” functionality within Zapier for Twitter. Essentially, it allows us to provide a Twitter query and trigger an automation when the data is found. More on that soon.
As a result, we’ll end up with the following raw data:
{
"created_at": "Tue Feb 02 20:31:58 +0000 2021",
"id": "1356701917603238000",
"id_str": "1356701917603237888",
"full_text": "In case anyone is interested in learning about how to work with streaming data using Node.js, I wrote a tutorial about it on the @MongoDB Developer Hub. https://t.co/Dxt80lD8xj #javascript",
"truncated": false,
"display_text_range": [0, 188],
"metadata": {
"iso_language_code": "en",
"result_type": "recent"
},
"source": "<a href='https://about.twitter.com/products/tweetdeck' rel='nofollow'>TweetDeck</a>",
"in_reply_to_status_id": null,
"in_reply_to_status_id_str": null,
"in_reply_to_user_id": null,
"in_reply_to_user_id_str": null,
"in_reply_to_screen_name": null,
"user": {
"id": "227546834",
"id_str": "227546834",
"name": "Nic Raboy",
"screen_name": "nraboy",
"location": "Tracy, CA",
"description": "Advocate of modern web and mobile development technologies. I write tutorials and speak at events to make app development easier to understand. I work @MongoDB.",
"url": "https://t.co/mRqzaKrmvm",
"entities": {
"url": {
"urls": [
{
"url": "https://t.co/mRqzaKrmvm",
"expanded_url": "https://www.thepolyglotdeveloper.com",
"display_url": "thepolyglotdeveloper.com",
"indices": [0, 23]
}
]
},
"description": {
"urls": ""
}
},
"protected": false,
"followers_count": 4599,
"friends_count": 551,
"listed_count": 265,
"created_at": "Fri Dec 17 03:33:03 +0000 2010",
"favourites_count": 4550,
"verified": false
},
"lang": "en",
"url": "https://twitter.com/227546834/status/1356701917603237888",
"text": "In case anyone is interested in learning about how to work with streaming data using Node.js, I wrote a tutorial about it on the @MongoDB Developer Hub. https://t.co/Dxt80lD8xj #javascript"
}
The data we have access to is probably more than we need. However, it really depends on what you’re interested in. For this example, we’ll be storing the following within MongoDB:
{
"created_at": "Tue Feb 02 20:31:58 +0000 2021",
"user": {
"screen_name": "nraboy",
"location": "Tracy, CA",
"followers_count": 4599,
"friends_count": 551
},
"text": "In case anyone is interested in learning about how to work with streaming data using Node.js, I wrote a tutorial about it on the @MongoDB Developer Hub. https://t.co/Dxt80lD8xj #javascript"
}
Without getting too far ahead of ourselves, our analysis will be based off the followers_count
and the location
of the user. We want to be able to make sense of where our users are and give priority to users that meet a certain followers threshold.
Before we start connecting Zapier and MongoDB, we need to develop the middleware that will be responsible for receiving tweet data from Zapier.
Remember, you’ll need to have a properly configured MongoDB Atlas cluster.
We need to create a Realm application. Within the MongoDB Atlas dashboard, click the Realm tab.
For simplicity, we’re going to want to create a new application. Click the Create a New App button and proceed to fill in the information about your application.
From the Realm Dashboard, click the 3rd Party Services tab.
We’re going to want to create an HTTP service. The name doesn’t matter, but it might make sense to name it Twitter based on what we’re planning to do.
Because we plan to work with tweet data, it makes sense to call our webhook function tweet, but the name doesn’t truly matter.
With the exception of the HTTP Method, the defaults are fine for this webhook. We want the method to be POST because we plan to create data with this particular webhook function. Make note of the Webhook URL because it will be used when we connect Zapier.
The next step is to open the Function Editor so we can add some logic behind this function. Add the following JavaScript code:
exports = function (payload, response) {
const tweet = EJSON.parse(payload.body.text());
const collection = context.services.get("mongodb-atlas").db("zapier").collection("tweets");
return collection.insertOne(tweet);
};
In the above code, we are taking the request payload, getting a handle to the tweets collection within the zapier database, and then doing an insert operation to store the data in the payload.
There are a few things to note in the above code:
When we call our function, a new document should be created within MongoDB.
By default, the function will not deploy when saving. After saving, make sure to review and deploy the changes through the notification at the top of the browser window.
So, we know the data we’ll be working with and we have a MongoDB Realm webhook function that is ready for receiving data. Now, we need to bring everything together with Zapier.
For clarity, new Twitter matches will be our trigger in Zapier, and the webhook function will be our event.
Within Zapier, choose to create a new “Zap,” which is an automation. The trigger needs to be a Search Mention in Twitter, which means that when a new Tweet is detected using a search query, our events happen.
For this example, we’re going to use the following Twitter search query:
url:developer.mongodb.com -filter:retweets filter:safe lang:en -from:mongodb -from:realm
The above query says that we are looking for tweets that include a URL to developer.mongodb.com. The URL doesn’t need to match exactly as long as the domain matches. The query also says that we aren’t interested in retweets. We only want original tweets, they have to be in English, and they have to be detected as safe for work.
In addition to the mentioned search criteria, we are also excluding tweets that originate from one of the MongoDB accounts.
In theory, the above search query could be used to see what people are saying about the MongoDB Developer Hub.
With the trigger in place, we need to identify the next stage of the automation pipeline. The next stage is taking the data from the trigger and sending it to our Realm webhook function.
As the event, make sure to choose Webhooks by Zapier and specify a POST request. From here, you’ll be prompted to enter your Realm webhook URL and the method, which should be POST. Realm is expecting the payload to be JSON, so it is important to select JSON within Zapier.
We have the option to choose which data from the previous automation stage to pass to our webhook. Select the fields you’re interested in and save your automation.
The data I chose to send looks like this:
{
"created_at": "Tue Feb 02 20:31:58 +0000 2021",
"username": "nraboy",
"location": "Tracy, CA",
"follower_count": "4599",
"following_count": "551",
"message": "In case anyone is interested in learning about how to work with streaming data using Node.js, I wrote a tutorial about it on the @MongoDB Developer Hub. https://t.co/Dxt80lD8xj #javascript"
}
The fields do not match the original fields brought in by Twitter. It is because I chose to map them to what made sense for me.
When deploying the Zap, anytime a tweet is found that matches our query, it will be saved into our MongoDB cluster.
With tweet data populating in MongoDB, it’s time to start querying it to make sense of it. In this fictional example, we want to know what people are saying about our Developer Hub and how popular these individuals are.
To do this, we’re going to want to make use of an aggregation pipeline within MongoDB.
Take the following, for example:
[
{
"$addFields": {
"follower_count": {
"$toInt": "$follower_count"
},
"following_count": {
"$toInt": "$following_count"
}
}
}, {
"$match": {
"follower_count": {
"$gt": 1000
}
}
}, {
"$group": {
"_id": {
"location": "$location"
},
"location": {
"$sum": 1
}
}
}
]
There are three stages in the above aggregation pipeline.
We want to understand the follower data for the individual who made the tweet, but that data comes into MongoDB as a string rather than an integer. The first stage of the pipeline takes the follower_count
and following_count
fields and converts them from string to integer. In reality, we are using $addFields
to create new fields, but because they have the same name as existing fields, the existing fields are replaced.
The next stage is where we want to identify people with more than 1,000 followers as a person of interest. While people with fewer followers might be saying great things, in this example, we don’t care.
After we’ve filtered out people by their follower count, we do a group based on their location. It might be valuable for us to know where in the world people are talking about MongoDB. We might want to know where our target audience exists.
The aggregation pipeline we chose to use can be executed with any of the MongoDB drivers, through the MongoDB Atlas dashboard, or through the CLI.
You just saw how to use Zapier with MongoDB to automate certain tasks and store the results as documents within the NoSQL database. In this example, we chose to store Twitter data that matched certain criteria, later to be analyzed with an aggregation pipeline. The automations and analysis options that you can do are quite limitless.
If you enjoyed this tutorial and want to get engaged with more content and like-minded developers, check out the MongoDB Community.
This content first appeared on MongoDB.
Original article source at: https://www.thepolyglotdeveloper.com/