# Tag Info

## Hot answers tagged typescript

39

No one but the folks who reviewed your code for the company can say with certainty why you were rejected. It also depends on the position you're applying for. If you're applying for an entry-level role or a guru role, the expectations are drastically different. As a hiring manager, a couple things jumped out at me (from most to least relevant to me, a ...

28

This is mostly how I would solve it (in Python): In [2]: import random In [3]: class Deck: ...: def __init__(self): ...: self._cards = list(range(52)) ...: def shuffle(self): ...: random.shuffle(self._cards) ...: def deal(self): ...: return self._cards.pop() The data structure is as simple as it gets, ...

26

While not strictly required, we value usage instructions, nicely-modeled data, automated tests, and thoughtful consideration of architectural decisions and simplicity-vs-completeness trade-offs. Given this clause, a few things stand out from your code: TypeScript - TypeScript is overkill for this problem. TypeScript is a fine language but not all projects ...

23

To be using strict null checks, you must be on "typescript": "^2.0.0". Thus, my example will be using this version of typescript with "compilerOptions":{"strictNullChecks": true}. It does seem that the filter solution is the most elegant solution to the titular question. Sadly, it seems that the typescript static analysis is unable to track this behavior: ...

18

Typescript 1.6 introduced user defined type guards that are a function whose return type is a boolean that is cast as a type predicate. To define a simple isString type guard (note the X is string return type), use syntax like below: function isString(str: string | undefined): str is string { return str !== undefined } or as a lambda with a slightly ...

13

I'm not entirely enthusiastic about either. The parts[parts.length - 1] using manual index lookup and subtraction may well take a moment to recognize, "Oh, this is getting the last element of the array". The second, using .reverse() followed by destructuring of the first item also could take a moment to think about before you understand what ...

11

One edge case you're missing is how to handle null. isEmpty(null) will fail because Object.getOwnPropertyNames(null) will throw TypeError: can't convert null to object. Also be aware that isEmpty(NaN) will return false, which may or may not be what you want.

10

Building on @RichardJohnson's answer: why not write one function that can filter any array of possibly-undefined values? Let's make it generic. export function filterUndef<T>(ts: (T | undefined)[]): T[] { return ts.filter((t: T | undefined): t is T => !!t) } This simplifies your filter call, too: const nums = [20, 44, undefined] const numsSafe =...

10

I sympathise :) I'm not sure if my answer will actually help much as it's either a rant or a list of hard work to do but hopefully it informs. Interview tests are hopelessly flawed experiments When we give someone a test in an interview, what are we testing? If it's something along the lines of "this person is a good programmer", and we're testing a pool ...

9

tl;dr at the end. In terms of 'performance', js engines are pretty well optimized. For something like this, performance should not be part of your argument against a given piece of code. In terms of readability, they are very similar so either works. There are better ways to think through this though. When it comes to PRs I would ponder on a few questions: ...

9

How to modify this code, so it doesn't use forEach? One way to achieve this is using Array.prototype.reduce(): const totalWordCount = fileTexts.reduce((big: sum, fileText: string) => { return sum + nlp(fileText).wordCount() }, 0) Notice that totalWordCount is assigned once so const can be used which helps avoid accidental re-assignment and other ...

8

Your service looks perfectly fine to me. As far as the Clock component goes, I can only recommend one thing. When getClock().subscribe(...) is executed, a reference to the subscription is being returned back. Ideally, the reference should be kept as long as the component is alive. On component destruction, the subscription should be released by invoking ...

8

It may seem unlikely but it is not impossible for an input string to contain tempBracket so a solution that doesn't involve adding and replacing that string would be ideal. function flipBracketsDirection(str) { return str // flip () brackets .replace(/$$/g, 'tempBracket').replace(/$$/g, '(').replace(/tempBracket/g, ')') // flip [] brackets ...

8

Another suggestion: with TypeScript, you only need to note the type of a parameter when TypeScript can't infer it itself. You might find it easier to read and write code when you avoid explicitly typing functions except when necessary for the TS to compile, or when the type of a return value isn't clear at a glance. In other words, if I were you, I'd switch ...

