#program:
Explore tagged Tumblr posts
jcmarchi · 9 months ago
Text
All About JavaScript Loops
New Post has been published on https://thedigitalinsider.com/all-about-javascript-loops/
All About JavaScript Loops
Every programming language has loops. Loops perform an operation (i.e., a chunk of work) a number of times, usually once for every item in an array or list, or to simply repeat an operation until a certain condition is met.
JavaScript in particular has quite a few different types of loops. I haven’t even used all of them, so for my own curiosity, I thought I’d do a high-level overview of them. And as it turns out, there are pretty good reasons I haven’t used at least a couple of the different types.
So, for now let’s spend a while exploring the different types of loops, what we can do with each of one, and why you might use one over another. (You’ll think that little play on words is absolutely hilarious by the end.)
The while and do...while loops
First up is the while loop. It’s the most basic type of loop and has the potential to be the easiest to read and the fastest in many cases. It’s usually used for doing something until a certain condition is met. It’s also the easiest way to make an infinite loop or a loop that never stops. There is also the do...while statement. Really, the only difference is that the condition is checked at the end versus the beginning of each iteration.
// remove the first item from an array and log it until the array is empty let queue1 = ["a", "b", "c"]; while (queue1.length) let item = queue1.shift(); console.log(item); // same as above but also log when the array is empty let queue2 = []; do let item = queue2.shift() ?? "empty"; console.log(item); while (queue2.length);
The for loop
Next is the for loop. It should be the go to way to do something a certain number of times. If you need to repeat an operation, say, 10 times, then use a for loop instead. This particular loop may be intimidating to those new to programming, but rewriting the same loop in the while-style loop can help illustrate the syntax make it easier to stick in your mind.
// log the numbers 1 to 5 for (let i = 1; i <= 5; i++) console.log(i); // same thing but as a while loop let i = 1; // the first part of a for loop // the second while (i <= 5) console.log(i); i++; // the third ("end");
The for...of and for await...of loops
A for...of loop is the easiest way to loop through an array.
let myList = ["a", "b", "c"]; for (let item of myList) console.log(item);
They aren’t limited to arrays though. Technically they can iterate through anything that implements what is called an iterable protocol. There are a few built-in types that implement the protocol: arrays, maps, set, and string, to mention the most common ones, but you can implement the protocol in your own code. What you’d do is add a [Symbol.iterator] method to any object and that method should return an iterator. It’s a bit confusing, but the gist is that iterables are things with a special method that returns iterators; a factory method for iterators if you will. A special type of function called a generator is a function that returns both a iterable and iterator.
let myList = *[Symbol.iterator]() yield "a"; yield "b"; yield "c"; , ; for (let item of myList) console.log(item);
There is the async version of all the things I just mentioned: async iterables, async iterators, and async generators. You’d use an async iterable with for await...of.
async function delay(ms) return new Promise((resolve) => setTimeout(resolve, ms); ); // this time we're not making an iterable, but a generator async function* aNumberAMinute() let i = 0; while (true) // an infinite loop yield i++; // pause a minute await delay(60_000); // it's a generator, so we need to call it ourselves for await (let i of aNumberAMinute()) console.log(i); // stop after one hour if (i >= 59) break;
One unobvious thing about for await...of statement is that you can use it with non-async iterables and it will work just fine. The reverse, however, is not true; you can’t use async iterables with the for...of statement.
The forEach and map loops
While these are not technically loops per se, you can use them to iterate over a list.
Here is the thing about the forEach method. Historically it was much slower than using a for loop. I think in some cases that may not be true anymore, but if performance is a concern, then I would avoid using it. And now that we have for...of I’m not sure there is much reason to use it. I guess the only reason that it still may come up is if you have a function ready to use as the callback, but you could easily just call that same function from inside the body of for...of.
forEach also receives the index for each item though, so that may be a thing you need too. Ultimately, the decision to use it will probably come down to whether any other code you’re working with uses it, but I personally would avoid using it if I’m writing something new.
let myList = ["a", "b", "c"]; for (let item of myList) console.log(item); // but maybe if I need the index use forEach ["a", "b", "c"].forEach((item, index) => console.log(`$index: $item`); );
Meanwhile, map essentially converts one array into another. It still has the same performance impact that forEach has, but it is a bit nicer to read than the alternative. It’s certainly subjective though, and just like with forEach you’ll want to do what the rest of your other code is doing. You see it a ton in React and React-inspired libraries as the primary way to loop through an array and output a list of items within JSX.
function MyList(items) return ( <ul> items.map((item) => return <li>item</li>; ) </ul> );
The for...in loop
This list of loops in JavaScript wouldn’t be complete without mentioning the for...in statement because it can loop through the fields of an object. It visits fields that are inherited through the object’s prototype chain too, though, and I’ve honestly always avoided it for that reason.
That said, if you have an object literal, then for...in might be a viable way to iterate through the keys of that object. Also it’s worth noting that if you’ve been programming JavaScript for a long time, you may remember that the order of keys use to be inconsistent between browsers, but now the order is consistent. Any key that could be an array index (i.e., positive integers) will be first in ascending order, and then everything else in the order as authored.
let myObject = a: 1, b: 2, c: 3, ; for (let k in myObject) console.log(myObject[k]);
Wrapping up
Loops are something that many programmers use every day, though we may take them for granted and not think about them too much.
But when you step back and look at all of the ways we have to loop through things in JavaScript, it turns out there are several ways to do it. Not only that, but there are significant — if not nuanced — differences between them that can and will influence your approach to scripts.
0 notes
gravitascivics · 2 years ago
Text
JUDGING LIBERATED FEDERALISM, VI
In sharing the various elements of liberated federalism, the proposed view by which to develop a civics curriculum, this blog is offering equality as a central concern.  In the last posting, using the ideas of Philip Selznick,[1] it described and explained the implications of what Selznick calls baseline equality.  This posting will now review his other form of equality, equal treatment.
         This next aspect, equal treatment, as with the case of baseline equality, is based on the belief in the dignity and integrity of each member of a union.  Such a belief leads to the aspiration for creating a commonwealth in which all its members can enjoy equal treatment or condition.[2]  
