海外TECH |
DEV Community |
Javascript loops: for vs forEach vs for.. in vs for.. of |
https://dev.to/smpnjn/javascript-loops-for-vs-foreach-vs-for-in-vs-for-of-1mbo
|
Javascript loops for vs forEach vs for in vs for ofThere are quite a few ways in Javascript to loop through an array of items or any other iterable item in Javascript You may have seen them arr forEach for let item of arr for let item in arr for let item item lt arr length item This may seem like a lot of ways to accomplish the same thing but they all have their own nuance For any of these to work the item in question also needs to be iterable So while they will work with things like Map Set and Arrays they will not work with Objects Strings are also iterable Since there are so many ways it can be confusing when to use forEach in or of in Javascript Today let s understand in detail what each of these does and when to use them The forEach MethodforEach is a tool many are drawn to because linguistically it makes sense arr forEach sounds right and it provides an easy callback function to do whatever we want to do with each item in an iterable like an array let x x forEach item index gt x index console log x However forEach is a method which means that it only appears on certain data types in Javascript For example all Arrays have a forEach method and so do Maps and Sets but despite being iterable Strings do not Notably DOM elements didn t have forEach until recently So while it is reliably available in many different circumstances It is also much slower than a regular old for loop Beyond that forEach does not really work with async methods like await or promises either In circumstances where you need to use promises or await its best to avoid it and use for loops instead While forEach is definitely an easy way to iterate over an array it s not always the best Using for loops on iterablesThere are three types of for loops to run over iterables in Javascript for let item of arr for let item in arr for let item item lt arr length item For those new to the language the syntax can seem quite confusing When Javascript first started out the original for loop everyone used was the last one listed above let x for let i i lt x length i console log x i This is an easy straight forward way of accessing the index of an array Here i starts at and increases for each item in the array x Therefore i reliably represents the index for each item and thus writing x i will let us do something with each item in the array Since then two new types of for loop have been introduced in and of in vs of in Javascript for loopsThe best way to understand in and of in Javascript for loops is that in is a simplification of the for loop we just looked at It is an easier way to access the index in an array Meanwhile of is an easy way to represent the array item itself Let s look at a quick example Here we get the index of each item in our array using in let x for let i in x console log i Meanwhile if we use of it gets the actual value of the array item let x for let i of x console log i So while in basically simplifies for let i i lt x length i of actually gives us new functionality to access the array contents itself This can be particularly useful if we have objects in our arrays let x name John name Jacob name Jingleheimer name Schmidt for let item of x console log item name John Jacob Jingleheimer Schmidt It should also be noted that for other iterables like Maps and Sets for of will return an array of both key and value while in will not work For example let myMap new Map myMap set x for let x of myMap console log x x for let x in myMap console log x does not console log anything To learn more about Maps and Sets you can read my detailed Javascript Map guide and Javascript Set guide here Iterating through objectsWhile objects themselves aren t iterable in Javascript they can be converted to iterables by using Object keys or Object values This converts an object in an array of either its keys or values which can then be iterated on let obj name John secondName Jacob age let iterableKeys Object keys obj for let item of iterableKeys console log item name secondName age ConclusionThat about covers everything you need to know In summary forEach is a method that is attached to most iterable items in Javascript with a few exceptions It is callback based usually doesn t work with promises and is slower than a traditional for loop for loops are available on every iterable object and it used to be for let i i lt x length i was the only format anyone used for in was introduced to simplify for let i i lt x length i to for let i in x Finally we gained the ability to access the values of each item in the iterable rather than just the key using for of I hope you ve enjoyed this guide and have a better idea of when to use in forEach and of in Javascript |
2022-11-06 17:46:50 |
海外TECH |
DEV Community |
How to monetize your Google Workspace add-on? |
https://dev.to/frenchcooc/how-to-monetize-your-google-workspace-add-on-1k0a
|
How to monetize your Google Workspace add on You ve built a great add on for the Google Workspace ecosystem Google Docs Google Sheets Gmail amp co It s getting a lot of traction and you feel like you can monetize it If this is your current situation great We were in the same situation a few years ago at Mailmeteor and we totally understand how excited you can feel today Below is the guide I wish I had found a few years ago when I was researching how to monetize our mail merge add on for Google Sheets There are several ways to manage how you monetize add ons I ll share with you how we do it at Mailmeteor Our approach is I believe one that provides the best user experience for your users and high security for you the developer Also at Mailmeteor we heavily rely on Firebase which has a NoSQL database Real time Database and can run serverless functions Cloud Functions We use both to handle the licensing If you aren t familiar with Firebase yet feel free to read on The general concept still applies even if you prefer AWS or other cloud providers Step AuthenticationFirst you need to authenticate your users When you build an add on sometimes you don t have a way for your users to authenticate That s especially true for narrowed add ons that provide a limited set of features The thing is as soon as you want to monetize your add on you need to provide a signup flow to safely authenticate users and retrieve their status e g free vs paid Google Apps Script already provides an authentication mechanism so there s no need to start from scratch Using UserSession getEmail you can safely know which user is running your code That s a very good start Plus if you take this path which we did at Mailmeteor you don t need to prompt to users an email password form The user is already logged in That s a high five for your users plus this will save you hours of work This being said now you need to make Google Apps Script communicate with your backend As I said at Mailmetoer we use Cloud Functions for our backend This has the benefit of being relatively cheap at the start and scaling automatically as the add on grows But Cloud Functions is not a requirement you could grab a cheap droplet on DigitalOcean and that would work just as well To make Google Apps Script work with your backend you can create a User class in your Apps Script code And add a getProfile method in it That method will fetch the user profile every time you call the function Here s a gist of our user gs file in Apps Script export class User public getProfile const userId this getUserIdFromEmail Session getEffectiveUser getEmail const request url BACKEND ENDPOINT user uid email options method GET headers Authorization Bearer BACKEND TOKEN const response UrlFetchApp fetch request const profile JSON parse response getContentText return profile public getUserIdFromEmail email const hash SOME RANDOM STRING email toLowerCase trim const digest Utilities computeDigest Utilities DigestAlgorithm SHA hash return digest map function byte const v byte lt byte byte return v toString slice join To retrieve the authenticated user profile you would run new User getProfile As you can see we rely on Session getEffectiveUser getEmail to safely retrieve the authenticated user email This method is made available by Google Apps Script via the Session class Also you might have noticed that the user s ID is generated by the getUserIdFromEmail which is just an SHA of the user email That won t resist brute force so we prefix it with a random string to make it harder to guess Sometimes your addon might use Apps Script to create and serve HTML for example by showing a modal or sidebar In such a case you would have to create a function in your user gs file function getUserProfile return new User getProfile Then you can retrieve the user profile from the HTML page by running google script run getUserProfile Now that you know how to retrieve a user profile let s see how to create a user Step User creationIn your backend you will need to create the user endpoint that will retrieve the user profile Again Firebase provides a great environment to do just that export const profile async request response next gt try Retrieve params const userId request query uid Validation if typeof userId string userId throw new Error invalid params Retrieve the profile from Firebase Real time Database const userRef FirebaseDatabase ref users uid const userSnap await userRef once value const profile userSnap val Send response to client response status response send profile response end catch error next error The user ID generated in Apps Script We use it as a key in our Firebase Real time Database to retrieve the user profile That s very easy to implement Before releasing to production make sure to secure your application by protecting your database from read write learn how to do it If you are already familiar with Firebase you might have noticed that this example doesn t use Firebase Authentication Firebase s user management feature That s because it way easier to do like that and at Mailmeteor we have some applications that run just this code Mailmeteor is a bit different as we provide a Dashboard where users can sign in to send emails and manage their accounts So we do use the Firebase Authentication layer What s great about using Firebase is that it lets you build lots of things easily For example Firebase lets you run a function as soon as a new field is created in your database This can help you send an onboarding email sequence for example Step Integrating with StripeSo let s recap from your add on using Apps Script and Firebase you can now safely retrieve a user profile All you need to do now is to update the user profile when someone pays you We use Stripe because that s a relatively intuitive payment platform but the following would work just as well with a PayPal account or any other service We use Stripe Checkout at Mailmeteor to handle the checkout flow If you want to manage the checkout flow yourself you can do so according to their docs What we will focus on here are Stripe webhooks In Stripe you can create webhooks so that Stripe can inform you whenever something happens There are webhooks for just about anything new customer new subscription new payment new invoice etc The webhook that you will use depends on the business model for lifetime subscriptions i e the user pays you once and gets full access to the software for the rest of its life you need to listen to the checkout session completed event for recurring subscriptions i e you are building a SaaS you need to listen to multiple webhooks At least webhook checkout session completed and customer subscription deleted And depending on how advanced your SaaS is you might need as well customer subscription updated and invoice events To keep things simple I ll show you how to listen to checkout session completed And if the business model of your add on requires more it s up to you to handle more webhooks events export const webhook async req res next gt Stripe webhook request signature const sig req get stripe signature Stripe webhook raw request Note rawBody is a Firebase method see const rawBody req rawBody try Verify Stripe request const event stripe webhooks constructEvent rawBody sig STRIPE WEBHOOK SECRET Handle the event switch event type case checkout session completed const session event data object const customer await stripe customers retrieve session customer Update profile in Firebase RTDB const uid getUserIdFromEmail customer email const userRef await FirebaseDatabase ref users uid await userRef update paid true customer customer id break The webhook function updates the user s profile with the status paid true and the customer s ID more on that later This means that starting from now whenever you retrieve the user s profile you can show it all your paid features Once you have deployed the webhook function to Firebase you can configure the webhook in Stripe Dashboard Just retrieve the URL of your function in the Firebase console and paste it into Stripe I would highly recommend you use Stripe s test mode to make sure everything works great Bonus Customer portalWhen you start to monetize your add on your users will regularly ask you for their invoices If you don t want to spend of your support on these requests it s best to create a customer portal where users can retrieve their invoices on their own Good news Stripe can help you with that From your add on in the UI you could add a new view where users can manage their accounts To add a link to the customer portal you need to redirect your users to Cloud Functions which will create the Stripe URL to the customer s portal The portal function looks similar to this one export const portal async re res next gt const userId req body amp amp req body user const customerId req body amp amp req body customer if typeof userId string userId throw new Error invalid params if typeof customerId string customerId throw new Error invalid params const customer await stripe customers retrieve customerId const userEmail getUserIdFromEmail customer email if userId userEmail throw new Error invalid customer const session await stripe billingPortal sessions create customer customer id res redirect session url The customer value is saved at the webhook step so you can reuse it easily Also for better security we double check that the customer s email in Stripe matches the provided user ID Well that was a lot You ll probably need a few things here and here to finalize the process But I hope that s a good starting point to help you monetize your Google Workspace add on If you need more help to connect the dots please feel free to reach out to me And if you haven t an add on yet find some inspiration in our best Google add ons directory |
2022-11-06 17:13:24 |
ニュース |
BBC News - Home |
Gavin Williamson text messages unacceptable, PM says |
https://www.bbc.co.uk/news/uk-politics-63530070?at_medium=RSS&at_campaign=KARANGA
|
gavin |
2022-11-06 17:49:02 |
ニュース |
BBC News - Home |
Tanzanian Precision Air plane crashes into Lake Victoria |
https://www.bbc.co.uk/news/world-africa-63532896?at_medium=RSS&at_campaign=KARANGA
|
africa |
2022-11-06 17:37:02 |
ニュース |
BBC News - Home |
England 29-30 Argentina: Pumas land famous win at Twickenham |
https://www.bbc.co.uk/sport/rugby-union/63534786?at_medium=RSS&at_campaign=KARANGA
|
argentina |
2022-11-06 17:19:14 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
「相手によって態度を変える人」のたった1つの特徴 - 99%はバイアス |
https://diamond.jp/articles/-/312081
|
突破 |
2022-11-07 02:55:00 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
「やらされる受験勉強」がどれだけ子どもにストレスをかけるか? - 子どもが「学びたくなる」育て方 |
https://diamond.jp/articles/-/312265
|
中学受験 |
2022-11-07 02:50:00 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
【営業が苦手な人のための「A4」1枚チラシ営業法】頭をさげて買ってもらわなくてもすむようにするには? - 「A4」1枚チラシで今すぐ売上をあげるすごい方法 |
https://diamond.jp/articles/-/311924
|
|
2022-11-07 02:45:00 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
ワガママや自己中とは違う「本物の自分軸」で生きている人の特徴とは?【予約の取れないカウンセラーが教える】 - あなたはもう、自分のために生きていい |
https://diamond.jp/articles/-/311810
|
twitter |
2022-11-07 02:40:00 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
【全財産90万円から株式投資で2億円】 親子喧嘩で包丁持ち出すほどグレた息子が サラリーマンになったとき教えた “かなりの確率でうまくいく”4つのポイント 【書籍オンライン編集部セレクション】 - どん底サラリーマンが株式投資で2億円 いま息子に教えたいお金と投資の話 |
https://diamond.jp/articles/-/311941
|
|
2022-11-07 02:35:00 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
【売れる人は知っている】お客様への声がけのタイミングの見きわめ方と「失敗しない」言い方とは? - 接客のきほん |
https://diamond.jp/articles/-/312105
|
購入 |
2022-11-07 02:30:00 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
赤っぽい柿と、黄色っぽい柿、意外とおいしいのはどっち? - 旬のカレンダー |
https://diamond.jp/articles/-/312327
|
赤っぽい柿と、黄色っぽい柿、意外とおいしいのはどっち旬のカレンダー今は、スーパーに行けばたいていのものが手に入るので、どれが旬の食材なのかぼんやりとしかわからない。 |
2022-11-07 02:25:00 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
【精神科医が教える】 近ごろストレスが溜まりっ放し… モヤモヤが止まらない頭のなかを 一瞬でスッキリさせる方法がある - 精神科医Tomyが教える 1秒で不安が吹き飛ぶ言葉 |
https://diamond.jp/articles/-/311170
|
【精神科医が教える】近ごろストレスが溜まりっ放し…モヤモヤが止まらない頭のなかを一瞬でスッキリさせる方法がある精神科医Tomyが教える秒で不安が吹き飛ぶ言葉増刷を重ねて好評多々の感動小説『精神科医Tomyが教える心の荷物の手放し方』の出発点となった「秒シリーズ」の第弾『精神科医Tomyが教える秒で不安が吹き飛ぶ言葉』から、きょうのひと言最近、泣いたことがありますか感動モノの映画やネット動画を観て、涙腺が崩壊して大泣きした、なんてことは意外とないのではないでしょうか。 |
2022-11-07 02:20:00 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
【ローマ人の最強であり続けるための思考法】アンラーンは古えより利益を生み出す知恵だった - アンラーン戦略 |
https://diamond.jp/articles/-/312367
|
近年 |
2022-11-07 02:15:00 |
コメント
コメントを投稿