#typescript casting
Explore tagged Tumblr posts
Video
youtube
TypeScript Function & Casting Tutorial for JavaScript Developers | #type... Full Video Link -   https://youtu.be/HmPfntT63Ns Check out this new video on the CodeOneDigest YouTube channel! Learn Function & Casting in typescript. Learn how to write function in typescript and how to type cast variable in typescript programming language. #video #typescript #function #casting # #nodejs #javascript #codeonedigest@java @awscloud @AWSCloudIndia @YouTube @codeonedigest #typescript #javascript #typescript #typescripttutorial #typescriptforbeginners #learntypescript #typescript #typescripttutorialforbeginners #typescriptfullcourse #typescriptfulltutorial #typescriptfullcourseforbeginners #typescriptfunctionoverloading #typescriptfunctionalcomponent #typescriptfunction #typescriptcasting #castingintypescript #castingtypes #typescripttypecasting #typescriptexplained #typescriptexampleproject #typescriptfunctionexample #typescriptcastingexample #guide Â
#youtube#typescript#typescript full course#typescript full tutorial#typescript guide#typescript function#typescript casting
0 notes
Text
Boost Code Readability in TypeScript with Type Guards
Introduction Type Guards in TypeScript are a powerful feature that enhances the readability and maintainability of your code by allowing you to narrow the type of a variable within a specific scope. They are functions that return a type predicate, making your type checks explicit and reducing the need for type assertions or casting. This tutorial will guide you through the implementation andâŚ
0 notes
Text
Matt Pocock's Total TypeScript: Essentials

Some notes I made while reading this book:
Optional values in a tuple
Not only can a tuple have named values, it can have optional ones:
[name: string, year: number, info?: string]
[string, number, string?]
Dealing with an unknown
If we have obj of type unknown, and we want to get obj.prop of type string, this is how to do it correctly:
typeof obj === 'object' && obj && 'prop' in obj && typeof obj.prop === 'string'
If we refactor the expression above into a return value of a type guard, this would be its type signature:
(obj: unknown) => obj is {prop: string}
Destructuring values of union types (tuples vs. objects)
const [status, value]: ['success', User[]] | ['error', string] = await fetchData();
TS can then guess based on the type of the discriminant (the status variable) the type of the rest of the return value (the value variable), but wouldn't be able to do the same, if fetchData returned an object instead of tuple. An object type should be narrowed first, before we can destructure its value!
Dynamic keys
If we don't know, what keys the object may have during the lifetime of the program, we can have index signatures...
type DynamicKeys = { [index: string]: number; }
interface DynamicKeys { [index: string]: string; }
...or we can use Record helper type. Record type supports union types of type literals, unlike index signatures!
type DynamicKeys = Record<'name' | 'age' | 'occupation', boolean>
Read-only arrays
We can disallow array mutation by marking arrays and tuples as readonly, or using ReadonlyArray helper type:
const readOnlyGenres: readonly string[] = ["rock", "pop", "unclassifiable"];
const readOnlyGenres: ReadonlyArray<string> = ["rock", "pop", "unclassifiable"];
Read-only arrays/tuples can only be passed to functions that explicitly expect read-only arrays/tuples:
Matt's strange opinions on class methods
function printGenresReadOnly(genres: readonly string[]) { }
More helper types

When Matt talks about the difference between arrow and function methods, he mentions only the different ways they handle this, but isn't a much more important distinction the fact that arrow methods are technically class properties, so will be copied on every instance of a class?
UPD: And later he recommends using arrow functions!

This is extremely memory inefficient, right?
satisfies operator
Very useful thing I've never heard of before!
When a value isn't annotated with type, its type is inferred. When a value is annotated with type, its type is checked against the annotated type. When a value is followed with satisfies, its type is inferred (as if there were no annotation), but still checked against the constraint (as if there were an annotation).
Useful (?) type assertions
as any // turns off type checking for a particular value.
as unknown as T // cast a value to a completely unrelated type.
as const satisfies T // makes a value immutable, while checking it against a type.
Object.keys (user).forEach((key) => { console.log(user[key as keyof typeof user]); }) // by default TS infers return values of Object.keys() and for ... in as string[].
Excess properties
TS doesn't throw an error, when (1) a variable containing an object with excess properties is passed to a function, or (2) when an object with excess properties is returned by a callback. Both the variable and the return type of the callback should be annotated, if that is an issue.
Modules vs. scripts
Files with no import or export statement are treated by the compiler as scripts, executing in the global scope. The problem is, that's not how the distinction works in pure JS, so we can end up in sitiations like this...

...just because the name variable already exists elsewhere. One way to fix this mistake (which I knew about) is by adding export {}; to the end of the file, turning it into a module from TS perspective. Another way (which I found out about just now) is by adding line "moduleDetection": "force" to the config file. Cool.
Recommended configuration (link)