As baseline equality was a fundamental right, equal treatment is a derivative right and is based on an equal evaluation of everyone’s welfare.  In pursuing this right, to the extent it exists, dissimilar treatment for people in different categories can be considered and deemed rightful under what is judged to be the appropriate conditions.  
Dissimilar treatment must be justified on some grounds in which circumstances show that a level of disrespect to the dignity and welfare of certain groups exists.  “The objective is fairness based on moral equality, not consistency for its own sake.”[3]  In other words, government should treat people differently if to do so would be to respect and advance the ideal that everyone has intrinsic worth.  This can meaningfully give substance to a moral equality standard, i.e., to afford treatment to individuals as equals but realistic as to their situations.
This dissimilar treatment is not meant to down-level people, but to raise them to create a community in which all are ideally – and to a great extent actually – well-born.  So, therefore, a study of government should include inquiry and debate over the connection between the social equality that exists in fact and the equality which is advocated by this element of the liberated federalist model. In addition, inquiry should be extended to ask what this element of moral equality would prohibit or set limits on public or private sector policy within a commonwealth.
This blogger in other venues has made a distinction among how advocates of natural rights, critical theory, and liberated federalism define equality.  Natural rights view sees it as being the establishment of equal conditions, as in equality before the law.  This blog identifies that condition as an attribute of baseline equality.  
Critical theory defines it as equal results – that there should be minimal variance in the distribution of assets – such as wealth. And liberated federalism sees equality as regulated equality in which government and other authorities see to it that where factors, such as historical ones, place disadvantages in the path of certain groups, authoritative regulations should be put in place to alleviate or rectify the resulting disadvantages.[4]  A minimum wage would be such a regulation.
A commonwealth is then faced with a double-edged sword.  On the one hand, the inevitable ranking of individuals leads to an uneven distribution of material values.  Such a reality, though, threatens the level of moral equality in the commonwealth. But this sort of ranking is not only pervasive among societies of all kinds but is readily justified within those societies.  Calls to end uneven distributions are unrealistic and attempts will (and have) caused unacceptable costs to other values.
For example, would attempts to even out distributions act to squelch the motivation of those who would otherwise work creatively and assiduously to advance technological and other business-oriented activities which result in higher production and productivity?  The experience of collectivist societies, such as in purely socialistic societies where such attempts have been made, seems to indicate that such motivation would be squelched.
The key to resolving the dichotomy of values is the classical liberal call for equal opportunity.  Selznick describes these values as follows:
 No one should be hampered, no door should be closed to anyone, because of a prejudice against that person’s social origin. Whatever opportunities exist should be open to all without regard to social class or (as later extended) to race, creed, ethnicity, or gender.  Thus equality of opportunity has the limited objective of overcoming prejudice while maintaining the legitimacy of differential rewards.[5]
 In short, the focus is on ending any caste elements within the commonwealth.[6]  Affirmative action, under such a value, is limited to the following activities:  
 ·       identifying and providing appropriate training to those victimized by discrimination,