7

Edit: I've updated the code and uploaded a gist that will work in the TS playground - the gist will compile with Typescript 3.1. The primary benefit of Typescript is to provide types for Javascript. And since Typescript provides Generics - I don't think your implementation of a Dictionary provides any benefit over a plain javascript object. In fact, as you ...

7

A few of thoughts: You don't need to declare types for the arguments in the implementation of your constructor, just the overloads (which precede the implementation). I wouldn't use a separate object for the height and width, why not declare them as private members? Consider throwing TypeError instead of plain Error if your constructor can't figure the ...

6

You could move the door.locked check into the door.unlock() function (or into a new function) which would allow you return a promise for both cases: function unlockDoor(door) { return door.locked ? door.unlock() : Promise.resolve(); } } function openDoor(door) { unlockDoor(door).then(() => { door.handle.turn(...

6

First solution using .forEach, for...in and .sort Here what I did to achieve this: First sort your array of objects, i.e convert: data = [ {...}, {...}, {...}, {...}, {...}, {...} ] into an object sorted by year: sortedY = { 2017: [{...}, {...}, {...}], 2018: [{...}, {...}, {...}] } You can achieve such result by using a forEach loop: const sortedY = {...

6

One of the main ways in which you can improve this is by using Renderer2 in the directive instead of directly accessing this.el.nativeElement and making changes to it. This might work in most of the cases. But remember, the Angular code might run at other places as well(like in case of Service Workers and in case of Server Side Rendering). In these cases, ...

6

This is an answer that I posted to the original question on StackOverflow. It does away with regular expressions entirely, and uses a similar case-statement to the one suggested in @Henrik's answer The original code performs 6 regular expression substitutions (which require 1 pass each), and fails on strings that contain the text tempBracket (as noted by @...

6

Your code looks quite reasonable, though there are a few tweaks you could consider. Function or Callback? Rather than names like FoldlFunction and MMapFunction, since what those types contain are the types for the callback run for each element of the array, consider calling them FoldlCallback etc instead. It's a bit more precise and will make more intuitive ...

5

updated version of the code, based on @MarcoTerzolo 's answer import { Injectable } from '@angular/core'; import { Observable, Observer, ReplaySubject, Subject } from 'rxjs'; import { take } from 'rxjs/operators'; const VERSION = 2; // good tutorial: https://code.tutsplus.com/tutorials/working-with-indexeddb--net-34673 // reference: https://developer....

5

This is a really good question -- starred it! I am not very experienced with RxJs, but I believe your code around BehaviorSubject and Observable is as concise as possible. BehaviourSubject itself is "subscribable" (just like an Observable) but it's a really bad practice to expose it directly to the consumer, i.e. your separation of users\$ and usersSource is ...

5

For small arrays as input your script's performance is very good. Let me show you a different approach which might especially improve readability and might also increase performance for larger inputs and multiple runs. .reduce() Instead of iterating through the elements manually, I've used Array.prototype.reduce(): The reduce() method applies a function ...

5

A few points first. Avoid any like the plague. You can nearly always figure out a better type. When dealing with a JSON serialized data, I like to have a function similar to this to get rid of any as soon as possible: function verify<T>(obj: any, fallback: T, isT: (obj: any) => obj is T): T { return isT(obj) ? obj : fallback; } Object.keys and ...

5

One of the improvements would be to use an HttpClient instead of Http for making the API calls. If you use HttpClient, you won't have to call the res.json() everytime you subscribe to the response. To use HttpClient, you'll first have to import HttpClientModule from @angular/common/http. Then you'll have to add it to the imports array of your @NgModule ...

5

You don't need to define each individual transition state since there's a simple general rule: total all the numerals, but subtract the ones that occur in front of a larger numeral. function romanToInt(roman: string): number { const value: {[numeral: string]: number} = { 'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, ...

Only top voted, non community-wiki answers of a minimum length are eligible