0 notes
Note
Hey there, so we got The Scene today, and do you have any thoughts on Dracula's interest in/designs on Jonathan?
The "The man belongs to me!" scene is one of those moments in Dracula that is just neutron star dense with possible meaning, and it is obviously an episode that was on Stoker's mind for a while, given that outlines of it appeared in his notes seven years prior to Dracula's publication. As so much of tumblr instantly observed, it's easy to read the moment as one of homoerotic desire, and this a reading I tend to agree has merit. Stoker definitely seemed to have some deep apprehensions about his sexuality/gender even if you don't believe he was queer (and I tend to believe he probably was queer), and I think that having a strong, commanding man protect one of your authorial inserts from sexually aggressive, anti-maternal vampire women definitely speaks to those apprehensions. The fact that Jonathan subsequently faints and needs to be carried to his rooms is a moment that I feel really underscores how much of Dracula's first section is an inversion of our expectations for Gothic heroes and heroines; this is exactly the sort of moment that one would typically see play out with a frightened young woman in a white nightdress doing the swooning in earlier gothic literature, and it's fascinating to have a young male professional suddenly cast in that role.
In addition to this, while I don't tend to favor readings of Dracula that position him as completely based on Henry Irving, Irving was noted for having a commanding, somewhat tyrannical presence, he does share quite a number of features with the Count, and he was definitely a focal point of much of Bram's personal and professional life. If you read Stoker's Personal Reminiscences of Henry Irving, the way he describes Irving's influence on him feels almost mesmeric in its intensity. While we can't know the degree to which Stoker was or was not personally smitten with his employer, I think that it is not too far fetched to imagine that some aspect of his relationship to Irving left an impression on Dracula.
Lastly, I am personally of the belief that Dracula was very much influenced by the W. G. Wills stage adaptation of Faust, which was a massive hit in the 1870s and starred Irving as Mephistopheles. Some of the aspects of Mephistopheles that were really played up in that production were his aversion to crucifixes and his problems crossing thresholds, and there's a deleted fragment in the typescript that very much compares the Count to this version of the character. As such, I think one can also read "This man belongs to me" in terms of a demonic/devil-like entity laying claim to his victim's soul.
Overall, I personally read this instant as Dracula expressing a genuine desire for a man who represents the life and animation that he seeks to reclaim through his attempt to relocate to England, but I also think that there is a possessiveness that is meant to be read as otherworldly and Satanic in nature: that this is a claim that manages to intermingle Dracula's humanity and his inhumanity. I also think that it very much touches on a desire for/fear of men desiring men that Stoker could not really write about outside of a supernatural setting.
#Bram Stoker#Dracula#Dracula Daily#The Count#Jonathan Harker#Henry Irving#W. G. Wills#Faust#liveblogging dracula 2022
2K notes
¡
View notes
Text
âď¸Shipping Our Castđ
Today we bring you a small treat!
Behold, a behind-the-scenes look at a topic sure to interest and entice: how did the FujoGuide team come up with such a shippable cast of characters?
If you're just joining us now and need to catch up on what #FujoGuide is all about, read our pitch (and back our project) at our Kickstarter page. (TL;DR: weâre making web development more accessible to fandom communities.)
As with most things in our Kickstarter, our character creation was a collaborative effort. We wanted our cast to embody tropes beloved by shippers, but also to prove to existing developers we know what we're talking about!
This was not an easy task. So, how did we accomplish it?
Follow the cut to find out!
At first, we didn't know which characters we needed! When our project lead @essential-randomness wrote the initial pitch, she jotted down a couple examples of how the characters MIGHT behave.
Why these characters? Well, she loves TypeScript, and Git wrote itself.
Character creation was a collective process and TV Tropes, our best friend. Which characters did the team like? What tropes did they embody? What were genre must-haves? What made them undeniably hot?
We watched classics like Ouran or Fruits Basket to get ready! Hetalia, even!
During this process, we got to teaching! Our lead @essential-randomness held some learning sessions for collaborators explaining modern web development technologies and their relationships.
You can see the resulting diagram here.
While we researched, we discussed possible topics and created more characters. We even have some yet-to-be-released work-in-progress hotties who unfortunately didn't make it into our first guide: [REDACTED] and [TOP SECRET], courtesy of @cmdonovann.
Eventually, we landed on Git(Hub) as a topic: widely applicable, complex enough, and yet self containedâthe perfect test for our educational prowess!
And (we'll admit it) the words "tentacle catboy" were all the team needed to get really sold on the vision.
Documents were made and filled with technical details, references, and character tidbits we brainstormed together. Character designers worked closely with the rest of the team to tastefully include technical references, such as Git's branches, Terminal's cowsay, and CSS' owl.
Want to know more about these âmasters at workâ? Go follow them! @brokemycrown (Git & GitHub), @mappapapa (Terminal), @ymkse (HTML & CSS), and @sgt-spank (ARIA).
Throughout this process, our team wanted to balance creating just enough canon for people to latch on, while having "blank slates" characters open to wide reinterpretation.
Most of us come from transformative fandom, so what is canon if not just a sandbox for us all to play in?
But then how DO we make a cast of characters that people will love to ship while leaving the door open to interpretation? @playerprophet answered our cry for help with their amazing cast creation tool!
You can get it here on their Patreon!
Shoutout to all the amazing creators involved in developing our characters:
@enigmalea @elendraug @mizunotic @a-brilliant-loser @tempural (and more not on this platform!)
This concludes our tale of breathing life into our characters. We hope people will come to love them as much as we do. The response to them already has blown us out of the water!
Check out all their character cards (and back us!) on Kickstarter.
Questions? Comments? Our team is always here for them đ
177 notes
¡
View notes
Text
Dracula: The Evidence
Well, now that we've finished reading Dracula, I'd like to highlight yet another upcoming way to read Dracula! This one is Dracula: The Evidence by Beehive Books, a small press imprint in Philadelphia currently available to preorder. Let me preface this by saying that I'm not affiliated with the creators of this project. I'm just discussing it because I think it's cool. I'll also warn that the two cheapest options for purchasing these items are $400 (for the complete artifactual experience) or $100 (for a hardcover version). If that's too much for you, I'd still recommend taking a look at the neat prototype images and information about the creation process found on their product pages and project updates.
Dracula: The Evidence is a project recreating the primary sources that make up Dracula. As they describe it, "In our edition, you are not merely a reader â you are an explorer making your way through this archive of first-hand evidence, retracing this nightmarish story through the remnants it left behind: correspondence, charts and diagrams, memoranda, artifacts, photographs, and much more."
That means you'll be receiving items like Jonathan's journal and letters from Lucy to Mina in their complete (and unburnt) form.
For people willing and able to shell out the $400, these items will come in a suitcase. For those who can commit $100, you can purchase a hardcover art book with pictures of the artifacts and transcripts of their contents.
There's also the option to purchase a vinyl record of Seward's phonograph recordings (also for $100).
I'm going to ramble a bit more about the project under the cut, but before that here's a link to a post I've made with links to the project. One of them is a promotional Twitter thread written by a fictional archival intern hired to process the Stoker Papers. It's pretty fun.
Edit: It slipped my mind that there was a PDF preorder on offer on Kickstarter for $25. It's not currently on the Beehive Books storefront, but it might be sold once the preorder period is over.
Beehive Books has been transparent about supply chain issues and events like the calligrapher they cast to write for Jonathan Harker being conscripted in the army causing delays. However, it is currently projected that the products will ship in early 2023.
Speaking of calligraphers, they've hired over a dozen of them to write for the different characters. It's neat to hear that they've put a lot of consideration into how the personalities of the characters should be reflected in their handwriting.
If you want to hear a sample of their recordings for Dr. Seward's diary, check out the September 12th Kickstarter Update on either edition. The updates are open to the public, and they've posting a link to a Dropbox with a two-minute sample from Jack's May 25th entry.
Check out the update from January 10th, 2022 to hear how they're tackling the fact that most of the documents that make up Dracula are originally not written in standard English. Here's an excerpt from it:
"For Mina, we've had her switch back and forth between shorthand and longhand throughout her diary. We've used it to enhance character building and storytelling. She's using the journal as an opportunity to learn and practice shorthand -- so which sections does she feel most urgent about, and might she scrawl down in her natural hand without translating into her shaky shorthand? Which sections might she feel private about, and want written in an alphabet that someone who comes upon her diary might not understand?
And then we have Mina's typescript, which transcribes every word of every document contained therein, and more. This allows readers to work with the two documents side-by-side, decoding shorthand or Russian with the help of the typescript."
On the update from October 29th, 2021, they discuss how the Captain of the Demeter wrote his log before the modernization of the Cyrillic alphabet and how they had to find a linguist to rewrite their Russian translation.
Seriously, even if you can't afford to buy this, there's a lot of fun to be had in poking around the project updates and looking at the prototype images they've shared.
That's all from me! It's time to see some of the adaptations for myself, starting with Dracula (1931).
98 notes
¡
View notes
Video
youtube
J.R.R. Tolkien reads from The Hobbit and The Lord of the Rings, 1952
This is J.R.R. Tolkien readingâand singing!âexcerpts from The Hobbit and The Lord of the Rings, and it is exactly as amazing as it sounds. George Sayer, a friend of Tolkienâs, helped make the recordings while Tolkien was visiting him in August 1952, two years before The Lord of the Rings was published. (It doesnât have that information under the youtube videos, but I was able to find out the context from Tolkien Gateway and the Tolkien Library.) These are so wonderful and Iâm so glad they exist! Itâs absolutely delightful to hear the Professor reading his own stories. You have not lived until you have heard Tolkienâs Gollum impression, or his Treebeard voice, or him speaking in Elvish...not to mention reading The Ride of the Rohirrim! Yes, he actually recorded that and it is literally the best thing ever. Itâs amazing to listen to him reciting the Song of Beren and LĂşthien (just like Strider told it to the hobbits!), and everything else, and Iâm so, so, so glad that these recordings were made. This is a treasure trove! I want more people to know about this!Â
Excerpt from Riddles in the Dark The Road Goes Ever On Upon the Hearth the Fire is Red Snow-white! Snow-white! O Lady Clear! The Bath Song Farewell We Call to Hearth and Hall! Hey dol! merry dol! ring a dong dillo! The Man in the Moon Stayed Up Too Late The Fall of Gil-galad The Song Of Beren And LĂşthien The Stone Troll A Elbereth Gilthoniel The Song of Durin The Song of Nimrodel When evening in the Shire was grey Gandalf's Song of LĂłrien Lament for Boromir The Long List of the Ents Treebeardâs Song The Ent and the Entwife Bregaladâs Song The Entsâ Marching Song Where now the horse and the rider? Gollumâs fish song Oliphaunt Excerpt from Of Herbs and Stewed Rabbit Lament for ThĂŠoden Excerpt from The Ride of the Rohirrim Song of the Mounds of Mundburg Excerpt from Mount Doom Sing now, ye people of the Tower of Anor NamĂĄriĂŤ
Finally, this is George Sayerâs note on the recordings, which I transcribed from this radio broadcast because I thought others would like to read it.Â
George Sayer writes: âThis record is based on a tape recording that Tolkien made when he was staying in my house in northern Worcestershire. It was in August 1952. For the whole of that summer he had been depressed because The Lord of the Rings, the book on which he had worked for fourteen years, had been refused by publishers, so that he had almost given up hope of ever seeing it in print. But the fact that they had returned it made it possible for my wife Moira and I to borrow the only complete typescript and become, with our friend C.S. Lewis, about the first of passionately enthusiastic Tolkien fans. There arose the question of how to return it to its author. Since it could not, of course, be trusted to the post, I wrote to ask when he would be at home in Oxford for me to deliver it. His reply indicated that he would be quite on his own in the second half of August, and perhaps even rather lonely, and we therefore invited him to come to more than to pick up the typescript, and to stay for a few days. âIt was easy to entertain him by day. He and I tramped the Malvern Hills, which he had often seen during his boyhood in Birmingham, or from his brotherâs house on the other side of the Seven River Valley. He lived the book as we walked, sometimes comparing parts of the hills with, for instance, the White Mountains of Gondor. We drove to the Black Mountains on the borders of Wales, picked billberries, and climbed through the heather there. We picnicked on bread and cheese and apples, and washed them down with perry, beer or cider. When we saw signs of industrial pollution, he talked of orcs and orcery. At home, he helped me to garden. Characteristically, what he liked most was to cultivate a very small areaâsay a square yardâextremely well. âTo entertain him in the evening I produced a tape recorder, a solid early Ferrograph that is still going strong. He had never seen one before, and said whimsically that he ought to cast out any devil that might be in it by recording a prayer, the Lordâs Prayer, in Gothicâone of the extinct languages of which he was a master. He was delighted when I played it back to him, and asked if he might record some of the poems in The Lord of the Rings to find out how they sounded to other people. The more he recorded, the more he enjoyed recording, and the more his literary self-confidence grew. When he had finished the poems, one of us said, âRecord for us the riddle scene from The Hobbit!â and we sat spellbound for almost half an hour while he did. I then asked him to record what he thought one of the best pieces of prose in The Lord of the Rings, and he recorded part of The Ride of the Rohirrim.Â
ââSurely you know thatâs really good?â I asked, after playing it back. âYes,â he said. âItâs good. This machine has made me believe in it again. But how am I to get it published?â I thought of what I myself might do in the same difficulty. âHavenât you an old pupil in publishing who might like it for its own sake, and therefore be willing to take the risk?â âThereâs only Rayner Unwin,â he replied, after a pause. âThen send it to Rayner Unwin personally!â And he did. And the result was that even during his lifetime, over 3 million copies were sold. When he got back to Oxford, Tolkien wrote to thank us for having himâa letter in Elvish that is one of my most valued posessions.â
#Tolkien#J.R.R. Tolkien#LOTR#The Hobbit#THIS IS SO WONDERFUL#YOU MUST LISTEN TO IT#I LOVE TOLKIEN SO MUCH#I'M SO GLAD LOTR WAS PUBLISHED#my post#recordings of Tolkien
3K notes
¡
View notes
Text
An Intro Post
So much to do... so little time...
About Me
Howdy! The name's Perseverant Determination, but that's exteremely long. Feel free to call me anything, though Perse will do just fine. You might also see me in other places under other names, especially EF159. Feel free to use that as well.
I do a lot of things, which means that this main blog will have an assortment of topics. I create beatmaps for VSRGs, write stories, and code personal programs. I'll tag my posts as shown below, so you can filter my posts.
#the-void's-determination: For all stuff related to writing
#code.tryperse: For all stuff related to programming
#perse-the-beat: For all stuff related to rhythm games and beatmapping
If you have questions about a certain topic, feel free to ask me. While I'm more likely to answer programming-related questions, I'll try to do my best to give you satisfactory answers.
The Void's Determination
I like writing sci-fi, though lately, I find myself preferring fantasy more. I've been writing for a few years and have a few short stories on r/WritingPrompts, but those are years old now and they're not that good, in my opinion. If you can find them somehow, good for you. I'm not linking to them.
Projects
Days of Moonlight Riddles
I play Sky, that game of Light. Riddles, I see with great delight. I might not solve them all the time. I might be wrong but still, I'll try.
Along with Duet's last two weeks, The lanterns cast, for all to see. In each of them, a riddle held. Answer three â three tickets left.
And thus, to bring my prose to test, A riddle a day; I bring my best. If you so seek to answer those, Look below and have your go.
Riddles: [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] [13] [14]
Ethereal Dreams (currently being reworked from the ground up)
Code.TryPerse()
I have a side blog for this now!
I consider myself experienced in C#, though I've also practiced a bit of C/C++, Java, Javascript/Typescript, Python, and Lua. I don't do much with that knowledge though. I just code some stuff that can help me with random trivial problems. I want to be a game developer but that's going to take time, what with me doing all this writing and beatmapping.
10 notes
¡
View notes
Link
A little while before she died â when it seemed she might have almost any amount of time left, from days to months â I screwed up my courage and suggested to my mother that, given that she was 82 and suffering from significantly terminal cancer, it might not be too early to give some consideration to retirement, or, failing that, a week off. On her sickbed, she continued to search through her notes from late last year, looking for anything my father David, who wrote as John le CarrĂŠ, might have written that would otherwise be missing from the body of work he left behind. It was an unnecessary labour; we have everything, and we had it then. While I didnât want to take away something that was a mainstay of her life, I was concerned that she was growing unhappy in the search for new material that did not exist.
She looked back at me as if Iâd said she should grow wings.
âBut what would I do?â
I suggested a short list of diversions: talk, eat, watch cricket or snooker â they both loved sport â or some of the films on her endlessly postponed watch list.
She gave it some thought. âNo,â she said at last.
For as long as I can remember, my parents have been defined by the work they did together, and by a working relationship so interwoven with their personal one that the two were actually inseparable. Davidâs first report of Jane, long before I was born, was that she had rescued his novel A Small Town in Germany when it was literally in pieces on the floor. Some of my earliest memories are of him reading, handwritten pages or typescript with annotations in black pen, sometimes physically cut and pasted in the days before computers, and her listening, absorbing, only occasionally responding, but always with immediate effect.
It was easy to misunderstand her as just a typist â and many did â not only because she also typed everything, as he never learned how, but also because her interventions were made in private, before the text was ever seen by anyone else. I was witness to it as a child and then as a teenager, but by and large only they knew what passed between them and how much she reframed, adjusted, trained the novels as they grew. She was adamant that her contribution was not writing, that the creative partnership they had was uneven. She declined interviews and stepped out of photographs â even family ones, so that as we were looking this week for images for the order of service at her cremation, we had very few, and those were stolen moments gleaned before she could practise her invisibility trick. It was part of how it worked: he produced, they edited; he burned, she fanned. It was their conspiracy, the thing that no one else could ever offer him, in which they both connived.
Very few, very wise people saw through them both, of whom the most recent and the most absolute is Richard Ovenden, who examined the papers my father loaned to the Bodleian library in Oxford and observed a âdeep process of collaborationâ. His analysis is a perfect match for my recollection: âA rhythm of working together that was incredibly efficient ⌠a kind of cadence from manuscript, to typescript, to annotated and amended typescripts ⌠with scissors and staplers being brought to bear ⌠getting closer and closer to the final published version.â
Exactly that: at each turn, fresh problems to be solved, fresh insights and flourishes of invention. And all along, at every step, was Jane, recalling the first moment of inspiration to refresh a tired passage, or asking whether a given phrase really reflected the intent she knew was behind it. She was never dramatic; she was ubiquitous and persisting throughout the body of work.
As they both became ill in their later years, it only revealed the extent of the mutual support and mutual dependency. They might struggle, as everyone does after 80, to remember things in casual conversation, but in work each could rely on the other to make the connection, to pick up the slack when a brilliant but ageing mind suddenly stuttered. As a team â more, as a single process functioning between two people, defining them both â they were immune to the halting state.
It was a wonderful thing, but the more painful, when he died rather abruptly in December, to see her deprived of the other half of her way of thinking across five decades. She was casting around for who might be holding the part of herself that she had vested in him, looking for the rest of the process that was trying to continue in her â hence the search for the missing material, the determination to keep going, because to stop working was to die again.
20 notes
¡
View notes
Video
youtube
TypeScript Function & Casting Tutorial for JavaScript Developers | #type...
0 notes
Text
TypeScript Generics: Unlocking Type Inference and Polymorphism
Introduction TypeScriptâs Generics: Unlocking the Power of Type Inference and Polymorphism is a powerful feature that allows developers to create reusable and flexible code. Generics enable you to define functions, classes, and interfaces that can work with multiple types, without the need for explicit type casting or type checking. In this tutorial, we will delve into the world of TypeScriptâŚ
0 notes
Text
Our Son, Arc II, Storytime, Chapter 12
@notevenjokingficââ took a small idea I had and used her wonderful mind to help me build on it for this chapter. Both she and @balfeheughlywedâ give me their time, advise and support and I really value it all as I know they've hectic lives outside of fanfic land. As usual @laythornmuseâ and @ladyviolethummingbird have been hugely helpful and supportive, and the DM's over our combined fics could fill a novel lol.
7 weeks later. Boston.
  With my phone tucked under my chin and Jenny Fraserâs persistent questioning in my ear, I fumbled in the bottom of my bag in search of the house keys.
 âJenny, honestly Iâm fine. We're back in a routine now, Willie is happy to see his old school friends. â I â am fine.â
  âYe have repeated fine twice, so ye must be then.â She quipped sarcastically, before her tone softened â âye are not and I ken it well, mam and Da want to go out to see ye and Willie in a few weeks would that be ok?â
 âOf course, I would love to see them, and Willie would be delighted.â
 âaye,â Jenny agreed quietly. I could almost hear her mind working over the phone.
 âWot?â I blurted out more testily than Jenny deserved and kicked myself.
 âAch, itâs nothing Claire, itâs just I ken ye dinna want to talk about him, but I only wondered if ye had heard anything from Jamie? His calls are becoming less and less frequent here, Mam and Da are worrit and I â donât want to upset ye, but there is something off about what is going on there.â
 I wasnât capable of answering without sounding bitter, but I heard the weary, worried tone in Jennyâs voice and wouldnât hurt her for anything.
 âHe rings Willie every second day.â I said sighing, since the first phone call after I returned to Boston, I just hand the phone to Willie, so I havenât really spoken to him myself â I canât just yet.â I finished honestly.
 âaye â off course Claire.â
 The vice-tight grip on my heart as I even discussed Jamie was the reason I wasnât capable of holding a conversation with him. My days and nights spent missing him, followed by the wave of gripping pain overcoming me every time I imagined him with Geneva Dunsany, her high pitched giggle haunting my dreams as I saw her, at work, at play and in his bed.
 Willie tugged impatiently on my coat, âWill ye open the door mama, Iâm burstân.â I looked down at him as he danced from foot to foot while holding his crotch.
 Pushing the door open, I dropped my bag and swapped Jenny to my opposite ear.
 âLook Iâm sure, he is just busy there Jen, itâs all new â â I trailed off lamely. Geneva is new; I thought to myself and felt the lump run from my stomach up to my throat.
 âClaire â âJenny began hesitantly âI dinna think Jamie is busy for the reasons you do; I have spoken to him â I told ye what he said.â
 I blinked back tears, âYes you did â but I really canât think about it anymore â I need to be strong for Willie and working myself into a weeping heap thinking of the what ifâs will not help me function.â I admitted in resigned sigh.
 There was silence on the other end of the phone for a few moments, and Jennyâs tone was almost unrecognisable when she spoke again.
 âAs mad as I am with him for putting you in this position, to even give people the chance to question him. I donât believe it. â Claire, I heard him. There is no way that man loves anyone but ye.â
 The bitterness in my retort surprised me as much as Jenny, âHe doesnât need to love her Jenny.â
 I could hear static and the sound of Jenny picking something up and placing it down again. I didnât need to see her to know she was pacing, a tell when Jenny was thinking, similar to Jamieâs fingers running a rhythm on his thigh. Fraser quirks.
 âClaire â ya ken ye need to speak to him, yer not being honest with him either. â
 âNot yet- its â too â I cut off mid-sentence when my eye fell on an envelope amongst the post that was  strewn across the welcome mat.Â
 Mr William Fraser, followed by our address and in Jamieâs very distinguishable scrawl.
 âClaire, are ye there?â
 âOh yes sorry- yes âyes I am.â An urgency to get Jenny off the phone made me blurt out âI promise I will talk to him soon.â
 âJen I have to go Willie needs â â
 âAye, aye, go on then I will speak to ye tomorrow.â
 I heard a click at her end and grabbed the envelope from the floor ignoring the rest.
          ___________
  Willie ripped open the package with gusto, tongue hanging from his mouth in concentration. Toppling the contents on to the table, he clutched something resembling a brightly illustrated, bound journal.
 He cast it up into the air and excitedly declared âDa send me a book.â
 âSo it would seemâ I replied throwing my dubious gaze over it.
 The front cover was a sweeping landscape of fields and meadows, a little mole family standing front and centre arms and hands entwined with each other. I only needed to glance once to know that it was Jamieâs work. He had inherited Ellenâs artistic streak, and often drew funny cartoon characters to entertain Willie, this work had the same detailed sketching but with bright wisps of colour illuminating it.Â
 It wasnât unusual for Jamie to buy or send books to Willie; bedtime story was their thing whenever they were together. Jamie excelled at it, he read animatedly to Willie, giving each character a funny accent, making background sounds and explaining any detail Willie failed to grasp. In the short time he had lived together in Lallybroch I found myself being lulled into Willieâs room at night to hear Jamie read to him.
 The bound storybook I held in my hand now, was a first; Jamie had made an actual book just for Willie.
 The title at the top of it read, The Mole family and at the bottom, it said written and illustrated by James Fraser.
  âLook Mamaâ Willie was jumping up and down excitedly, âthose moles are us, see.â His little finger jamming each animal. âThe big mole looks like Da, he is really tall and has red curly hair, and he is wearing a kilt!â Willieâs eyes were wide as saucers as his gaze drifted to the littlest of the moles, who was wearing Willieâs favourite jeans, sweater combo, this mole had the same straight floppy red hair as Willie that made it so easy to pick him from a crowd.
 âThat one is me ââ he continued voice getting pitcher with each similarity he could find âoh and lookâ â he almost screeched â âthat pretty mole is you, mama.â
 I had never seen a pretty mole before and had to admit the mole Willie was now jabbing eagerly, was quite eye-catching, and there was little doubt this mole was female.
 She stood out from the rest of her family, wearing a pretty floral dress resembling something I owned and wore regularly, a matching flower stuck in long curly hair. However, what made her different to the others wasnât just her lack of red hair or feminine wardrobe, it was the detail Jamie went to in adding golden flecks to her eyes making them look like they were glowing. She had long fluttering eyelashes sweeping wide across her upper lid and a wide smile lighting her face. Her femininity was further emphasised by the usual lack of roundness moles typically possessed, this mole had an accentuated curvy figure with a controversial voluptuous cleavage for a childrenâs book.
 Jamie had further personalised this mole to resemble me by adding a shiny stethoscope, which hung loosely around her neck.
 I bristled at the happy little family bounding up from the page, suddenly angry at whatever Jamie was trying to pull off. Paint a picture of a happy mole family running through a pretty garden, make it resemble the woman you fucked over and all should be forgiven?
  Willie peeked inside the front cover which had an inscription a printed version of Jamieâs scrawl, he hastily thrust the book into my hand, âwhat does it say mama?â rubbing his little hands together, smile wide and brimming with delight.
 I inhaled deeply as I glanced at the typescript and cursed Jamie with everything I possessed.
 âWellâ I began evenly, âthe name is called the Mole Familyâ I traced my finger lightly over the title. Imagining Jamie bent over a desk plotting his story out.
 Willie nodded his head, âaye and what does that say at the bottom?â
 I puffed out an incredulous  breath and damned Jamie Fraser to hell and back.
 âIt says: Mama please read this to Willie, all my love Da.â
 My childish heart felt like picking up my phone and texting him to read his own bloody story.
 However, I wouldnât deprive Willie of anything and certainly not something that had lit up his whole face the way this book had.
Letting out a shaky breath I told Willie to brush his teeth and to hop into bed, âI will be there in a minute.â
 ________
 Holding Willie under the crook of my arm I opening the first page of Jamieâs book, feeling ridiculously nervous for someone about to undertake what most parents routinely went through every evening.  I couldnât shake the feeling that this book was more than just a bedtime story.
 Once upon a time, way up in the Scottish highlands lived a mole family.
Da Mole, Mama Mole and Baby Mole.
They loved their home, and their little farm and being together â
  Jamie had illustrated each page, showing the moles living and working happily on their farm, to build the story he had included the moles with different types of dialogue, riding horses, playing with the baby mole, all lending to the storybook happy family image most childrenâs books captured.
 I turned a page to find the mole family standing outside a house that looked eerily familiar to what the finished product of our house at Lallybroch should have looked like; Willie didnât seem to notice my hesitancy at turning the next page, as if I was waiting for something to explode from the book.
 Willie pointed at the smallest mole riding a large black horse, tilting his head up to look at me,
 âlook mama Iâm riding Donasâ he declared proudly.
 âSo you are.â The next page showed the mole talking to a new family of animals. âWhat are those?â Willie asked, his brows creased in confusion. âWait until I get to that bitâ my curiosity had me skimming ahead quickly, suddenly desperate to know where this story was going.
 One day a weasel family came to visit. They asked Da mole to go and work for them at their home, far away from Scotland. Da Mole didnât want to work for the Weasel family, so he said no thank you, he would hate to leave Mama mole and baby mole. However, the Weasels were a mean family and _____
  My heart beat fast in my chest as I read on to Willie, revealing the Weasel family threatened and fought with the moles until Da mole went with them.
 Willieâs brow creased and his chin dimpled while he listened to each twist and turn.
  I couldnât deny I was more familiar with the beginning of the story but once I turned the page to see Da mole working at the weasel farm and a new character introduced on the page next to him. I almost forgot I was reading a four-year-old story and found my eyes jumping ahead as I eyed a puffin dressed in a police uniform that Jamie had drawn in great detail.
 The puffin had floppy blonde hair, with boggle eyes, he was dressed head to toe in police uniform.
 Da mole was working one day on the Weasel farm when Puffin the policeman came to see him â
 My lips trembled, and my sweaty palms fumbled with the pages as I read over the piece about the policeman to Willie and again in my head. The policeman said the weasels had a lot of money that didnât belong to them, and if Da mole could pretend to be their friend, the weasels might show Da mole where they hid their money.
 I almost forgot to read the bit to Willie where the puffin would watch and listen to everything Da mole did so he could catch the weasels I was so intent on working out what this meant for Jamie in Hellwater.
 âye skipped a bit mamaâ Willie pushed his hand to where the puffin was observing Da mole from a distance.
 As the story played out, I found myself ignoring Willieâs requests to put different accents on the animals as Jamie did. Instead carefully piecing  together the plot Jamie was laying out, and the message he sent when the policeman told the mole of the risks to his family should they find out what he was doing.
 Jamie had worked towards Willie seeing how much the mole missed his family, a little thought cloud bubble over the moleâs head, imagining what it would be like to be home again in bed with his family all of them curled up contently in one bed.
 Willieâs head bent solemnly, âthatâs like pur Da.â
 I turned the next page to images and text of Da mole befriending the weasels so that they led him to the money. Willie complained I was reading too fast.
  The quality of the bedtime story taking a backseat as I grappled to understand what this all meant.
 As I reached the last few pages, Da mole was stood in a room filled with money, showing it to a little army of puffins. Willie laughed at the funny caricature faces Jamie had given each one.
 I licked my lips nervously as the story concluded with Da mole back and happy with his family. The weasels locked up. Willie sighed contentedly, âthat was sooo good mama, will ye read it one more time?â
 I could barely stop myself from tearing out of the room to scan the book alone. Turning off the light I promised Willie I would read it one more time in the morning before school.
 A few minutes later I was bent over the book in the kitchen, going through each detail. Panic rising in my belly as I examined each picture again, this time noticing small details that my addled brain had missed, the puffin pointing at a phone and telling the mole not to use it, âif the weasels should find out.â  Written in the dialogue box about the puffins head.
 I let my fingers feel each drawing, feather-light touching the words images of Jamie plotting, planning and taking the time to sketch something to match each twist and turn so that he could tell me a story.
 This wasnât the action of someone who was cheating with another woman; this was someone who was caught and still found a way â to make me see.
 My fingers suddenly felt something like brail along the last page.
 I traced each letter with my finger before hastily jotting it on a notepad beside me.
 Gaelic words, I knew few but recognised the first two instantly. Jamie used the first one when he slipped his ring on my finger. My bhean, my wife. The second he regularly used when talking about Willie. Mo Mhac, my son.
 I grabbed my phone from the table and typed in the last two, tears flowing down my cheeks when the translation popped up on the screen.
 Mo bhean
Mo mhac
Mo h-uile rud.
Na dĂŹochuimhnich
 My Wife, My Son, My everything, donât forget.
487 notes
¡
View notes
Text
Smart cast doesn't work well with computed properties
In Kotlin, you can smart cast a property of a class in the same module, but you cannot do that when the class is in another module.
class X(val y: String?) {} fun s(s: String) {} val x = X() if (x.y != null) { s(x.y) // This is valid only when X is in the same module }
This is because the compiler cannot assume y isn't a computed property if X is in another module. It can return a different value when you call it twice if y is a computed property.
On the other hand, TypeScript seems to allow this.
interface I { readonly y: string | null; } function s(s: string) { console.log(s); } function i(i: I) { if (i.y != null) { s(i.y); } } class X implements I { get y(): string | null { return Math.random() > 0.5 ? 'y' : null; } } i(new X());
As you can see, this can print null even though s won't take null. In i, the compiler assumes i.y always returns the same value.
0 notes
Text
A Brief Guide to Early Literary Dracula AUs
One of the coolest things about being a Dracula fan in the 2010s is all the recent publication of materials shedding light on all of the really bonkers alternate Draculas that either nearly became Dracula itself or spun off from the original 1897 text. So yeah... hereâs a rundown of the three weird psuedo-canonical AUs that this fin de siecle vampire novel just sort of... comes with.
Stoker's Notes/Typescript/"Dracula's Guest"
Bram's notes for Dracula indicate that he worked on the novel for at least seven years, that it went through many substantial changes in its plot and cast, and that he had a lot of completely metal ideas that either fate, his editors, or his slender grip on good taste did not permit to appear in the final novel. Some of these things appear in fragmentary form in the typescript for Dracula. Some of them got recycled into a short story later published as "Dracula's Guest." Some of them only appear scrawled in Stoker's atrocious handwriting on the various papers collected at the Rosenbach in Philadelphia.
Highlights:
Things initially were going to take place in Styria and the villain's name was going to be Count Wampyr.
Arthur doesn't exist and Jack/Lucy is canon.
Jonathan Harker has a "shrewd, skeptical sister."
There's a third heroine named Kate Reed (or Kate Lee) who is school chums with Lucy and Mina and apparently helps to spread the flow of gossip about Lucy and her curly-hair beau going to St. James concerts.
There's a painter named Francis who probably discovers that the Count (in addition to having no reflection and showing up as a skeleton in photographs) cannot even be painted.
Other unused characters include a philosophic historian, a paranormal investigator, and a pair of deaf/mute servants in the Count's employ.
The Count has a secret chamber where everything is blood red, and it's apparently really scary.
Quincey might be a professional inventor named Brutus Marix. He also might go to Transylvania in the middle of the book. Also, he just might SAVE THE DAY DURING THE FINAL BATTLE BY OPENING FIRE WITH AN EARLY FORERUNNER TO THE MACHINE GUN.
There appear to have been werewolves planned.
Jack has a spooky party at his house where everyone has to tell a ghost story like they're living it up at the Villa Diodati. Dracula shows up and is the thirteenth guest at this super goth affair and presumably tells the spookiest story of all.
Jonathan spends three chapters/100 pages doing all sorts of crazy stuff that happens before what we now think of a Chapter 1 of Dracula. These shenanigans include encountering the Count pretending to be dead in a Munich leichenhaus, going to see a performance of The Flying Dutchman, and doing all that incredibly spooky stuff in "Dracula's Guest" where he has adventures with wolf friends on Walpurgisnacht.
Castle Dracula sinks into the earth in a VOLCANIC EXPLOSION after Dracula dies.
There is also mention of Dracula FLYING out of his coffin into the air during the final confrontation and the Brides getting taken out by chance BOLTS OF LIGHTNING.Â
Seriously. We have legitimate evidence that were we but in the true and righteous timeline, Dracula would have ended with lightning bolts and machine guns going off in an aerial vampire battle before a volcano explodes.
Makt Myrkranna (AKA Powers of Darkness AKA Icelandic Bootleg Porno Dracula)
So a few years after Dracula was published, it appears that somebody in Sweden ripped it off, made it much much more Hammer Horror, and published it as their own thing called MĂśrkrets Makter (Powers of Darkness). Then, after that, Valdimar Ăsmundsson in Iceland ripped that off and republished it as his own thing called Makt Myrkranna (...also Powers of Darkness). This latter work just got translated into English in 2017, and there's been intense speculation as to whether or not whomever originally wrote this thing had anything to do with Bram Stoker and his early drafts for the novel, given that it is headed by a preface that is controversially claimed to have been written by Bram, himself.Â
Highlights:
The first four chapters of the book (the ones everyone tends to really like) are now massively massively expanded, and Jonathan Harker (now named Thomas) gets to spend much more time exploring the castle, trying to escape, having the Count tell him creepy sexual anecdotes, and watching busty women get murdered.
The three women in the castle have been condensed into one woman, who seems to be the Count's vampiric, incesty bride/cousin/whatever and whose death involved her being locked in a bedroom with her lover until he went mad and threw himself out a window.
Instead of finding a secret room of boxes with dirt in them, Jonathan Thomas finds a secret ritual orgymurder room where primordial ape men engage in forbidden revels while the Count bites hypnotized virgins to death.
Everything that is not in the massively expanded castle section is barely sketched out summaries of lots and lots of wacky things happening with no real explanation (apparently these portions were treated with more detail in at least one version of MĂśrkrets Makter, but that's not available in English yet).
Lucy (now Lucia) becomes a vampire, but she is never staked, and her plot is never really resolved. Arthur, convinced she is alive after people watch her get back up from being dead, orders that people leave out some blankets and snacks for her (very considerate), and then that thread just sort of ends.
Renfield doesn't exist. Jack sort of makes up for this gap in the novel's tragically dead madmen quota by going mad and dying himself.
Said going mad and dying is facilitated by him attending one two many freaky mesmerism parties at Carfax with the Count's posse of debauched, anarchist, international conspirator, orgymurder cultist noblemen.Â
Then like... a mysterious violinist shows up at his asylum and the next thing you know, the Count & Co. have taken over the joint, Quincey has to pretend to go crazy to infiltrate, and the entire place burns down.Â
There is actually some sort of police investigation into all of the many many many illegal things going on. After Van Helsing knifes Dracula to death, Quincey takes the fall for him, but the investigators don't end up taking him to trial.
KazÄąklÄą Voyvoda (AKA Impaling Voivode AKA Dracula in Istanbul AKA Turkish Nationalist Propaganda Bootleg Dracula)
Taking a cue from Ăsmundsson and whomever the MĂśrkrets Makter guy is (or not...), Turkish author Ali RÄąza Seyfi wrote his own pirated version of Dracula and published it as his own work in 1928. Unlike the Makt Mykrannaverse, the world of KazÄąklÄą Voyvoda is fairly faithful to the original text... save that the action is transposed from London to Istanbul, the events of the story now postdates the Turkish War of Independence, and the entire cast (Dracula excepted) is now very Turkish and very fond of waxing eloquent about their immense national pride in being very Turkish.
Highlights:
Dracula is explicitly identified as being Vlad III, and he is a marauding terrible foreign menace from the exotic West, persecuting the good Eastern folk of Istanbul just as he historically persecuted and impaled their ancestors before them. Anyone who has ever read and enjoyed any academic essay on Dracula and the colonial gaze may begin to salivate uncontrollably.
Forty-seven years before Salemâs Lot, Seyfi establishes that pretty much any religious symbol works on a vampire if you believe in it, and everyone throughout the text waves around charms made out of suras of the Koran and such to great effect.
Azmi (Jonathan) gets the tiniest scraps of expanded backstory in which we learn about his childhood predisposition towards fainting and the existence of his pious mother who took him to saintsâ shrines in the hopes he might faint less.
GĂźzin (Mina) is no longer one of Draculaâs victims (unlike in the 1953 film adaptation of this book). She is, however, still an incredibly hardcore researcher nerd who makes sure to tell her fiance all sorts of cool Vlad III history facts.
Turan (Arthur), Afif (Jack), and Ăzdemir (Quincey) all served together during the war and became bros that way instead of just being three guys who went on crazy globetrotting adventures together before all independently deciding to propose to the same girl.Â
ResuhČ (Van Helsing) makes sure to drop a line reminding everyone of that time they all did blood tests and found out their blood types are compatible... you know... just in case anybody in this post-blood-typing era might be doing a bunch of blood transfusions and worrying about fatal hemolytic reactions.
#Bram Stoker#Dracula#Powers of Darkness#Dracula in Istanbul#Valdimar Asmundsson#Makt Myrkranna#Morkrets Makter#Ali Riza Seyfi#Kazikli Voyvoda#Drakula Istanbul'da#vampires#assault
1K notes
¡
View notes
Text
Ark Core Desktop Wallet
Increased blockchain usage is a very good thing, right? ARK is definitely a fairly fresh job aimed at increasing user adoption of blockchain technologies, among other things. Nonetheless, one of the major concepts in the ARK whitepaper is that that they will bring blockchain technological innovation to the masses. They will intend on doing this by simply providing �Practical Solutions regarding Real People� along with Swift Secure Core Technology�. A single way ARK is doing it is by creating a good environment that will let any individual or even company to create their unique wash blockchain in a new couple of minutes. To get this to propagate as immediately and extensively as possible typically the ARK team has place a great emphasis on adding as many coding languages together with blockchains as possible, and providing the very best possible user experience. On this ARK Coin review you will take an in-depth glance at the project as well since the technology together with potential clients for the coin themselves. Increased blockchain usage is definitely the good thing, ideal? ARK is a rather new project aimed at increasing user use connected with blockchain technology, amongst other factors. But, one of the crucial concepts in the ARK whitepaper is that that they will bring blockchain technological innovation to the masses. That they plan on performing that by providing �Practical Services with regard to Authentic People� as very well as Fast Protect Central Technology�. One way ARK is carrying out this can be by means of generating an ecosystem that will allow any individual or maybe business to build their very own standalone blockchain inside of a few minutes. To get this to spread as quickly plus commonly as possible the particular ARK staff has put an emphasis on incorporating like many coding languages and even blockchains as possible, together with providing the best achievable user encounter. In this ARK Coin overview many of us will take an exhaustive look at the venture as well as typically the technologies and prospects for the gold coin itself. Bounce to ?? [hide] 1 ARK Background a couple of How Does ARK Function? 2. 1 Sensible Bridges 2. 2 Option Development Languages 2. 3 Drive Button Deployable Blockchains a few Delegated Proof-of-Stake four ARK Token 5 ARK Charges 6 ARK Functionality several Where to Buy ARK 8 Where to Retailer ARK 9 ARK Use outsourcing for Voting 10 Conclusion ARK History The ARK blockchain was launched in February 2017 by some sort of group regarding 27 member spread over the planet, making regarding a really decentralized workforce. Currently the core staff consists of 17 members. A person of the primary creators, and the current CTO involving ARK, is FOREX TRADING Thoorens, who was likewise some sort of center developer at Lisk just before working about the ARK venture. ARK was modeled greatly upon Bitshares, Lisk plus Crypti, three older tasks all using the Delegated Evidence of Stake (dPoS) general opinion protocol. This is a good different associated with traditional Proof-of-Stake (PoS) comprehensive agreement algorithms. How Make a difference ARK Get the job done? There will be Windows ARk Coin Wallet appearing built into the key ARK ecosystem which can help the venture gain its goal of getting blockchain technology more accessible. All these key features include: SmartBridges Alternative Programming Languages Thrust Button Deployable Blockchains Wise Bridges The Smart Connect notion will be employed by ARK to produce �bridges� involving different opuesto blockchains. In essence ARK can grow to be an intermediary between your blockchains, allowing for transmission concerning disparate chains, and the power to trigger functions on other chains. Even though other jobs have been working on a new equivalent function, this remains a thing that isn�t currently possible. Ark Smart Bridge Overview regarding ARK Smart Bridges. Source: ark. io The seriously great matter is that will SmartBridges can be made it possible for with nothing more in comparison with a bit of value provided simply by ARK. One use advantages of SmartBridges might be through swaps, which in turn could use encoded audience members to determine when a business deal can be an exchange business deal, and then approach those people transactions automatically even though now charging their typical costs. For example, a user could send 100 ARK to their Coinbase pocket, in addition to Coinbase would recognize typically the transfer as a good swap transaction and quickly switch the ARK to ETH before depositing this within the users budget. Alternate Programming Languages The ARK builders were very clear in their purpose to allow development in as numerous coding dialects as achievable, hence which include as many software coders as potential. Currently all of often the right after programming languages happen to be supported by simply ARK: Python Elixer RPC Java . INTERNET Head out PHP/Laravel TypeScript API Nucleid Ruby Swift iOS Symfony Javascript Kotlin Lua Typically the ARK team is definitely also guaranteeing support regarding R, C, Advanced PowerShell, Rust, and C++ is going to soon be available. Press Button Deployable Blockchains This can allow anyone to effortlessly make up the ARK blockchain and create their unique blockchain job. Yes, is considered identical for you to Ethereum, although without typically the cost. And these recently deployed chains will are provided with SmartBridges already entirely functional. Delegated Proof-of-Stake Alternatively than using the controversial proof-of-work consensus procedure, ARK is definitely running with a good Delegated Proof of Stake comprehensive agreement algorithm. This implies no costly components and large electricity consumption is needed, as the ARK network is anchored by means of delegates. Anyone may be a use outside agencies for, yet currently merely 51 people actually become delegates, and these are picked by way of the ARK expression owners through a voting program. Each delegate gets 2 ARK for each one block that they forge, in addition to since blocks are generally cast every single 8 secs all these delegates can make over 200 ARK per moment. ARK token holders may be each allowed one vote for delegate, which costs first ARK. It is likewise possible to unvote your delegate plus vote intended for a different delegate as well as the cost is 1 ARK every time you vote or unvote. The greater ARK tokens presented, the harder powerful and individuals have your say is. Delegated Evidence of Stake Delegate Facts of Stake Case in point. Impression Source. You�ll see that use outsourcing for job hopefuls have written recommendations detailing how they will continue to work to secure the networking create ARK better intended for everyone. 1 well-liked means of obtaining electoral votes is through profit posting. Due to the fact each of the fifty-one delegates receives the praise to get forging new blocks, it is possible for them to share these benefits with those that choose them in a sort of dividend technique. One more popular course with regard to future delegates is to operate a growth project that plots on or improves often the ARK ecosystem, and throughout several cases these delegates present an equity position in the new project, or offer services for cost-free. ARK Expression ARK seemed to be launched in early 2017 with 100 million tokens, and with the recent 8 subsequent block time period there are 15, 700 new ARK created any day. Assuming this specific doesn�t change, ARK has a good decreasing inflation amount, which often is 6. 31% from the first year, but is going to decrease to 4. 02% by the tenth calendar year. This drop is a long way less impressive than that will seen using Ethereum or perhaps Lisk. Typically the 8 next block time is one particular of the quicker amid cryptocurrencies. Ethereum is close up having a 14 second block time, yet Bitcoin offers a 15 minute prevent time. Along with have speedy block times, each prohibit can process 25 orders. While this excellent, often the ARK team has now explained in their whitepaper that they may make this scalable by improving the number of transactions processed by every single block, as well like reducing the block period. ARK Fees The system price for sending ARK to another wallet is 0. 1 ARK, however this specific is designed to transformation as the network increases larger and becomes better. If you wish to register as a delegate it costs 25 ARK, and to vote as well as unvote a delegate charges first ARK. These expenses usually are planned to be reduced together with the next core update, and will then turn out to be just 0. 01 ARK as a network cost for sending, zero. 02 ARK for voting about a delegate, and 10 ARK to register like a assign. All service fees are paid to the particular forging delegate which functions the block containing these fees. ARK Performance As with most cryptocurrencies the particular price of ARK has been heavily influenced by way of its own developmental milestones, but in addition by the price tag of Bitcoin, containing possessed an huge impact in the overall cryptocurrency markets. This particular means we possess seen attracts and valleys in this price of ARK considering the idea had its ICO in 2016. The first raise occurred in 06 2017, if the token hit $1. 2009 after typically the developers released a collection for Java help with the platform. With Coffee being one of often the most popular programming 'languages' the community was clearly enthusiastic by the media and directed price higher accordingly. We can easily envision a good nice spike may happen when languages such as C++ are additional. ARK Gold coin Performance ARK Gold coin Functionality. Source: Coin Promote Hat The next spike took place in Sept. 2010 2017, with often the cost reaching $3. 96 following the ARK team introduced a desktop wallet the fact that resolved many reported bugs in the earlier type of typically the desktop pocket book. The upgrade also included assistance to get Ledger, one of this most famous hardware wallets. The biggest spike got in January 2018 while the entire cryptocurrency marketplace rallied. Price hit $9. 29 at that time, nonetheless that has due to the fact downed rather far, hitting $1. forty one as regarding late August 2018 with the entire cryptocurrency industry under pressure for just about the entire starting regarding 2018. Where to Purchase ARK The largest dealing areas for ARK will be Binance and Bittrex. With Binance each BTC and even ETH are poular stock trading pairs, although Bittrex views mostly BTC trades. ARK also sees trading up Upbit and the biggest trade quantity there is against the Korean Was the winner. There are some scaled-down exchanges supplying ARK, although volumes may be small. Wherever to Store ARK Often the easiest place to retail outlet your ARK is throughout one of several wallets presented upon their internet site. You include three options: Desktop computer Wallet Paper Wallet Internet En aning Wallet The pc finances is a very fine choice as being the design can be quite good together with wonderful is excellent. You could also employ the Ledger hardware pocket book if you�re after a lot more safety. Or for individuals on the go you can find mobile versions of often the ARK wallet for each Android mobile phone and iOS. Each variants are ranked 5-stars, nevertheless to be sure they haven�t acquired numerous reviews to date. ARK Delegate Voting If you happen to be intending on buying and positioning ARK you probably need to vote for some sort of delegate as soon while you get your ARK off the exchange and even with your own wallet. It is just one ARK to perform so, and you can easily use the vote on a good delegate which will pay a person dividends, which should help you recover the cost of voting initially. Or in the event that you prefer you can get some sort of delegate who�s working on a cool project you�d want to support. Voting is effortless. After you have on least 1 ARK inside your wallet simply demand �Votes� tab. As soon as presently there you�ll click �Add Delegate� and you�ll get a new pop-up where you might vote for one regarding the fifty-one existing delegates, or if you love you can easily get into the name associated with one more user you�d like to vote for. Choose a delegate and make sure the checkbox next to your selected use outsourcing for is checked after which simply click �Vote�. Finally you are going to require to enter your passphrase to confirm your election. You are able to change your delegate vote any time, nonetheless an individual will have to give a single ARK each time you do so. Summary The ARK team attempts be building a beneficial resource for that blockchain environment as a whole. They will may possibly not be the particular only assignment trying in order to attach disparate blockchains, but that doesn�t make their particular work any less precious, specially if they ending up making it where other folks neglect. The roadmap getting implemented from the team is quite ambitious, although the fact that simply means if the workforce is successful these people should be wildly productive. Personally I like this type of assignment of which aims to create some sort of useful user interface, plus make blockchain technology attainable by the lots. I could see ARK getting one of the long term survivors in the blockchain revolution.
1 note
¡
View note
Link
Introduction
With TypeScript we get a unified class construct in JavaScript. The syntax is based on the ES6 version, preparing TypeScript to remain a full superset of JavaScript even with ES6 implementations. Of course TypeScript compiles down to ES3 or ES5, which means that this class construct will be decomposed to something that is available right now: again the prototype mechanism. Nevertheless, what remains is code that is readable, cross-implementation (ES3 / ES5) safe and agrees on a common base. With my own approach (oop.js) no one besides me did know what was going on without reading the helper code. With TypeScript a broad set of developers uses the same pattern, as it is embedded in the language.
It was therefore just natural to convert the Mario5 project to TypeScript. What makes this worth an article on CodeProject? I think it is a nice study how to convert a project. It also illustrates the main points of TypeScript. And finally it gives a nice introduction to the syntax and the behavior. After all, TypeScript is easy for those who already know JavaScript and makes it easier to approach JavaScript, for those who do not have any experience yet.
Background
More than a year ago Anders Heijlsberg announced Microsoft's new language called TypeScript. This was a surprise for most people, as Microsoft (and especially Anders) seemed to be against dynamic languages, in particular JavaScript. However, it turned out, that Microsoft realized what a big opportunity the centralization of general purpose programming to web programming is. With JavaScript for Windows Store apps, the ongoing hype with node.js and the NoSQL movement with document stores that use JavaScript for running queries, it is obvious that JavaScript is definitely important.
Remark: Anders joined the TypeScript team at some point (v0.8) in the development. It is unclear if he invented the language or if somebody else came up with the idea. Nevertheless the team is currently lead by Anders and given his experience and expertise, it is certainly good to have him in charge of the project.
The realization did influence the decision on the design of a new language. Instead of creating a new language from the ground up (like Google did with Dart), Anders decided that any language that may be still established has to extend JavaScript. No solution should be orthogonal. The problem with CoffeeScript is that it hides JavaScript. This may be appealing for some developers, but for most developers it is an absolute exclusion criterion. Anders decided that the language has to be strongly typed, even though only an intelligent compiler (or transpiler to be more correct) will see these annotations.
So what happened? A true superset of ECMAScript 5 has been created. This superset has been called TypeScript to indicate the close relationsship with JavaScript (or ECMAScript in general), with the additional type annotations. Every other feature, such as interfaces, enums, generics, casts, ... follows from these type annotations. In the future TypeScript will evolve. There are two areas:
Embracing ES6 to remain a true superset of JavaScript
Bringing in further features to make JS development easier
The primary benefit of using TypeScript is two-fold. On the one side we can take the advantage of being informed of potential errors and problems during compile-time. If an argument does not fulfill a given signature, then the compiler will throw an error. This is especially useful when working with larger teams or an a bigger project. The other side is also interesting. Microsoft is known for their excellent tooling with Visual Studio. Giving JavaScript code a good tooling support is tedious, due to the dynamic nature of JavaScript code. Therefore even simple refactoring tasks such as renaming a variable cannot be performed with the desired stability.
In the end TypeScript gives us great tooling support combined with a much better idea about how our code will work. The combination of productivity plus robustness is the most appealing argument for using TypeScript. In this article we will explore how to convert existing projects. We will see, that transforming a code to TypeScript can be done incrementally.
Converting the existing project
TypeScript does not hide JavaScript. It starts with plain JavaScript.
The first step in utilizing TypeScript is of course to have TypeScript source files. Since we want to use TypeScript in an existing project, we'll have to convert these files. There is nothing to do here as a requirement, however, we'll just rename our files from *.js to *.ts. This is just a matter of convention, nothing that is actually required. Nevertheless, as the TypeScript compiler tsc usually considers *.ts files as input, writing *.js files as output, renaming the extension ensures that nothing wrong happens.
The next subsections deal with incremental improvements in the conversion process. We now assume that every file has the usual TypeScript extension *.ts, even though no additional TypeScript feature is used.
References
The first step is to supply references from single JavaScript files, to all other (required) JavaScript files. Usually we would only write single files, which, however, (usually) have to be inserted in a certain order in our HTML code. The JavaScript files do not know the HTML file, nor do they know the order of these files (not to speak of which files).
Now that we want to give our intelligent compiler (TypeScript) some hints, we need to specify what other objects might be available. Therefore we need to place a reference hint in the beginning of code files. The reference hint will declare all other files, that will be used from the current file.
For instance we might include jQuery (used by, e.g., the main.ts file) by its definition as via:
/// <reference path="def/jquery.d.ts"/>
We could also include a TypeScript version of the library, or the JavaScript version, however, there are reasons for including the definition file only. Definition files do not carry any logic. This will make the file substantially smaller and faster to parse. Also, such files will usually contain much more / better documentation comments. Finally, while we would prefer our own *.ts files to *.d.ts files, in case of jQuery and other libraries the original has been written in JavaScript. It is unclear, if the TypeScript compiler is satisfied with the source code. By taking a definition file, we can be sure that everything works.
There are reasons to write plain definition files ourselves, as well. The most basic one is covered by the def/interfaces.d.ts file. We do not have any code, which would make a compilation irrelevant. Referencing this file on the other hand makes sense, since the additional type information provided by the file helps in annotating our code.
Annotations
The most important TypeScript feature is type annotations. Actually, the name of the language indicates the high importance of this feature.
Most type annotations are actually not required. If a variable is immediately assigned (i.e. we define a variable, instead of just declaring it), then the compiler can infer the type of the variable.
var basepath = 'Content/';
Obviously, the type of this variable is a.string This is also what TypeScript infers. Nevertheless, we could also name the type explicitly.
var basepath: string = 'Content/';
Usually we do not want to be explicit with such annotations. It introduces more clutter and less flexibility than we aim for. However, sometimes such annotations are required. Of course the most obvious case appears, when we only declare a variable:
var frameCount: number;
There are other scenarios, too. Consider the creation of a single object, that may be extended with more properties. Writing the usual JavaScript code is definitely not enough information for the compiler:
var settings = { };
What properties are available? What is the type of the properties? Maybe we don't know, and we want to use it as a dictionary. In this case we should specify the arbitrary usage of the object:
var settings: any = { };
But there is also another case. We already know what properties might be available, and we only need to set or get some of these optional properties. In that case we can also specify the exact type:
var settings: Settings = { };
The most important case has been omitted so far. While variables (local or global) can be inferred in most cases, function parameters can never be inferred. In fact function parameters may be inferred for a single usage (such as the types of generic parameters), but not within the function itself. Therefore we need to tell the compiler what type of parameters we have.
setPosition(x: number, y: number) { this.x = x; this.y = y; }
Transforming JavaScript incrementally with type annotations therefore is a process, that starts by changing the signature of functions. So what about the basics of such annotations? We already learned that number, stringand any are built-in types, that represent elementary types. Additionally we have boolean and void. The latter is only useful for return types of functions. It indicates that nothing useful is returned (as JS functions will always return something, at least undefined).
What about arrays? A standard array is of type any[]. If we want to indicate that only numbers can be used with that array, we could annotate it as number[]. Multi-dimensional arrays are possible as well. A matrix might be annotated as number[][]. Due to the nature of JavaScript we only have jagged arrays for multi-dimensions.
Enumerations
Now that we started annotating our functions and variables, we will eventually require custom types. Of course we already have some types here and there, however, these types may be less annotated than we want to, or defined in a too special way.
Sometimes there are better alternatives offered by TypeScript. Collections of numeric constants, for instance, can be defined as an enumeration. In the old code we had objects such as:
var directions = { none: 0, left: 1, up: 2, right: 3, down: 4 };
It is not obvious that the contained elements are supposed to be constants. They could be easily changed. So what about a compiler that might give us an error if we really want to do nasty things with such an object? This is where enum types come in handy. Right now they are restricted to numbers, however, for most constant collections this is sufficient. Most importantly, they are transported as types, which means that we can use them in our type annotations.
The name has been changed to uppercase, which indicates that Direction is indeed a type. Since we do not want to use it like an enumeration flag, we use the singular version (following the .NET convention, which makes sense in this scenario).
enum Direction { none = 0, left = 1, up = 2, right = 3, down = 4, };
Now we can use it in the code such as:
setDirection(dir: Direction) { this.direction = dir; }
Please note that the dir parameter is annotated to be restricted to arguments of type Direction. This excludes arbitrary numbers and must use values of the Direction enumeration. What if we have a user input that happens to be a number? In such a scenario we can also get wild and use a TypeScript cast:
var userInput: number; // ... setDirection(<Direction>userInput);
Casts in TypeScript work only if they could work. Since every Direction is a number, a number could be a valid Direction. Sometimes a cast is known to fail a priori. If the userInput would be a plain string, TypeScript would complain and return an error on the cast.
Interfaces
Interfaces define types without specifying an implementation. They will vanish completely in the resulting JavaScript, like all of our type annotations. Basically they are quite similar to interfaces in C#, however, there are some notable differences.
Let's have a look at a sample interface:
interface LevelFormat { width: number; height: number; id: number; background: number; data: string[][]; }
This defines the format of a level definition. We see that such a definition must consist of numbers such as,widthheight, background and an.id Also, a two-dimensional string-array defines the various tiles that should be used in the level.
We already mentioned that TypeScript interfaces are different to C# interfaces. One of the reasons is that TypeScript interfaces allow merging. If an interface with the given name already exists, it won't be overwritten. There is also no compiler warning or error. Instead the existing interface will be extended with the properties defined in the new one.
The following interface merges the existing Math interface (from the TypeScript base definitions) with the provided one. We gain one additional method:
interface Math { sign(x: number): number; }
Methods are specified by specifying parameters in round brackets. The usual type annotation is then the return type of the method. With the provided interface (extension) the TypeScript compiler allows us to write the following method:
Math.sign = function(x: number) { if (x > 0) return 1; else if (x < 0) return -1; return 0; };
Another interesting option in TypeScript interfaces is the hybrid declaration. In JavaScript an object is not limited to be a pure key-value carrier. An object could also be invoked as a function. A great example for such a behavior is jQuery. There are many possible ways to call the jQuery object, each resulting in a new jQuery selection being returned. Alternatively the jQuery object also carries properties that represent nice little helpers and more useful stuff.
In the case of jQuery one of the interfaces looks like:
interface JQueryStatic { (): JQuery; (html: string, ownerDocument?: Document): JQuery; ajax(settings: JQueryAjaxSettings): JQueryXHR; /* ... */ }
Here we have to possible calls (among many) and a property that is directly available. Hybrid interfaces, therefore, require that the implementing object is, in fact, a function, that is extended with further properties.
We can also create interfaces based on other interfaces (or classes, which will be used as interfaces in this context).
Let's consider the following case. To distinguish points we use the Point interface. Here we only declare two coordinates, x and y. If we want to define a picture in the code, we need two values. A location (offset), where it should be placed, and the string that represents the source of the image.
Therefore we define the interface to represent this functionality to be derived / specialized of the Pointinterface. We use the extends keyword to trigger this behavior in TypeScript.
interface Point { x: number; y: number; } interface Picture extends Point { path: string; }
We can use as many interfaces as we want, but we need to separate them with commas.
Classes
At this stage we already typed most of our code, but an important concept has not been translated to TypeScript. The original codebase makes use of a special concept that brings class-like objects (incl. inheritance) to JavaScript. Originally this looked like the following sample:
var Gauge = Base.extend({ init: function(id, startImgX, startImgY, fps, frames, rewind) { this._super(0, 0); this.view = $('#' + id); this.setSize(this.view.width(), this.view.height()); this.setImage(this.view.css('background-image'), startImgX, startImgY); this.setupFrames(fps, frames, rewind); }, });
Unfortunately there are a lot of problems with the shown approach. The biggest problem is that it is non-normative, i.e. it is no standard way. Therefore developers who aren't familiar with this style of implementing class-like objects, cannot read or write code as they usually would. Also the exact implementation is unknown. All in all any developer has to look at the original definition of the Class object and its usage.
With TypeScript a unified way of creating class-like objects exists. Additionally it is implemented in the same manner as in ECMAScript 6. Therefore we get a portability, readability and extensibility, that is easy to use and standardized. Coming back from our original example we can transform it to become:
class Gauge extends Base { constructor(id: string, startImgX: number, startImgY: number, fps: number, frames: number, rewind: boolean) { super(0, 0); this.view = $('#' + id); this.setSize(this.view.width(), this.view.height()); this.setImage(this.view.css('background-image'), startImgX, startImgY); this.setupFrames(fps, frames, rewind); } };
This looks quite similar and behaves nearly identical. Nevertheless, changing the former definition with the TypeScript variant needs to be done in a single iteration. Why? If we change the base class (just called Base), we need to change all derived classes (TypeScript needs classes to inherit from other TypeScript classes).
On the other hand, if we change one of the derived classes we cannot use the base class any more. That being said, only classes, that are completely decoupled from the class hierarchy, can be transformed within a single iteration. Otherwise, we need to transform the whole class hierarchy.
The keywordextends has a different meaning than for interfaces. Interfaces extend other definitions (interfaces or the interface part of a class) by the specified set of definitions. A class extends another class by setting its prototype to the given one. Additionally, some other neat features are placed on top of this, like the ability to access the parent's functionality via.super
The most important class is the root of the class hierachy, called Base. It contains quite some features, most notably
class Base implements Point, Size { frameCount: number; x: number; y: number; image: Picture; width: number; height: number; currentFrame: number; frameID: string; rewindFrames: boolean; frameTick: number; frames: number; view: JQuery; constructor(x: number, y: number) { this.setPosition(x || 0, y || 0); this.clearFrames(); this.frameCount = 0; } setPosition(x: number, y: number) { this.x = x; this.y = y; } getPosition(): Point { return { x : this.x, y : this.y }; } setImage(img: string, x: number, y: number) { this.image = { path : img, x : x, y : y }; } setSize(width, height) { this.width = width; this.height = height; } getSize(): Size { return { width: this.width, height: this.height }; } setupFrames(fps: number, frames: number, rewind: boolean, id?: string) { if (id) { if (this.frameID === id) return true; this.frameID = id; } this.currentFrame = 0; this.frameTick = frames ? (1000 / fps / setup.interval) : 0; this.frames = frames; this.rewindFrames = rewind; return false; } clearFrames() { this.frameID = undefined; this.frames = 0; this.currentFrame = 0; this.frameTick = 0; } playFrame() { if (this.frameTick && this.view) { this.frameCount++; if (this.frameCount >= this.frameTick) { this.frameCount = 0; if (this.currentFrame === this.frames) this.currentFrame = 0; var $el = this.view; $el.css('background-position', '-' + (this.image.x + this.width * ((this.rewindFrames ? this.frames - 1 : 0) - this.currentFrame)) + 'px -' + this.image.y + 'px'); this.currentFrame++; } } } };
The implements keyword is similar to implementing interfaces (explicitely) in C#. We basically enable a contract, that we provide the abilities defined in the given interfaces within our class. While we can only extend from a single class, we can implement as many interfaces as we want. In the previous example we choose not to inherit from any class, but to implement two interfaces.
Then we define what kind of fields are available on objects of the given type. The order does not matter, but defining them initially (and most importantly: in a single place) makes sense. The functionconstructor is a special function that has the same meaning as the custom methodinit before. We use it as the class's constructor. The base class's constructor can be called any time via.super()
TypeScript also provides modifiers. They are not included in the ECMAScript 6 standard. Therefore I also do not like to use them. Nevertheless, we could make fields private (but remember: only from the view of the compiler, not in the JavaScript code itself) and therefore restrict access to such variables.
A nice usage of these modifiers is possible in combination with the constructor function itself.
class Base implements Point, Size { frameCount: number; // no x and y image: Picture; width: number; height: number; currentFrame: number; frameID: string; rewindFrames: boolean; frameTick: number; frames: number; view: JQuery; constructor(public x: number, public y: number) { this.clearFrames(); this.frameCount = 0; } /* ... */ }
By specifying that the arguments are public, we can omit the definition (and initialization) of x and y in the class. TypeScript will handle this automatically.
Fat arrow functions
Can anyone remember how to create anonymous functions in C# prior to lambda expressions? Most (C#) devs cannot. And the reason is simple: Lambda expressions bring expressiveness and readability. In JavaScript everything is evolving around the concept of anonymous functions. Personally, I only use function expressions (anonymous functions) instead of function statements (named functions). It is much more obvious what is happening, more flexible and brings a consistent look and feel to the code. I would say it is coherent.
Nevertheless, there are little snippets, where it sucks writing something like:
var me = this; me.loop = setInterval(function() { me.tick(); }, setup.interval);
Why this waste? Four lines for nothing. The first line is required, since the interval callback is invoked on behalf of the window. Therefore we need to cache the original this, in order to access / find the object. This closure is effective. Now that we stored the this in me, we can already profit from the shorter typing (at least something). Finally we need to hand that single function over in another function. Madness? Let's use the fat-arrow function!
this.loop = setInterval(() => this.tick(), setup.interval);
Ah well, now it is just a neat one-liner. One line we "lost" by preserving the this within fat-arrow functions (let's call them lambda expressions). Two more lines have been dedicated to preserving style for functions, which is now redundant as we use a lambda expression. In my opinion, this is not only readable but also understandable.
Under the hood, of course, TypeScript is using the same thing as we did before. But we do not care. We also do not care about MSIL generated by a C# compiler, or assembler code generated by any C compiler. We only care about the (original) source code being much more readable and flexible. If we are unsure about the wethis should use the fat arrow operator.
Extending the project
TypeScript compiles to (human-readable) JavaScript. It ends with ECMAScript 3 or 5 depending on the target.
Now that we basically typed our whole solution we might even go further and use some TypeScript features to make the code nicer, easier to extend and use. We will see that TypeScript offers some interesting concepts, that allow us to fully decouple our application and make it accessible, not only in the browser, but also on other platforms such as node.js (and therefore the terminal).
Default values and optional parameters
At this stage we are already quite good, but why leave it at that? Let's place default values for some parameters to make them optional.
For instance ,the following TypeScript snippet will be transformed...
var f = function(a: number = 0) { } f();
... to this:
var f = function (a) { if (a === void 0) { a = 0; } }; f();
The void 0 is basically a safe variant of undefined. That way these default values are always dynamically bound, instead of default values in C#, which are statically bound. This is a great reduction in code, as we can now omit essentially all default value checks and let TypeScript do the work.
As an example consider the following code snippet:
constructor(x: number, y: number) { this.setPosition(x || 0, y || 0); // ... }
Why should we ensure that the x and y values are set? We can directly place this constraint on the constructor function. Let's see how the updated code looks like:
constructor(x: number = 0, y: number = 0) { this.setPosition(x, y); // ... }
There are other examples, as well. The following already shows the function after being altered:
setImage(img: string, x: number = 0, y: number = 0) { this.view.css({ backgroundImage : img ? c2u(img) : 'none', backgroundPosition : '-' + x + 'px -' + y + 'px', }); super.setImage(img, x, y); }
Again, this makes the code much easier to read. Otherwise, the propertybackgroundPosition would be assigned with default value consideration, which looks quite ugly.
Having default values is certainly nice, but we might also have a scenario, where we can safely omit the argument without having to specify a default value. In that case we have still to do the work of checking if a parameter has been supplied, but a caller may omit the argument without running into trouble.
The key is to place a question mark behind the parameter. Let's look at an example:
setupFrames(fps: number, frames: number, rewind: boolean, id?: string) { if (id) { if (this.frameID === id) return true; this.frameID = id; } // ... return false; }
Obviously ,we allow calling the method without specifying the id parameter. Therefore we need to check if it exists. This is done in the first line of the method's body. This guard protects the usage of the optional parameter, even though TypeScript allows us to use it at free will. Nevertheless, we should be careful. TypeScript won't detect all mistakes - it's still our responsibility to ensure a working code in every possible path.
Overloads
JavaScript by its nature does not know function overloads. The reason is quite simple: Naming a function only results in a local variable. Adding a function to an object places a key in its dictionary. Both ways allow only unique identifiers. Otherwise we would be allowed to have two variables or properties with the same name. Of course there is an easy way around this. We create a super function that calls sub functions depending on the number and types of the arguments.
Nevertheless, while inspecting the number of arguments is easy, getting the type is hard. At least with TypeScript. TypeScript only knows / keeps the types during compile-time, and then throws the whole created type system away. This means that no type checking is possible during runtime - at least not beyond very elementary JavaScript type checking.
Okay, so why is a subsection dedicated to this topic, when TypeScript does not help us here? Well, obviously compile-time overloads are still possible and required. Many JavaScript libraries offer functions that offer one or the other functionality, depending on the arguments. jQuery for instance usually offers two or more variants. One is to read, the other to write a certain property. When we overload methods in TypeScript, we only have one implementation with multiple signatures.
Typically one tries to avoid such ambiguous definitions, which is why there is are no such methods in the original code. We do not want to introduce them right now, but let's just see how we could write t tohem:
interface MathX { abs: { (v: number[]): number; (n: number): number; } }
The implementation could look as follows:
var obj: MathX = { abs: function(a) { var sum = 0; if (typeof(a) === 'number') sum = a * a; else if (Array.isArray(a)) a.forEach(v => sum += v * v); return Math.sqrt(sum); } };
The advantage of telling TypeScript about the multiple calling versions lies in the enhanced UI capabilities. IDEs like Visual Studio, or text editors like Bracket may show all the overloads including the descriptions. As usual c,alls are restricted to the provided overloads, which will ensure some safety.
Generics
Generics may be useful to tame multiple (type) usages, as well. They work a little bit different than in C#, as well, since they are only evaluated during compile time. Additionally ,they do not have anything special about the runtime representation. There is no template meta programming or anything here. Generics is only another way to handle type safety without becoming too verbose.
Let's consider the following function:
function identity(x) { return x; }
Here the argument x is of type any. Therefore the function will return something of type any. This may not sound like a problem, but let's assume the following function invocations.
var num = identity(5); var str = identity('Hello'); var obj = identity({ a : 3, b : 9 });
What is the type of num, str and obj? They might have an obvious name, but from the perspective of the TypeScript compiler, they are all of type any.
This is where generics come to rescue. We can teach the compiler that the return type of the function is the calling type, which should be of the exact type that has been used.
function identity<t>(x: T): T { return x; } </t>
In the above snippet we simply return the same type that already entered the function. There are multiple possibilities (including returning a type determined from the context), but returning one of the argument types is probably the most common.
The current code does not have any generics included. The reason is simple: The code is mostly focused on changing states and not on evaluating input. Therefore we mostly deal with procedures and not with functions. If we would use functions with multiple argument types, classes with argument type dependencies or similar constructs, then generics would certainly be helpful. Right now everything was possible without them.
Modules
The final touch is to decouple our application. Instead of referencing all the files, we will use a module loader (e.g. AMD for browsers, or CommonJS for node) and load the various scripts on demand. There are many advantage to this pattern. The code is much easier to test, debug and usually does not suffer from wrong orders, as the modules are always loaded after the specified dependencies are available.
TypeScript offers a neat abstraction over the whole module system, since it provides two keywords (import and export), which are transformed to some code that is related to the desired module system. This means that a single code base can be compiled to AMD conform code, as well as CommonJS conform code. There is no magic required.
As an example the file constants.ts won't be referened any more. Instead, the file will export its contents in form of a module. This is done via:
export var audiopath = 'Content/audio/'; export var basepath = 'Content/'; export enum Direction { none = 0, left = 1, up = 2, right = 3, down = 4, }; /* ... */
How can this be used? Instead of having a reference comment, we use the require() method. To indicate that we wish to use the module directly, we do not write var, but import. Please note, that we can skip the *.tsextension. This makes sense, since the file will have the same name later on, but a different ending.
import constants = require('./constants');
The difference between var and import is quite important. Consider the following lines:
import Direction = constants.Direction; import MarioState = constants.MarioState; import SizeState = constants.SizeState; import GroundBlocking = constants.GroundBlocking; import CollisionType = constants.CollisionType; import DeathMode = constants.DeathMode; import MushroomMode = constants.MushroomMode;
If we would write var, then we would actually use the JavaScript representation of the property. However, we want to use the TypeScript abstraction. The JavaScript realization of Direction is only an object. The TypeScript abstraction is a type, that will be realized in form of an object. Sometimes it does not make a difference, however, with types such as interfaces, classes or enums, we should prefer import to var. Otherwise we just use var for renaming:
var setup = constants.setup; var images = constants.images;
Is this everything? Well, there is much to be said about modules, but I try to be brief here. First of all, we can use these modules to make interfaces to files. For instance the public interface to the main.ts is given by the following snippet:
export function run(levelData: LevelFormat, controls: Keys, sounds?: SoundManager) { var level = new Level('world', controls); level.load(levelData); if (sounds) level.setSounds(sounds); level.start(); };
All modules are then brought together in some file like game.ts. We load all the dependencies and then run the game. While most modules are just objects bundled together with single pieces, a module can also be just one of these pieces.
import constants = require('./constants'); import game = require('./main'); import levels = require('./testlevels'); import controls = require('./keys'); import HtmlAudioManager = require('./HtmlAudioManager'); $(document).ready(function() { var sounds = new HtmlAudioManager(constants.audiopath); game.run(levels[0], controls, sounds); });
The controls module is an example for a single piece module. We achieve this with a single statement such as:
export = keys;
This assigns the export object to be the keys object.
Let's see what we got so far. Due to the modular nature of our code we included some new files.
We have another dependency on RequireJS, but in fact, our code is more robust and easier to extend than before. Additionally, all dependencies are always exposed, which removes the possibility of unknown dependencies drastically. The module loader system combined with intellisense, improved refactoring capabilities and the strong typing added much safety to the whole project.
Of course not every project can be refactored so easily. The project has been small and was based on a solid code base, that did not rust that much.
In a final step we will break apart the massive main.ts file, to create small, decoupled files, which may only depend on some setting. This setting would be injected in the beginning. However, such a transformation is not for everyone. For certain projects, it might add too much noise than gain clarity.
Either way, for the Matter class we would have the following code:
/// <reference path="def/jquery.d.ts"/> import Base = require('./Base'); import Level = require('./Level'); import constants = require('./constants'); class Matter extends Base { blocking: constants.GroundBlocking; level: Level; constructor(x: number, y: number, blocking: constants.GroundBlocking, level: Level) { this.blocking = blocking; this.view = $('<div />').addClass('matter').appendTo(level.world); this.level = level; super(x, y); this.setSize(32, 32); this.addToGrid(level); } addToGrid(level) { level.obstacles[this.x / 32][this.level.getGridHeight() - 1 - this.y / 32] = this; } setImage(img: string, x: number = 0, y: number = 0) { this.view.css({ backgroundImage : img ? img.toUrl() : 'none', backgroundPosition : '-' + x + 'px -' + y + 'px', }); super.setImage(img, x, y); } setPosition(x: number, y: number) { this.view.css({ left: x, bottom: y }); super.setPosition(x, y); } }; export = Matter;
This technique would refine the dependencies. Additionally, the code base would gain accessibility. Nevertheless, it depends on the project and state of the code, if further refinement is actually desired or unnecessary cosmetics.
Credit
Florian Rappl
Florian lives in Munich, Germany. He started his programming career with Perl. After programming C/C++ for some years he discovered his favorite programming language C#. He did work at Siemens as a programmer until he decided to study Physics. During his studies he worked as an IT consultant for various companies. After graduating with a PhD in theoretical particle Physics he is working as a senior technical consultant in the field of home automation and IoT. Florian has been giving lectures in C#, HTML5 with CSS3 and JavaScript, software design, and other topics. He is regularly giving talks at user groups, conferences, and companies. He is actively contributing to open-source projects. Florian is the maintainer of AngleSharp, a completely managed browser engine.
Repository at GitHub
Points of Interest
One of the most asked questions in the original article has been where to acquire the sound / how to set up the sound system. It turns out that the sound might be one of the most interesting parts, yet I decided to drop it from the article. Why?
The sound files might cause a legal problem (however, the same could be said about the graphics)
The sound files are actually quite big (effect files are small, but the background music is O(MB))
Every sound file has to be duplicated to avoid compatibility issues (OGG and MP3 files are distributed)
The game has been made independent of a particular sound implementation
The last argument is my key point. I wanted to illustrate that the game can actually work without strongly coupling it to a particular implementation. Audio has been a widely discussed topic for web applications. First of all, we need to consider a series of formats since different formats and encodings only work on a subset of browsers. To reach all major browsers, one usually needs at least 2 different formats (usually consisting of one open and one proprietary format). Additionally, the current implementation of the HTMLAudioElement is not very efficient and useful for games. That is what motivated Google to work on another standard, which works much better for games.
Nevertheless, you want a standard implementation? The GitHub repository actually contains a standard implementation. The original JavaScript version is available, as is the Type'd version. Both are just called.SoundManager One is in the folder Original, the other one in the Scripts folder (both are subfolders of src).
1 note
¡
View note