·       helping members of a discriminated group, or to demand evidence that public or private agencies have dealt with discriminated groups in good faith, and
·       exert meaningful effort to rectify past incidences of discrimination by actual accomplishments.
 Helping efforts might be extended to those who have not even been discriminated against, in order to upgrade the group as a whole.  In addition, public agencies, such as schools, should provide resources to poorer members of the commonwealth to encourage recipients to compete economically for limited material values.  At its base, the commonwealth would rely on a meritocratic standard that allows those who produce or have good fortune to benefit from their effort or luck, but it dismisses as illegitimate the ideal that holds that “winners” are inherently superior.
         Inequalities in such a value system are tolerated on the grounds that to eliminate them would be costly, impractical, and too disruptive and counterproductive to the general creation of wealth of material and other assets.  This would ultimately work to the disinterests of all, including the disadvantaged and the discriminated.  Therefore, the moral equality that is sought is based on a reciprocal advantage, not on sympathy, pity, or benevolence.
         Under such a system, all should support an arrangement as if anyone making up the commonwealth could be at the bottom – “there but for the grace of God go I.”  This reciprocal nature calls on a meaningful reality that (1) allows an opportunity to improve one’s position significantly, and (2) sets up a cooperative mode of social interaction.
         It allows for rational decision-making, maximizing one’s benefits and minimizing one’s costs, but is more encompassing than the marginal analysis of the systems approach (reviewed earlier in this blog). It considers the potential and often real distribution of assets.  Where significant imbalances exist – when basic humanity is threatened for an individual or group – leading to a lack of respect and dignity where anyone or anyone’s loved ones can find themselves in desperate and deprived conditions, appropriate welfare should be allotted.
         The reciprocal nature of this proposed arrangement has strong support within its logic for a fraternal ethos upon which community can be built and a meaningful commonwealth can be maintained.  But there exists under this logic the temptation to see all inequalities as counter to moral equality.  One needs to be clear about the functions of inequality. Selznick comments:
 Historically there have been four main justifications for inequalities as contributing to the common good.  It has been claimed that inequalities are essential for:  (1) effective organization for prosperity, education, public safety, and similar social goals; (2) achievement of excellence and high standards, especially in the realm of “high culture”; (3) protection of freedom, including the freedom to become unequal in possessions and personal attainment; and (4) commitment to ascriptive unities, especially family membership, which depend on recognition of special benefits and privileges.  None of these objectives can justify unlimited or unrestrained inequality.[7]
              The argument can be made that some level of inequality is both practical and moral, i.e., that a moral commonwealth should support an elitist element within its midst.  The elites, who are committed to democratic and republican ideals, are those the commonwealth depends upon to lead in the pursuit of a moral society under those ideals.
Included in this ideal is the goal of establishing a community in which the elites and non-elites can live in an overall cooperative venture.  In summary, that cooperative effort is to seek equality that restrains arbitrary power, encourages democratic participation, and promotes effective economic opportunity.  These qualities serve as the bedrock of a liberated federalist guided polity and should be at the core of a civics curriculum.
[1] Philip Selznick, The Moral Commonwealth:  Social Theory and the Promise of Community (Berkeley, CA: University of California Press, 1992).
[2] The term, “equal treatment,” as it is often used by those who ascribe to the ideas of natural rights, is limited to the notion that all should be treated in similar fashion by those in governmental authority.  Here, Selznick expands on this ideation of what “equal” or “equality” means.
[3] Ibid., 491.
[4] See for example, Robert Gutierrez, Toward a Federated Nation:  Implementing National Civics Standards (Tallahassee, FL: Gravitas/Civics Books, 2020).
[5] Selznick, The Moral Commonwealth, 492.
[6] Is “caste” too strong a term when considering the US?  To address that question readers are directed to Isabel Wilkerson, Caste:  The Origin of Our Discontents (New York, NY:  Random House, 2020/2023).  She makes a convincing argument that this nation has sufficient conditions to classify it as harboring a caste system.
[7] Selznick, The Moral Commonwealth, 499, emphasis in the original.
0 notes
389 · 1 year ago
Photo
Tumblr media
PORTO ROCHA
1K notes · View notes
bartleby-company · 2 months ago
Photo
Tumblr media
(vía Another America 50 by Phillip Toledano)
76 notes · View notes
nanaluvbug · 2 years ago
Photo
Tumblr media
🧀🥪🌶️🥭 The Ravening War portraits  🧀🥪🌶️🥭
patreon * twitch * shop  
[ID: a series of digitally illustrated portraits showing - top left to bottom right - Bishop Raphaniel Charlock (an old radish man with a big red head and large white eyebrows & a scraggly beard. he wears green and gold robes with symbols of the bulb and he smirks at the viewer) Karna Solara (a skinny young chili pepper woman with wavy green hair, freckled light green skin with red blooms on her cheeks. she wears a chili pepper hood lined with small pepper seeds and stares cagily ahead) Thane Delissandro Katzon (a muscular young beef man with bright pinkish skin with small skin variations to resemble pastrami and dark burgundy hair. he wears a bread headress with a swirl of rye covering his ears and he looks ahead, optimistic and determined) Queen Amangeaux Epicée du Peche (a bright mango woman with orange skin, big red hair adorned with a green laurel, and sparkling green/gold makeup. she wears large gold hoop earrings and a high leafy collar) and Colin Provolone (a scraggly cheese man with waxy yellow skin and dark slicked back hair and patchy dark facial hair. he wears a muted, ratty blue bandana around his neck and raises a scarred brow at the viewer with a smirk) End ID.)
2K notes · View notes
70sscifiart · 2 years ago
Photo
Tumblr media
One of my favorites by Paul Lehr, used as a 1971 cover to "Earth Abides," by George R. Stewart. It's also in my upcoming art book!
1K notes · View notes
taizooo · 8 months ago
Quote
もともとは10年ほど前にTumblrにすごくハマっていて。いろんな人をフォローしたらかっこいい写真や色が洪水のように出てきて、もう自分で絵を描かなくて良いじゃん、ってなったんです。それで何年も画像を集めていって、そこで集まった色のイメージやモチーフ、レンズの距離感など画面構成を抽象化して、いまの感覚にアウトプットしています。画像の持つ情報量というものが作品の影響になっていますね。
映画『きみの色』山田尚子監督×はくいきしろい対談。嫉妬し合うふたりが語る、色と光の表現|Tokyo Art Beat
156 notes · View notes
layla-keating · 2 years ago
Photo
Tumblr media Tumblr media Tumblr media Tumblr media Tumblr media Tumblr media Tumblr media Tumblr media Tumblr media Tumblr media
#thistension
XO, KITTY — 1.09 “SNAFU”
1K notes · View notes
nevver · 6 months ago
Photo
Tumblr media Tumblr media Tumblr media
No one wants to be here and no one wants to leave, Dave Smith (because)
111 notes · View notes
389 · 1 year ago
Photo
Tumblr media
PORTO ROCHA
768 notes · View notes
theroyalweekly · 2 months ago
Photo
Tumblr media
Beautiful photo of the Princess of Wales departing Westminster Abbey after attending the Commonwealth Day Service. --
84 notes · View notes
mellowlike · 5 months ago
Photo
Tumblr media
齋藤飛鳥
56 notes · View notes
goodvibesandmemes · 1 year ago
Text
GENERAL MEMES: Vampire/Immortal Themed 🩸🦇🌹
↳ Please feel free to tweak them.
Themes: violence, death, blood, murder, depression/negative thoughts
SYMBOLS: ↳ Use “↪”to reverse the characters where applicable!
🦇 - To catch my muse transforming into a bat 🌞 - To warn my muse about/see my muse in the sunlight. 🩸 - To witness my muse drinking blood from a bag. 🐇 - To witness To catch my muse drinking blood from an animal. 🧔🏽 - To witness To catch my muse drinking blood from a human. 🦌 - For our muses hunt together for the first time. 🏃🏿‍♀️ - To see my muse using super speed. 🏋🏼‍♂️ - To see my muse using their super strength. 🧛🏻‍♂️ - To confront my muse about being a vampire. 🌕 - For my muse to lament missing the sun. ⏰ - For my muse to tell yours about a story from their long, immortal life. 🤛🏽 - To offer my muse your wrist to drink from. 👩🏿 - For my muse to reminisce about a long lost love. 👩🏽‍🤝‍👩🏽 - For your muse to look exactly like my muse's lost love. 👄 - For my muse to bite yours. 👀 - For my muse to glamour/compel yours. 🧄 - To try and sneakily feed my muse garlic to test if they're a vampire. 🔗 - To try and apprehend my muse with silver chains. 🔪 - To try and attack my muse with a wooden stake. 👤 - To notice that my muse doesn't have a reflection. 🌹 - For my muse to turn yours into a vampire. 🌚 - For my muse and yours to spend time together during the night. 🧛🏼‍♀️ - For my muse to tell yours about their maker/sire.
SENTENCES:
"I've been alive for a long time [ name ], I can handle myself." "I'm over a thousand years old, you can't stop me!" "Lots of windows in this place, not exactly the greatest place for a vampire." "Do you really drink human blood? Don't you feel guilty?" "Vampires are predators, [ name ] hunting is just part of our nature, you can't change that." "You just killed that person! You're a monster!" "Tomorrow at dawn, you'll meet the sun [ name ]." "Can you make me like you?" "Do you really want to live forever?" "You say you want to live forever, [ name ], but forever is a long time, longer than you can imagine." "What was it like to live through [ historic event / time period ]?" "Did people really dress like that when you were young?" "What were you like when you were human?" "We’re vampires, [ name ], we have no soul to save, and I don’t care." "How many people have you killed? You can tell me, I can handle it." "Did you meet [ historic figure ]?" "Everyone dies in the end, what does it matter if I... speed it along." "Every time we feed that person is someone's mother, brother, sister, husband. You better start getting used to that if you want to survive this life." "[ she is / he is / they are ] the strongest vampire anyone has heard of, no one knows how to stop them, and if you try you're going to get yourselves killed." "Vampire hunters are everywhere in this city, you need to watch your back." "Humans will never understand the bond a vampire has with [ his / her / their ] maker, it's a bond like no other." "Here, have this ring, it will protect you from the sunlight." "I get you're an immortal creature of the night and all that, but do you have to be such a downer about it?" "In my [ centuries / decades / millennia ] of living, do you really think no one has tried to kill me before?" "Vampires aren't weakened by garlic, that's a myth." "I used to be a lot worse than I was now, [ name ], I've had time to mellow, to become used to what I am. I'm ashamed of the monster I was." "The worst part of living forever is watching everyone you love die, while you stay frozen, still, constant." "I've lived so long I don't feel anything any more." "Are there more people like you? How many?" "Life has never been fair, [ name ], why would start being fair now you're immortal?" "You want to be young forever? Knock yourself out, I just hope you understand what you're giving up." "You never told me who turned you into a vampire. Who were they? Why did they do it?" "I could spend an eternity with you and never get bored." "Do you really sleep in coffins?" "There are worse things for a vampire than death, of that I can assure you [ name ]." "You need to feed, it's been days. You can drink from me, I can tell you're hungry." "The process of becoming a vampire is risky, [ name ], you could die, and I don't know if I could forgive myself for killing you." "I'm a vampire, I can hold a grudge for a long time, so believe me when I say I will never forgive this. Never." "You were human once! How can you have no empathy?" "You don't have to kill to be a vampire, but what would be the fun in that." "You can spend your first years of immortality doing whatever you want to whoever you want, but when you come back to your senses, it'll hit you harder than anything you've felt before." "One day, [ name ], everything you've done is going to catch up to you, and you're never going to forgive yourself." "Stop kidding yourself, [ name ], you're a vampire, a killer, a predator. You might as well embrace it now because you can't keep this up forever." "You can't [ compel / glamour ] me, I have something to protect me." "When you've lived as long as me, there's not much more in life you can do." "You want me to turn you? You don't know what you're asking me to do." "You really have to stop hissing like that, it's getting on my nerves." "I'm going to drive this stake through your heart, [ name ], and I'm going to enjoy it."
161 notes · View notes
shitakeo33 · 6 months ago
Quote
よく「発明は1人でできる。製品化には10人かかる。量産化には100人かかる」とも言われますが、実際に、私はネオジム磁石を1人で発明しました。製品化、量産化については住友特殊金属の仲間たちと一緒に、短期間のうちに成功させました。82年に発明し、83年から生産が始まったのですから、非常に早いです。そしてネオジム磁石は、ハードディスクのVCM(ボイスコイルモーター)の部品などの電子機器を主な用途として大歓迎を受け、生産量も年々倍増して、2000年には世界で1万トンを超えました。
世界最強「ネオジム磁石はこうして見つけた」(佐川眞人 氏 / インターメタリックス株式会社 代表取締役社長) | Science Portal - 科学技術の最新情報サイト「サイエンスポータル」
81 notes · View notes
whencyclopedia · 3 months ago
Photo
Tumblr media
The Delian League, Part 2: From Eurymedon to the Thirty Years Peace (465/4-445/4 BCE)
This text is part of an article series on the Delian League.
The second phase of the Delian League's operations begins with the Hellenic victory over Mede forces at Eurymedon and ends with the Thirty Years Peace between Athens and Sparta (roughly 465/4 – 445/4 BCE).The Greek triumph at Eurymedon resulted in a cessation of hostilities against the Persians, which lasted almost six years. Whether or not this peace or truce followed from some formal treaty negotiated by Cimon, son of Miltiades, remains unknown.
Nevertheless, the Greek success at Eurymedon proved so decisive, the damage inflicted on Persia so great, and the wealth confiscated so considerable that an increasing number of League members soon began to wonder if the alliance still remained necessary. The Persians, however, had not altogether withdrawn from the Aegean. They still had, for example, a sizeable presence in both Cyprus and Doriscus. They also set about to build a great number of new triremes.
REDUCTION OF THASOS & THE BATTLE OF DRABESCUS
A quarrel soon erupted between the Athenians and Thasians over several trading ports and a wealth-producing mine (465 BCE). Competing economic interests compelled the rich and powerful Thasos to revolt from the Delian League. The Thasians resisted for almost three years. When the polis finally capitulated, the Athenians forced Thasos to surrender its naval fleet and the mine, dismantle defensive walls, pay retributions, and converted the future League contributions to monetary payments: 30 talents annum. Some League members became disaffected with the Athenian reduction of Thasos. Several poleis observed the Athenians had now developed a penchant for using "compulsion." They started to see Athens acting with both "arrogance and violence." On expeditions, furthermore, the other members felt they "no longer served as equals" (Thuc. 1.99.2).
The Athenians, meanwhile, attempted to establish a colony on the Strymon river to secure timber from Macedon, which shared its borders with the west bank. The location also proved a critical strategic point from which to protect the Hellespont. The Thracians, however, repelled the League forces at Drabescus. The Athenians soon realized the threats from both Thrace and Macedon made permanent settlements in the region difficult as they were essentially continental powers, and the League fleet could not reach them easily. Designs for the region, however, would not change, and the Athenians would return there again.
The Delian League had by this time demonstrated an inherent conflict from its beginnings: on the one hand, it engaged in heroic struggles against the Mede and extended its influence, reaping enormous benefits (especially for its poorer members). On the other hand, it also suppressed its members and soon demanded obedience from them.
The League engaged from the outset in a form of soft imperialism, collecting and commanding voluntary naval contributions and tribute while Athens used those resources and led all expeditions, enforcing continued membership but also showing little or no interest to interfere with the internal mechanisms of any member polis (unless it openly rebelled).
Continue reading...
35 notes · View notes