[#version version] | [#grammar-execution grammar and execution] | [#var-expr variables and expressions] | [#arithmetic-logic arithmetic and logic] | [#strings strings] | [#regexes regexes] | [#dates-time dates and time] | [#arrays arrays] | [#dictionaries dictionaries] | [#functions functions] | [#execution-control execution control] | [#exceptions exceptions] | [#streams streams] | [#files files] | [#file-fmt file formats] | [#directories directories ] | [#processes-environment processes and environment] | [#libraries-namespaces libraries and namespaces] | [#user-defined-types user-defined types] | [#generic-types generic types] | [#objects objects] | [#inheritance-polymorphism inheritance and polymorphism] | [#reflection reflection] | [#net-web net and web] | [#debugging-profiling debugging and profiling]
||||||~ # version[#version-note version]|| ||~ ||~ [#typescript typescript]||~ [#dart dart]|| ||# version-used[#version-used-note version used] _ @< >@||##gray|//1.5//##||##gray|//1.10//##|| ||# version[#version-note show version] _ @< >@||$ tsc @@–@@version||$ dart @@–@@version|| ||||||~ # grammar-execution[#grammar-execution-note grammar and execution]|| ||~ ||~ typescript||~ dart|| ||# hello-world[#hello-world-note hello world]||$ cat hello.ts _ console.log(“Hello, World!”); _ _ $ tsc hello.ts _ _ $ node hello.js _ Hello, World!||$ cat hello.dart _ void main() { _ @< >@print(‘Hello, World!’); _ } _ _ $ dart hello.dart _ Hello, World! _ _ $ dart2js hello.dart _ _ $ node out.js _ Hello, World!|| ||# file-suffixes[#file-suffixes-note file suffixes] _ ##gray|//source, header, object file//##||.ts .d.ts .js||.dart ##gray|//none//## .js|| ||# interpreter[#interpreter-note interpreter] _ @< >@||##gray|//none//##||$ dart foo.dart|| ||# block-delimiters[#block-delimiters-note block delimiters] _ @< >@||{}||{ ##gray|//…//## }|| ||# statement-separator[#statement-separator-note statement separator] _ @< >@||##gray|//; or newline _ _ newline not separator inside (), [], {}, ““, ‘‘, or after binary operator _ _ newline sometimes not separator when following line would not parse as a valid statement//##||;|| ||# eol-comment[#eol-comment-note end-of-line comment] _ @< >@||##gray|@@//@@ comment##||@@//@@ ##gray|//comment//##|| ||# multiple-line-comment[#multiple-line-comment-note multiple line comment] _ @< >@||##gray|/* line _ another line /##||/ ##gray|//comment line//## _ ##gray|//another line//## /* ##gray|//nested comment//## */ */|| ||||||~ # var-expr[#var-expr-note variables and expressions]|| ||~ ||~ typescript||~ dart|| ||# local-var[#local-var-note local variable] _ @< >@||var x: number = 1; _ var y: number = 2, z: number = 3; _ _ ##gray|@@//@@ type is inferred:## _ var x = 1; _ var y = 2, z = 3;||int i; _ int j = 3, k = 4; _ _ ##gray|@@//@@ type is inferred:## _ var x = 1; _ var y = 2, z = 3;|| ||# local-scope-regions[#local-scope-regions-note regions which define lexical scope]||##gray|//top level: _ @< >@html page _ _ nestable: _ @< >@function//##||##gray|//top level: _ @< >@file _ _ nestable: _ @< >@block//##|| ||# global-var[#global-var-note global variable]||##gray|@@//@@ no globals in TypeScript; if global is defined _ @@//@@ in JavaScript it can be declared. _ @@//@@ Run time ReferenceError if not found:## _ declare var g;|| || ||# uninitialized-var[#uninitialized-var-note uninitialized variable] _ @< >@||##gray|//set to// undefined##||##gray|//set to// null##|| ||# immutable-var[#immutable-var-note immutable variable]|| ||import ‘dart:math’; _ _ final x = (new Random()).nextDouble();|| ||# const[#const-note constant] _ @< >@||##gray|//none//##||const double pi = 3.14;|| ||# assignment[#assignment-note assignment] _ @< >@||x = 1;||i = 3;|| ||# parallel-assignment[#parallel-assignment-note parallel assignment] _ @< >@||##gray|//none//##||##gray|//none//##|| ||# swap[#swap-note swap] _ @< >@||var tmp = x; _ x = y; _ y = tmp;||int x = 1, y = 2, tmp; _ _ tmp = x; _ x = y; _ y = tmp;|| ||# compound-assignment[#compound-assignment-note compound assignment] _ ##gray|//arithmetic, string, logical, bit//##||+= -= *= /= ##gray|//none//## %= _ += _ ##gray|//none//## _ @@<<= >>= @@&= |= ^=||##gray|//arithmetic://## _ += -= *= /= ~/= %= _ _ ##gray|//string://## _ += *= _ _ ##gray|//bit://## _ @@<<= >>= &= ^= |=@@|| ||# incr-decr[#incr-decr-note increment and decrement] _ @< >@||var x = 1; _ var y = ++x; _ var z = @@–@@y;||##gray|//premodifiers://## _ ++i @@–@@i _ _ ##gray|//postmodifiers://## _ i++ i@@–@@|| ||# null[#null-note null] _ @< >@||null||null|| ||# null-test[#null-test-note null test] _ @< >@||v === null||x == null|| ||# option-type[#option-type-note option type]|| || || ||# undef-var[#undef-var-note undefined variable] _ @< >@||undefined|| || ||# conditional-expr[#conditional-expr-note conditional expression] _ @< >@||x > 0 ? x : -x||x > 0 ? x : -x|| ||||||~ # arithmetic-logic[#arithmetic-logic-note arithmetic and logic]|| ||~ ||~ typescript||~ dart|| ||# boolean-type[#boolean-type-note boolean type] _ @< >@||var x: boolean = true;||bool|| ||# true-false[#true-false-note true and false] _ @< >@||true false||true false|| ||# falsehoods[#falsehoods-note falsehoods] _ @< >@||false null undefined ““ 0 NaN||##gray|//everything except for the boolean//## true|| ||# logical-op[#logical-op-note logical operators] _ @< >@||@@&& ||@@ !||&& @@||@@ !|| ||# relational-op[#relational-op-note relational operators] _ @< >@||@@===@@ !== < > >= <= _ _ ##gray|//perform type coercion://## _ @@==@@ !=||== != < > <= >=|| ||# min-max[#min-max-note min and max] _ @< >@||Math.min(1, 2, 3) _ Math.max(1, 2, 3) _ _ Math.min.apply(Math, [1, 2, 3]) _ Math.max.apply(Math, [1, 2, 3])|| || ||# int-type[#int-type-note integer type] _ @< >@||##gray|//none; use// number##||int|| ||# float-type[#float-type-note float type]||var x: number = 3.14;||double|| ||# arith-op[#arith-op-note arithmetic operators] _ ##gray|//addition, subtraction, multiplication, float division, quotient, remainder//##||+ - * / ##gray|//none//## %||@@+@@ - * / %|| ||# int-div[#int-div-note integer division] _ @< >@||Math.floor(x / y)||3 ~/ 7|| ||# int-div-zero[#int-div-zero-note integer division by zero] _ @< >@||##gray|//returns assignable value Infinity, NaN, or -Infinity depending upon whether dividend is positive, zero, or negative. _ _ There are literals for Infinity and NaN.//##||IntegerDivisionByZeroException|| ||# float-div[#float-div-note float division] _ @< >@||13 / 5||3 / 7|| ||# float-div-zero[#float-div-zero-note float division by zero] _ @< >@||##gray|//same behavior as for integers//##||##gray|@@//@@ not literals:## _ Infinity, NaN, ##gray|//or//## -Infinity|| ||# power[#power-note power] _ @< >@||Math.pow(2, 32)||import ‘dart:math’ as math; _ _ math.pow(2.0, 3.0)|| ||# sqrt[#sqrt-note sqrt]||Math.sqrt(2)||import ‘dart:math’ as math; _ _ math.sqrt(2)|| ||# sqrt-negative-one[#sqrt-negative-one-note sqrt -1] _ @< >@||NaN||import ‘dart:math’ as math; _ _ ##gray|@@//@@ NaN:## _ math.sqrt(-1)|| ||# transcendental-func[#transcendental-func-note transcendental functions] _ @< >@||Math.exp Math.log Math.sin Math.cos Math.tan Math.asin Math.acos Math.atan Math.atan2||import ‘dart:math’ as math; _ _ math.log ##gray|//none//## ##gray|//none//## _ math.sin math.cos math.tan _ math.asin math.acos math.atan _ math.atan2|| ||# transcendental-const[#transcendental-const-note transcendental constants] _ ##gray|//π and e//##||Math.PI _ Math.E||import ‘dart:math’ as math; _ _ math.PI _ math.E|| ||# float-truncation[#float-truncation-note float truncation] _ @< >@||##gray|//none//## _ Math.round(3.1) _ Math.floor(3.1) _ Math.ceil(3.1)||3.14.truncate() _ 3.14.round() _ 3.14.floor() _ 3.14.ceil() _ _ ##gray|@@//@@ (-3.14).floor() is -4 but -3.14.floor() is -3.##|| ||# abs-val[#abs-val-note absolute value] _ @< >@||Math.abs(-3)||(-7.77).abs()|| ||# int-overflow[#int-overflow-note integer overflow] _ @< >@||##gray|//all numbers are floats//##|| || ||# float-overflow[#float-overflow-note float overflow] _ @< >@||Infinity|| || ||# random-num[#random-num-note random number] _ ##gray|//uniform integer, uniform float, normal float//##||Math.floor(Math.random() * 100) _ Math.random() _ ##gray|//none//##||import ‘dart:math’; _ _ var rnd = new Random(); _ int n = rnd.nextInt(100); _ int x = rnd.nextDouble();|| ||# random-seed[#random-seed-note random seed] _ ##gray|//set, get, restore//##||##gray|//none//##||import ‘dart:math’; _ _ var rnd = new Random(17);|| ||# bit-op[#bit-op-note bit operators] _ @< >@||@<<< >> & | ^ ~>@||@@ << >> & | ^ ~ @@|| ||# binary-octal-hex-literals[#binary-octal-hex-literals-note binary, octal, and hex literals]||##gray|//none//## _ 052 ##gray|@@//@@ deprecated## _ 0x2a|| || ||# radix[#radix-note radix] _ ##gray|//convert integer to and from string with radix//##||(42).toString(7) _ ##gray|//??//##|| || ||||||~ # strings[#strings-note strings]|| ||~ ||~ typescript||~ dart|| ||# str-type[#str-type-note string type] _ @< >@||var s: string = “lorem ipsum”;||String|| ||# str-literal[#str-literal-note string literal] _ @< >@||"don’t say "no"” _ ‘don\’t say “no”’||var s = ‘don\’t say “no”’; _ var s2 = “don’t say "no"”; _ var s3 = ‘‘‘don’t say “no”’ _ var s4 = “““don’t say “no"””” _ _ ##gray|//raw string literals://## r’foo’ r"foo”|| ||# newline-in-str-literal[#newline-in-str-literal-note newline in literal] _ @< >@||##gray|//yes//##||##gray|@@//@@ triple quote literals only:## _ var s = ‘‘‘first line _ second line’’’; _ _ var s2 = “““first line _ second line”””|| ||# str-literal-esc[#str-literal-esc-note literal escapes] _ @< >@||##gray|//single and double quotes://## _ \b \f \n \r \t \v \uhhhh \xhh " \’ \||\b \f \n \r \t \v " \’ $ \ _ \x##gray|//hh//## \u##gray|//hhhh//## \u{##gray|//h…//##}|| ||# here-doc[#here-doc-note here document] _ @< >@||##gray|//none//##|| || ||# var-interpolation[#var-interpolation-note variable interpolation] _ @< >@||##gray|@@//@@ None; use string concatenation. _ @@//@@ Both of these expressions are ‘11’:## _ 1 + “1” _ “1” + 1|| || ||# expr-interpolation[#expr-interpolation-note expression interpolation]||##gray|//none//##||var count = 3; _ var item = “BALL”; _ _ ##gray|@@//@@ 3 balls## _ print(‘$count ${item.toLowerCase()}s’);|| ||# format-str[#format-str-note format string] _ @< >@||##gray|@@//@@ None; use string concatenation. _ @@//@@ Evaluates to “12.35”:## _ 12.3456.toFixed(2)|| || ||# mutable-str[#mutable-str-note are strings mutable?]||##gray|//no//##|| || ||# compare-str[#compare-str-note compare strings]||"hello” === “world” _ “hello” < “world”||"hello” == “world” _ “hello”.compareTo(“world”) < 0|| ||# copy-str[#copy-str-note copy string]||##gray|//none//##|| || ||# str-concat[#str-concat-note concatenate] _ @< >@||s = “Hello, “ + “World!”;||"hello” + “ world”|| ||# str-replicate[#str-replicate-note replicate] _ @< >@||var hbar = Array(80).join(“-”);||var hbar = “-” * 80;|| ||# translate-case[#translate-case-note translate case] _ ##gray|//to upper, to lower//##||"lorem”.toUpperCase() _ “LOREM”.toLowerCase()||"hello”.toUpperCase() _ “HELLO”.toLowerCase()|| ||# capitalize[#capitalize-note capitalize] _ ##gray|//string, words//##||##gray|//none//##|| || ||# trim[#trim-note trim] _ ##gray|//both sides, left, right//##||” lorem “.trim() _ ##gray|# some browsers:## _ “ lorem”.trimLeft() _ “lorem “.trimRight()||” lorem “.trim() _ “ lorem “.trimLeft() _ “ lorem “.trimRight()|| ||# pad[#pad-note pad] _ ##gray|//on right, on left, centered//##||##gray|//none//##||"lorem”.padRight(10, “ “) _ “lorem”.padLeft(10, “ “)|| ||# num-to-str[#num-to-str-note number to string] _ @< >@||"value: “ + 8||3.14.toString() _ 7.toString()|| ||# str-to-num[#str-to-num-note string to number] _ @< >@||7 + parseInt(“12”, 10) _ 73.9 + parseFloat(“.037”) _ _ ##gray|@@//@@ 12:## _ parseInt(“12A”) _ ##gray|@@//@@ NaN:## _ parseInt(“A”)||var n = int.parse(“17”); _ var x = double.parse(“3.14”);|| ||# str-join[#str-join-note string join] _ @< >@||[“do”, “re”, “mi”].join(“ “)||[‘foo’, ‘bar’, ‘baz’].join(‘ ‘)|| ||# split[#split-note split] _ @< >@||##gray|@@//@@ [ “do”, “re”, ““, “mi”, ““ ]:## _ “do re@< >@mi “.split(“ “) _ _ ##gray|@@//@@ [ “do”, “re”, “mi”, ““ ]:## _ “do re@< >@mi “.split(/\s+/)||var a = “foo bar bar”.split(‘ ‘);|| ||# split-in-two[#split-in-two-note split in two] _ @< >@||##gray|//none//##|| || ||# split-keep-delimiters[#split-keep-delimiters-note split and keep delimiters]||##gray|//none//##|| || ||# prefix-suffix-test[#prefix-suffix-test-note prefix and suffix test]||"foobar”.startsWith(“foo”) _ “foobar”.endsWith(“bar”)|| || ||# str-len[#str-len-note length] _ @< >@||"lorem”.length||##gray|@@//@@ number of 16 bit runes:## _ “hello”.length|| ||# index-substr[#index-substr-note index of substring] _ ##gray|//first, last//##||##gray|@@//@@ returns -1 if not found:## _ “lorem ipsum”.indexOf(“ipsum”)||"hello”.indexOf(“ll”)|| ||# extract-substr[#extract-substr-note extract substring] _ ##gray|//by start and length, by start and end, by successive starts//##||"lorem ipsum”.substr(6, 5) _ “lorem ipsum”.substring(6, 11)||"hello”.substring(2, 4)|| ||# char-type[#char-type-note character type]|| ||##gray|@@//@@ 16 bits:## _ rune|| ||# lookup-char[#lookup-char-note character lookup]||"lorem ipsum”[6]|| || ||# chr-ord[#chr-ord-note chr and ord] _ @< >@||String.fromCharCode(65) _ “A”.charCodeAt(0)||new String.fromCharCodes([65]) _ “A”.codeUnitAt(0) _ _ ##gray|@@//@@ for Unicode points above U+FFFF codeUnitAt will _ @@//@@ return part of a surrogate pair##|| ||# str-to-char-array[#str-to-char-array-note to array of characters] _ @< >@||"abcd”.split(““)|| || ||# translate-char[#translate-char-note translate characters] _ @< >@||##gray|//none//##|| || ||# delete-char[#delete-char-note delete characters]||##gray|//none//##|| || ||# squeeze-char[#squeeze-char-note squeeze characters]||##gray|//none//##|| || ||||||~ # regexes[#regexes-note regular expressions]|| ||~ ||~ typescript||~ dart|| ||# regex-literal[#regex-literal-note literal, custom delimited literal]||/lorem|ipsum/|| || ||# regex-metachar[#regex-metachar-note metacharacters]|| ||. [ ] \ ( ) * + ? { } | ^ $ _ _ ##gray|//use raw string (i.e. with r prefix) literals to avoid having to escape backslashes.//##|| ||# char-class-abbrev[#char-class-abbrev-note character class abbreviations]||. \d \D \s \S \w \W||. \d \D \s \S \w \W|| ||# regex-anchors[#regex-anchors-note anchors] _ @< >@||^ $ \b \B||^ $ \b \B|| ||# regex-test[#regex-test-note match test] _ @< >@||if (s.match(/1999/)) { _ @< >@alert(“party!”); _ }|| RegExp rx = new RegExp(r"1999”); _ String s = “It’s 1999”; _ _ if (rx.hasMatch(s)) { _ @< >@print(“Party!”); _ }|| ||# case-insensitive-regex[#case-insensitive-regex-note case insensitive match test]||"Lorem”.match(/lorem/i)||RegExp rx = new RegExp(r"lorem”, caseSensitive: false); _ String s = “Lorem Ipsum”; _ _ if (rx.hasMatch(s)) { _ @< >@print(“case insensitive match”); _ }|| ||# regex-modifiers[#regex-modifiers-note modifiers] _ @< >@||g i m||##gray|RegExp //constructor takes two optional boolean named parameters://## _ _ multiLine _ caseSensitive|| ||# subst[#subst-note substitution] _ @< >@||s = “do re mi mi mi”; _ s.replace(/mi/g, “ma”);||RegExp re = new RegExp(r’mi’); _ print(“do re mi mi mi”.replaceAll(re, “ma”));|| ||# match-prematch-postmatch[#match-prematch-postmatch-note match, prematch, postmatch] _ @< >@||##per|m## = /\d{4}/.exec(s); _ if (m) { _ @< >@match = m[0]; _ @< >@##gray|# no prematch or postmatch## _ }|| || ||# group-capture[#group-capture-note group capture] _ @< >@||rx = /^(\d{4})-(\d{2})-(\d{2})$/; _ m = rx.exec(‘2009-06-03’); _ yr = m[1]; _ mo = m[2]; _ dy = m[3];||RegExp rx = new RegExp(r’(\d{4})-(\d{2})-(\d{2})’); _ var md = rx.firstMatch(“2010-06-03”); _ _ if (md != null) { _ @< >@var yyyy = md.group(1); _ @< >@var mm = md.group(2); _ @< >@var dd = md.group(3); _ @< >@print(“year: $yyyy month: $mm day: $dd”); _ }|| ||# named-group-capture[#named-group-capture-note named group capture]||##gray|//none//##|| || ||# scan[#scan-note scan] _ @< >@||var a = “dolor sit amet”.match(/\w+/g);|| || ||# backreference[#backreference-note backreference in match and substitution]||/(\w+) \1/.exec(“do do”) _ _ “do re”.replace(/(\w+) (\w+)/, ‘$2 $1’)|| || ||# recursive-regex[#recursive-regex-note recursive regex] _ @< >@||##gray|//none//##|| || ||||||~ # dates-time[#dates-time-note dates and time]|| ||~ ||~ typescript||~ dart|| ||# broken-down-datetime-type[#broken-down-datetime-type-note broken-down datetime type] _ @< >@||##green|Date##||DateTime|| ||# current-datetime[#current-datetime-note current datetime]||##purple|var## ##peru|t## = ##purple|new## ##green|Date##();||var dt = new DateTime.now();|| ||# current-unix-epoch[#current-unix-epoch-note current unix epoch]||(##purple|new## ##green|Date##()).getTime() / 1000|| || ||# broken-down-datetime-to-unix-epoch[#broken-down-datetime-to-unix-epoch-note broken-down datetime to unix epoch]||Math.round(t.getTime() / 1000)||dt.millisecondsSinceEpoch ~/ 1000|| ||# unix-epoch-to-broken-down-datetime[#unix-epoch-to-broken-down-datetime-note unix epoch to broken-down datetime]||##purple|var## ##peru|epoch## = 1315716177; _ ##purple|var## ##peru|t2## = ##purple|new## ##green|Date##(epoch * 1000);||int t = 1422021432; _ _ var dt = new DateTime.fromMillisecondsSinceEpoch(t * 1000);|| ||# fmt-datetime[#fmt-datetime-note format datetime]||##gray|//none//##|| || ||# parse-datetime[#parse-datetime-note parse datetime]||##gray|//none//##|| || ||# parse-datetime-without-fmt[#parse-datetime-without-fmt-note parse datetime w/o format]||##purple|var## ##peru|t## = ##purple|new## ##green|Date##(##maroon|"July 7, 1999”##);|| || ||# date-parts[#date-parts-note date parts]||t.getFullYear() _ t.getMonth() + 1 _ t.getDate() ##gray|# getDay() is day of week##||int yr = dt.year; _ int mo = dt.month; _ int dy = dt.day;|| ||# time-parts[#time-parts-note time parts]||t.getHours() _ t.getMinutes() _ t.getSeconds()||int hr = dt.hour; _ int mi = dt.minute; _ int ss = dt.second;|| ||# build-datetime[#build-datetime-note build broken-down datetime]||##purple|var## ##peru|yr## = 1999; _ ##purple|var## ##peru|mo## = 9; _ ##purple|var## ##peru|dy## = 10; _ ##purple|var## ##peru|hr## = 23; _ ##purple|var## ##peru|mi## = 30; _ ##purple|var## ##peru|ss## = 0; _ ##purple|var## ##peru|t## = ##purple|new## ##green|Date##(yr, mo - 1, dy, hr, mi, ss);||var dt = new DateTime(1999, 9, 10, 23, 30, 0); _ _ var dt_utc = new DateTime.utc(1999, 9, 10, 23, 30, 0);|| ||# datetime-subtraction[#datetime-subtraction-note datetime subtraction]||##gray|number //containing time difference in milliseconds//##||Duration delta = dt.difference(dt2);|| ||# add-duration[#add-duration-note add duration]||##purple|var## ##peru|t1## = ##purple|new## ##green|Date##(); _ ##purple|var## ##peru|delta## = (10 * 60 + 3) * 1000; _ ##purple|var## ##peru|t2## = ##purple|new## ##green|Date##(t1.getTime() + delta);||Duration delta1 = const Duration(seconds: 1000); _ Duration delta2 = const Duration(hours: 1000); _ Duration delta3 = const Duration(days: 1000); _ _ var dt2 = dt.add(delta1); _ var dt3 = dt.subtract(delta3);|| ||# local-tmz-determination[#local-tmz-determination-note local time zone determination]|| || || ||# tmz-info[#tmz-info-note time zone info] _ _ ##gray|//name and UTC offset//##|| || || ||# daylight-savings-test[#daylight-savings-test-note daylight savings test]|| || || ||# microseconds[#microseconds-note microseconds]|| || || ||# sleep[#sleep-note sleep]||##gray|//none//##|| || ||||||~ # arrays[#arrays-note arrays]|| ||~ ||~ typescript||~ dart|| ||# array-literal[#array-literal-note literal] _ @< >@||var a = [1, 2, 3, 4]; _ _ ##gray|@@//@@ two ways to declare type:## _ var a: number[] = [1, 2, 3, 4]; _ var a: Array = [1, 2, 3, 4];||var a = [1, 2, 3, 4];|| ||# array-size[#array-size-note size] _ @< >@||a.length||a.length|| ||# array-empty[#array-empty-note empty test] _ @< >@||##gray|@@//@@ TypeError if a is null or undefined:## _ a.length === 0||a.isEmpty|| ||# array-lookup[#array-lookup-note lookup] _ @< >@||a[0]||a[0]|| ||# array-update[#array-update-note update] _ @< >@||a[0] = “lorem”||a[0] = “lorem”;|| ||# array-out-of-bounds[#array-out-of-bounds-note out-of-bounds behavior]||##gray|//returns// undefined##||##gray|//lookups and updates raise// RangeError##|| ||# array-element-index[#array-element-index-note element index] _ _ ##gray|//first and last occurrence//##||##gray|@@//@@ returns -1 if not found:## _ [6, 7, 7, 8].indexOf(7) _ [6, 7, 7, 8].lastIndexOf(7)||##gray|@@//@@ returns -1 if not found:## _ [6, 7, 7, 8].indexOf(7) _ [6, 7, 7, 8].lastIndexOf(7)|| ||# array-slice[#array-slice-note slice] _ ##gray|//by endpoints, by length//## _ @< >@||##gray|@@//@@ select 3rd and 4th elements:## _ [“a”, “b”, “c”, “d”].slice(2, 4) _ ##gray|//none//##||var a = [“a”, “b”, “c”, “d”, “e”]; _ _ ##gray|@@//@@ [“c”, “d”]:## _ List a2 = a.getRange(2, 4);|| ||# array-slice-to-end[#array-slice-to-end-note slice to end] _ @< >@||[“a”, “b”, “c”, “d”].slice(1)||[“a”, “b”, “c”, “d”].skip(1)|| ||# array-back[#array-back-note manipulate back] _ @< >@||a = [6, 7, 8]; _ a.push(9); _ i = a.pop();||a.add(4); _ var v = a.removeLast();|| ||# array-front[#array-front-note manipulate front] _ @< >@||a = [6, 7, 8]; _ a.unshift(5); _ i = a.shift();||var a = [6, 7, 8]; _ a.insertAt(0, 5); _ var i = a.removeAt(0);|| ||# array-concatenation[#array-concatenation-note concatenate]||a = [1, 2, 3].concat([4, 5, 6]);||var a = [1, 2, 3]; _ a.addAll([4, 5, 6]);|| ||# replicate-array[#replicate-array-note replicate] _ @< >@||##gray|//none//##||var a = new List.filled(10, 0);|| ||# array-copy[#array-copy-note copy] _ ##gray|//address copy, shallow copy, deep copy//##||a = [1, 2, [3, 4]]; _ a2 = a; _ a3 = a.slice(0); _ a4 = JSON.parse(JSON.stringify(a));||var a = [“a”, “b”]; _ _ List a2 = new List.from(a);|| ||# array-as-func-arg[#array-as-func-arg-note array as function argument]||##gray|//parameter contains address copy//##||##gray|//parameter contains address copy//##|| ||# iterate-over-array[#iterate-over-array-note iterate over elements] _ @< >@||[1, 2, 3].forEach(function(n) { _ @< >@alert(n); _ });||for (var i in [1, 2, 3]) { _ @< >@print(i); _ } _ _ [1, 2, 3].forEach((i) => print(i));|| ||# indexed-array-iteration[#indexed-array-iteration-note iterate over indices and elements]||var len = a.length; _ for (var i = 0; i < len; i++ ) { _ @< >@alert(a[i]); _ }|| || ||# range-array[#range-array-note instantiate range as array]|| || || ||# array-reverse[#array-reverse-note reverse] _ ##gray|//non-destructive, in-place//##||var a = [1, 2, 3]; _ a.reverse();||var a = [“a”, “b”, “c”]; _ _ List a2 = new List.from(a.reversed);|| ||# array-sort[#array-sort-note sort] _ ##gray|//non-destructive, _ in-place, _ custom comparision//##||var a = [3, 1, 4, 2]; _ a.sort();||var a = [3, 1, 4, 2]; _ a.sort();|| ||# array-dedupe[#array-dedupe-note dedupe] _ ##gray|//non-destructive, in-place//##|| ||var a = [1, 2, 2, 3]; _ var set = new Set.from(a); _ var a2 = new List.from(set);|| ||# membership[#membership-note membership] _ @< >@|| ||[1, 2, 3].contains(7)|| ||# intersection[#intersection-note intersection] _ @< >@|| ||var set1 = new Set.from([1, 2]); _ var set2 = new Set.from([2, 3, 4]); _ _ set1.intersection(set2);|| ||# union[#union-note union] _ @< >@|| ||var set1 = new Set.from([1, 2]); _ var set2 = new Set.from([2, 3, 4]); _ _ set1.union(set2);|| ||# set-diff[#set-diff-note relative complement]|| ||var set1 = new Set.from([1, 2]); _ var set2 = new Set.from([2, 3, 4]); _ _ set1.difference(set2);|| ||# map[#map-note map] _ @< >@||##gray|@@//@@ callback gets 3 args: _ @@//@@ value, index, array## _ a.map(function(x) { return x * x })||var a = [1, 2, 3]; _ _ var a2 = new List.from(a.map((n) => n * n));|| ||# filter[#filter-note filter] _ @< >@||a.filter(function(x) { return x > 1 }) ||var a = [1, 2, 3]; _ _ var a2 = new List.from(a.where((n) => n > 1));|| ||# reduce[#reduce-note reduce] _ @< >@||a.reduce(function(m, o) { _ @< >@@< >@return m + o; _ @< >@}, 0)||var a = [1, 2, 3]; _ _ var sum = a.reduce((v, e) => v + e);|| ||# universal-existential-test[#universal-existential-test-note universal and existential tests] _ @< >@||var a = [1, 2, 3, 4]; _ var even = function(x) { _ @< >@return x % 2 == 0; _ }; _ _ a.every(even) _ a.some(even)||[1, 2, 3, 4].every((x) => x % 2 == 0) _ [1, 2, 3, 4].any((x) => x % 2 == 0)|| ||# shuffle-sample[#shuffle-sample-note shuffle and sample]|| ||var a = [1, 2, 3, 4]; _ a.shuffle(); _ var samp = a.take(2);|| ||# flatten[#flatten-note flatten] _ ##gray|//one level, completely//##|| || || ||# zip[#zip-note zip] _ @< >@|| || || ||||||~ # dictionaries[#dictionaries-note dictionaries]|| ||~ ||~ typescript||~ dart|| ||# dict-literal[#dict-literal-note literal] _ @< >@||d = {"t”: 1, “f”: 0}; _ ##gray|@@//@@ keys do not need to be quoted if they _ @@//@@ are a legal JavaScript variable name _ @@//@@and not a reserved word## _ _ ##gray|@@//@@ declare type:## _ var d: {[idx: string]: number} = {t: 1, f: 0}||var d = {"t”: 1, “f”: 0};|| ||# dict-size[#dict-size-note size] _ @< >@||var size = 0; _ for (var k in d) { _ @< >@if (d.hasOwnProperty(k)) size++; _ }||d.length|| ||# dict-lookup[#dict-lookup-note lookup] _ @< >@||d.hasOwnProperty(“t”) ? d[“t”] : undefined _ _ ##gray|@@//@@ if type of d not declared:## _ d.hasOwnProperty(“t”) ? d.t : undefined||d[“t”]|| ||# dict-update[#dict-update-note update]||d[“t”] = 2; _ _ ##gray|@@//@@ if type of d not declared:## _ d.t = 2;||d[“t”] = 2;|| ||# dict-missing-key[#dict-missing-key-note missing key behavior] _ @< >@||var d = {}; _ ##gray|@@//@@ sets s to undefined:## _ var s = d[“lorem”]; _ ##gray|@@//@@ adds key/value pair:## _ d[“lorem”] = “ipsum”; ||##gray|//returns//## null|| ||# dict-key-check[#dict-key-check-note is key present] _ @< >@||d.hasOwnProperty(“t”);||d.containsKey(“y”)|| ||# dict-delete[#dict-delete-note delete]||delete d[“t”]; _ _ ##gray|@@//@@ if type of d not declared:## _ delete d.t;||d.remove(“f”);|| ||# dict-assoc-array[#dict-assoc-array-note from array of pairs, from even length array]|| || || ||# dict-merge[#dict-merge-note merge]|| || || ||# dict-invert[#dict-invert-note invert]|| || || ||# dict-iter[#dict-iter-note iterate] _ @< >@||for (var k in d) { _ @< >@if (d.hasOwnProperty(k)) { _ @< >@@< >@##gray|@@//@@ use k or d[k]## _ @< >@} _ }||d.forEach((k, v) { _ @< >@print(k); _ @< >@print(v); _ });|| ||# dict-key-val[#dict-key-val-note keys and values as arrays]|| ||List keys = d.keys; _ List vals = d.values;|| ||# dict-sort-values[#dict-sort-values-note sort by values]||function cmp2(a, b) { _ @< >@if (a[1] < b[1]) { return -1; } _ @< >@if (a[1] > b[1]) { return 1; } _ @< >@return 0; _ } _ _ for (p in _.pairs(d).sort(cmp2)) { _ @< >@alert(p[0] + “: “ + p[1]); _ }|| || ||# dict-default-val[#dict-default-val-note default value, computed value]||##gray|//none//##|| || ||||||~ # functions[#functions-note functions]|| ||~ ||~ typescript||~ dart|| ||# def-func[#def-func-note define] _ @< >@||function add(x: number, y: number): number { _ @< >@return x + y; _ } _ _ ##gray|@@//@@ parameter and return types optional:## _ function add(x, y) { _ @< >@return x + y; _ }||num add(num n, num m) { _ @< >@return n + m; _ } _ _ ##gray|@@//@@ parameter and return types optional:## _ add(n, m) { _ @< >@return n + m; _ } _ _ ##gray|@@//@@ expression body shorthand:## _ num add(num n, num m) => n + m;|| ||# invoke-func[#invoke-func-note invoke]||add(1, 2)||add(1, 2)|| ||# overload-func[#overload-func-note overload]||function to_number(x: string): number; _ function to_number(x: number): number; _ function to_number(x): number { _ @< >@if (typeof(x) == “string”) { return parseFloat(x); } _ @< >@if (typeof(x) == “number”) { return x; } _ }||##gray|//none//##|| ||# missing-arg[#missing-arg-note missing argument behavior] _ @< >@||##gray|@@//@@ compilation error unless arg declared optional.## _ _ ##gray|@@//@@ how to declare arg optional:## _ function safe_length(s?: string): number { _ @< >@return s === undefined ? -1 : s.length; _ }||##gray|//compilation error//##|| ||# extra-arg[#extra-arg-note extra argument behavior] _ @< >@||##gray|//compilation error//##||##gray|//compilation error//##|| ||# default-arg[#default-arg-note default argument] _ @< >@||function my_log(x: number, base: number = 10) { _ @< >@return Math.log(x) / Math.log(base); _ }||import ‘dart:math’ as math; _ _ ##gray|@@//@@ named params can have defaults:## _ num my_log(num expt, {num base: 10}) { _ @< >@return math.log(expt) / math.log(base); _ } _ _ ##gray|@@//@@ positional params can be optional:## _ num my_log(num expt, [num base]) { _ @< >@if (base == null) { _ @< >@@< >@return math.log(expt) / math.log(10); _ @< >@} _ @< >@else { _ @< >@@< >@return math.log(expt) / math.log(base); _ @< >@} _ }|| ||# variadic-func[#variadic-func-note variadic function]||function ends(s: string, …rest: string[]): void { _ @< >@console.log(s); _ @< >@if (rest.length) _ @< >@@< >@console.log(rest[rest.length - 1]); _ }||##gray|//none//##|| ||# named-param[#named-param-note named parameters] _ @< >@||##gray|//none//##||num divide({num dividend, num divisor}) { _ return dividend / divisor; _ } _ _ divide(divisor: 3, dividend: 9);|| ||# retval[#retval-note return value] _ @< >@||return ##gray|//arg or//## undefined. ##gray|//If invoked with//## new ##gray|//and return value not an object, returns//## this||##gray|return //arg or// null##|| ||# anonymous-func-literal[#anonymous-func-literal-note anonymous function literal] _ @< >@||var sqr: (x: number) => number = function(x) { _ @< >@return x * x; _ } _ _ ##gray|@@//@@ lambda syntax does not bind “this” _ @@//@@ to global object:## _ var sqr2: (x: number) => number = (x) => { _ @< >@return x * x; _ }||Function sqr = (num x) => x * x;|| ||# invoke-anonymous-func[#invoke-anonymous-func-note invoke anonymous function] _ @< >@||sqr(2)||((num x) => x * x)(5)|| ||# func-as-val[#func-as-val-note function as value] _ @< >@||var func = add;||apply(Function fn, arg) { _ @< >@fn(arg); _ } _ _ apply(print, “lorem ipsum”);|| ||# func-with-state[#func-with-state-note function with state]|| ||##gray|//Use a variable defined outside the function; the scope of the variable is the containing file.//##|| ||# closure[#closure-note closure]||function make_counter(): () => number { _ @< >@var i = 0; _ _ @< >@return function() { _ @< >@@< >@i += 1; _ @< >@@< >@return i; _ @< >@} _ }||Function make_counter() { _ @< >@num i = 0; _ @< >@return () => ++i; _ }|| ||# generator[#generator-note generator]|| || || ||||||~ # execution-control[#execution-control-note execution control]|| ||~ ||~ typescript||~ dart|| ||# if[#if-note if] _ @< >@||if (0 == n) { _ @< >@alert(“no hits”); _ } else if (1 == n) { _ @< >@alert(“1 hit”); _ } else { _ @< >@alert(n + “ hits”); _ }||int signum; _ _ if (i > 0) { _ @< >@signum = 1; _ } else if (i == 0) { _ @< >@signum = 0; _ } else { _ @< >@signum = -1; _ }|| ||# switch[#switch-note switch]||switch (n) { _ case 0: _ @< >@alert(“no hits\n”); _ @< >@break; _ case 1: _ @< >@alert(“one hit\n”); _ @< >@break; _ default: _ @< >@alert(n + “ hits\n”); _ }||##gray|@@//@@ switch expression can be integer or string## _ _ switch (i) { _ @< >@case 0: _ @< >@case 1: _ @< >@@< >@print(“i is boolean”); _ @< >@@< >@break; _ @< >@default: _ @< >@@< >@print(“i is not boolean”); _ } _ _ ##gray|@@//@@ Falling through not permitted; exception if last _ @@//@@ statement not break, continue, throw, or return.##|| ||# while[#while-note while] _ @< >@||while (i < 100) { _ @< >@i += 1; _ }||int i = 0; _ _ while (i < 10) { _ @< >@++i; _ }|| ||# for[#for-note for] _ @< >@||for (var i = 0; i < 10; i++) { _ @< >@alert(i); _ }||int n, i; _ _ ##gray|@@//@@ Initialization and afterthought must be single _ @@//@@ statements; there is no comma operator.## _ n = 1; _ for (i = 1; i <= 10; ++i) { _ @< >@n *= i; _ }|| ||# break[#break-note break] _ @< >@||break||break|| ||# continue[#continue-note continue] _ @< >@||continue||continue|| ||# for-local-scope[#for-local-scope-note for with local scope]|| ||int n = 1; _ _ for (int i = 1; i <= 10; ++i) { _ @< >@n *= i; _ } _ _ ##gray|@@//@@ is no longer in scope##|| ||# infinite-loop[#infinite-loop-note infinite loop]|| ||for (;;) { _ @< >@##gray|@@//@@ code## _ } _ _ while (1) { _ @< >@##gray|@@//@@ code## _ }|| ||# break-from-nested-loops[#break-from-nested-loops-note break from nested loops]|| ||int a, b, c; _ _ outer: _ for (a = 1; ; ++a) { _ @< >@for (b = 1; b < a; ++b) { _ @< >@@< >@c = (math.sqrt(a * a + b * b)).truncate(); _ @< >@@< >@if (c * c == a * a + b * b) { _ @< >@@< >@@< >@break outer; _ @< >@@< >@} _ @< >@} _ }|| ||# single-stmt-branch-loop[#single-stmt-branch-loop-note single statement branches and loops]|| ||while (n % 17 == 0) _ @< >@++n; _ _ if (n < 0) _ @< >@print(“negative”);|| ||# dangling-else[#dangling-else-note dangling else]|| ||int a = 1, b = -3, c; _ _ ##gray|@@//@@ indentation shows how ambiguity is resolved## _ if (a > 0) _ @< >@if (b > 0) _ @< >@@< >@c = 1; _ @< >@else _ @< >@@< >@c = 2;|| ||||||~ # exceptions[#exceptions-note exceptions]|| ||~ ||~ typescript||~ dart|| ||# base-exc[#base-exc-note base exception]||##gray|//Any value can be thrown.//##||Exception _ Error _ _ ##gray|//Any non-null value can be thrown.//##|| ||# predefined-exc[#predefined-exc-note predefined exceptions]||Error _ @< >@EvalError _ @< >@RangeError _ @< >@ReferenceError _ @< >@SyntaxError _ @< >@TypeError _ @< >@URIError||Error _ @< >@AbstractClassInstantiationError _ @< >@ArgumentError _ @< >@@< >@RangeError _ @< >@@< >@@< >@IndexError _ @< >@AssertionError _ @< >@@< >@TypeError _ @< >@CastError _ @< >@ConcurrentModificationError _ @< >@CyclicInitializationError _ @< >@FallThroughError _ @< >@JsonUnsupportedObjectError _ @< >@NoSuchMethodError _ @< >@NullThrownError _ @< >@OutOfMemoryError _ @< >@RangeError _ @< >@StackOverflowError _ @< >@StateError _ @< >@UnimplementedError _ @< >@UnsupportedError _ _ ##gray|//intended to be caught://## _ Exception _ @< >@FormatException _ @< >@IntegerDivisionByZeroException|| ||# raise-exc[#raise-exc-note raise exception] _ @< >@||throw new Error(“bad arg”);||throw new Exception(“bad arg”);|| ||# catch-all-handler[#catch-all-handler-note catch-all handler] _ @< >@||try { _ @< >@risky(); _ } _ catch (e) { _ @< >@alert(“risky failed”); _ }||try { _ @< >@risky(); _ } _ catch (e) { _ @< >@print(“risky failed”); _ }|| ||# re-raise-exc[#re-raise-exc-note re-raise exception]||try { _ @< >@throw new Error(“bam!”); _ } _ catch (e) { _ @< >@alert(“re-raising@@…@@”); _ @< >@throw e; _ }||try { _ @< >@throw new Exception(“bam!”); _ } _ catch (e) { _ @< >@print(“re-raising…”); _ @< >@rethrow; _ }|| ||# def-exc[#def-exc-note define exception]||function Bam(msg) { _ @< >@this.message = msg; _ } _ _ Bam.prototype = new Error;||class Bam implements Exception { _ @< >@String msg; _ @< >@Bam(this.msg); _ }|| ||# handle-exc[#handle-exc-note handle exception]||try { _ @< >@throw new Bam(“bam!”); _ } _ catch (e) { _ @< >@if (e instanceof Bam) { _ @< >@@< >@alert(e.message); _ @< >@} _ @< >@else { _ @< >@@< >@throw e; _ @< >@} _ }||try { _ @< >@throw new Bam(“bam!”); _ } _ on Bam catch (e) { _ @< >@print(e.msg); _ }|| ||# finally-block[#finally-block-note finally block] _ @< >@||acquire_resource(); _ try { _ @< >@risky(); _ } _ finally { _ @< >@release_resource(); _ }||acquire_resource(); _ try { _ @< >@risky(); _ } _ finally { _ @< >@release_resource(); _ }|| ||||||~ # streams[#streams-note streams]|| ||~ ||~ node||~ dart|| ||# std-file-handles[#std-file-handles-note standard file handles]||process.stdin _ process.stdout _ process.stderr||import ‘dart:io’ as io; _ _ io.stdin io.stdout io.stderr|| ||# read-line-stdin[#read-line-stdin-note read line from stdin] _ @< >@|| || || ||# eof[#eof-note end-of-file behavior]|| || || ||# chomp[#chomp-note chomp] _ @< >@|| || || ||# write-line-stdout[#write-line-stdout-note write line to stdout] _ @< >@||console.log(“Hello, World”);||import ‘dart:io’ as io; _ _ print(‘Hello, World!’); _ _ io.stdout.writeln(‘Hello, World!’);|| ||# printf[#printf-note write formatted string to stdout]|| || || ||# open-file[#open-file-note open file for reading] _ @< >@|| || || ||# open-file-write[#open-file-write-note open file for writing] _ @< >@||var f = fs.openSync(“/tmp/test”, “w”);|| || ||# file-encoding[#file-encoding-note set file handle encoding]|| || || ||# open-file-append[#open-file-append-note open file for appending]|| || || ||# close-file[#close-file-note close file] _ @< >@|| || || ||# close-file-implicitly[#close-file-implicitly-note close file implicitly]|| || || ||# io-err[#io-err-note i/o error]|| || || ||# encoding-err[#encoding-err-note encoding error]|| || || ||# read-line[#read-line-note read line] _ @< >@|| || || ||# file-iterate[#file-iterate-note iterate over file by line] _ @< >@|| || || ||# read-file-array[#read-file-array-note read file into array of strings]|| || || ||# read-file-str[#read-file-str-note read file into string]||var fs = require(‘fs’); _ _ var s = fs.readFileSync(‘/etc/hosts’, ‘utf8’);||import ‘dart:io’ as io; _ _ File f = new io.File(‘/etc/hosts’); _ f.readAsString().then((String s) { _ @< >@print(‘length: ${s.length}’); _ });|| ||# write-str[#write-str-note write string] _ @< >@|| || || ||# write-line[#write-line-note write line] _ @< >@|| || || ||# flush[#flush-note flush file handle] _ @< >@|| || || ||# eof-test[#eof-test-note end-of-file test] _ @< >@|| || || ||# seek[#seek-note file handle position] _ _ ##gray|//get, set//##|| || || ||# tmp-file[#tmp-file-note open temporary file]|| || || ||# stringio[#stringio-note in memory file]|| || || ||||||~ # files[#files-note files]|| ||~ ||~ node||~ dart|| ||# file-test[#file-test-note file exists test, file regular test] _ @< >@||var fs = require(‘fs’); _ _ var qry = fs.existsSync(‘/etc/hosts’); _ _ var stat = fs.statSync(‘/etc/hosts’); _ var qry2 = stat.isFile();||import ‘dart:io’ as io; _ _ File f = new io.File(“/tmp/foo”); _ _ ##gray|@@//@@ existence check?## _ _ if (f.existsSync()) { _ @< >@print(“is a regular file\n”); _ }|| ||# file-size[#file-size-note file size] _ @< >@||var fs = require(‘fs’); _ _ var stat = fs.statSync(‘/etc/hosts’); _ var sz = stat.size;||f.lengthSync()|| ||# readable-writable-executable[#readable-writable-executable-note is file readable, writable, executable]|| || || ||# chmod[#chmod-note set file permissions] _ @< >@||var fs = require(‘fs’); _ _ fs.chmodSync(‘/tmp/foo’, _ @< >@parseInt(‘755’, 8));|| || ||# last-modification-time[#last-modification-time-note last modification time]||var fs = require(‘fs’); _ _ var stat = fs.statSync(‘/etc/hosts’); _ var dt = stat.mtime;||import ‘dart:io” as io; _ _ File f = new io.File(“/etc/hosts”); _ print(f.lastModifiedSync());|| ||# file-cp-rm-mv[#file-cp-rm-mv-note copy file, remove file, rename file]||##gray|# npm install fs-extra## _ var fs = require(‘fs-extra’); _ _ fs.copySync(‘/tmp/foo’, ‘/tmp/bar’); _ fs.unlinkSync(‘/tmp/foo’); _ fs.renameSync(‘/tmp/bar’, ‘/tmp/foo’);||import ‘dart:io’ as io; _ _ File f = new io.File(“/tmp/foo”); _ f.copySync(“/tmp/bar”); _ f.deleteSync(); _ File f2 = new io.File(“/tmp/bar”); _ f2.renameSync(“/tmp/foo”);|| ||# symlink[#symlink-note create symlink, symlink test, readlink]||var fs = require(‘fs’); _ _ fs.symlinkSync(‘/etc/hosts’, _ @< >@’/tmp/hosts’); _ var stat = fs.statSync(‘/tmp/hosts’); _ stat.isSymbolicLink(); _ var path = fs.readlinkSync( _ @< >@’/tmp/hosts’);|| || ||# unused-file-name[#unused-file-name-note generate unused file name]|| || || ||||||~ # file-fmt[#file-fmt-note file formats]|| ||~ ||~ node||~ dart|| ||# parse-csv[#parse-csv-note parse csv]||var fs = require(‘fs’); _ ##gray|# npm install csv## _ var csv = require(‘csv’); _ _ var s = fs.readFileSync(‘no-header.csv’); _ var a; _ csv().from.string(s).to.array(function(d) { a = d });|| || ||# generate-csv[#generate-csv-note generate csv]||##gray|# npm install csv## _ var csv = require(‘csv’); _ _ var a = [[‘one’, ‘une’, ‘uno’], _ [‘two’, ‘deux’, ‘dos’]]; _ _ var s; _ csv().from.array(a).to.string(function (o) { s = o; });|| || ||# parse-json[#parse-json-note parse json]||var s1 = ‘{"t”:1,"f”:0}’; _ var d1 = JSON.parse(s1);|| || ||# generate-json[#generate-json-note generate json]||var d2 = {’t’: 1, ‘f’: 0}; _ var s2 = JSON.stringify(d1);|| || ||# parse-yaml[#parse-yaml-note parse yaml]|| || || ||# generate-yaml[#generate-yaml-note generate yaml]|| || || ||# parse-xml[#parse-xml-note parse xml] _ ##gray|//all nodes matching xpath query; first node matching xpath query//##||##gray|# npm install xmldom xpath## _ var dom = require(‘xmldom’).DOMParser; _ var xpath = require(‘xpath’); _ _ var xml = ‘foo’; _ var doc = new dom().parseFromString(xml); _ var nodes = xpath.select(‘/a/b/c’, doc); _ nodes.length; _ nodes[0].firstChild.data;|| || ||# generate-xml[#generate-xml-note generate xml]||##gray|# npm install xmlbuilder## _ var builder = require(‘xmlbuilder’); _ _ var xml = builder.create(‘a’).ele(‘b’, {id: 123}, ‘foo’).end();|| || ||# parse-html[#parse-html-note parse html]|| || || ||||||~ # directories[#directories-note directories]|| ||~ ||~ node||~ dart|| ||# working-dir[#working-dir-note working directory]||var old_dir = process.cwd(); _ _ process.chdir(“/tmp”);|| || ||# build-pathname[#build-pathname-note build pathname]|| || || ||# dirname-basename[#dirname-basename-note dirname and basename]|| || || ||# absolute-pathname[#absolute-pathname-note absolute pathname] _ ##gray|//and tilde expansion//##|| || || ||# dir-iterate[#dir-iterate-note iterate over directory by file]||var fs = require(‘fs’); _ _ fs.readdirSync(‘/etc’).forEach( _ @< >@function(s) { console.log(s); } _ );|| || ||# glob[#glob-note glob paths]|| || || ||# mkdir[#mkdir-note make directory]|| || || ||# recursive-cp[#recursive-cp-note recursive copy]|| || || ||# rmdir[#rmdir-note remove empty directory]|| || || ||# rm-rf[#rm-rf-note remove directory and contents]|| || || ||# dir-test[#dir-test-note directory test] _ @< >@|| ||import ‘dart:io’ as io; _ _ bool isDir; _ _ io.FileSystemEntity.isDirectory(‘/tmp’).then((isDir) { _ @< >@if (isDir) { _ @< >@@< >@print(‘is directory’); _ @< >@} else { _ @< >@@< >@print(‘not a directory’); _ @< >@} _ });|| ||# unused-dir[#unused-dir-note generate unused directory]|| || || ||# system-tmp-dir[#system-tmp-dir-note system temporary file directory]|| || || ||||||~ # processes-environment[#processes-environment-note processes and environment]|| ||~ ||~ node||~ dart|| ||# cmd-line-arg[#cmd-line-arg-note command line arguments] _ ##gray|//and script name//##||process.argv.slice(2) _ process.argv[1] _ ##gray|@@//@@ process.argv[0] contains “node”##|| || ||# env-var[#env-var-note environment variable] _ _ ##gray|//get, set//##||process.env[“HOME”] _ _ process.env[“PATH”] = “/bin”;|| || ||# pid[#pid-note get pid, parent pid]||process.pid _ ##gray|//none//##|| || ||# user-id-name[#user-id-name-note user id and name]|| || || ||# exit[#exit-note exit] _ @< >@||process.exit(0);|| || ||# signal-handler[#signal-handler-note set signal handler] _ @< >@|| || || ||# executable-test[#executable-test-note executable test] _ @< >@|| || || ||# external-cmd[#external-cmd-note external command] _ @< >@|| ||import ‘dart:io’ as io; _ _ io.Process.start(‘ls’, [‘-l’, ‘/tmp’]).then((process) { _ @< >@@< >@io.stdout.addStream(process.stdout); _ @< >@@< >@io.stderr.addStream(process.stderr); _ @< >@@< >@process.exitCode.then(print); _ @< >@});|| ||# shell-esc-external-cmd[#shell-esc-external-cmd-note shell-escaped external command] _ @< >@|| || || ||# cmd-subst[#cmd-subst-note command substitution] _ @< >@|| || || ||||||~ # libraries-namespaces[#libraries-namespaces-note libraries and namespaces]|| ||~ ||~ node||~ dart|| ||# load-lib[#load-lib-note load library] _ @< >@|| ||##gray|@@//@@ load ./foo.dart:## _ import ‘foo.dart’ as foo; _ _ ##gray|@@//@@ load built-in library:## _ import ‘dart:io’ as io; _ _ ##gray|@@//@@ library installed by package manager:## _ import ‘package:foo/foo.dart’ as foo;|| ||# load-lib-subdir[#load-lib-subdir-note load library in subdirectory]|| ||import ‘lib/foo.dart’ as foo;|| ||# hot-patch[#hot-patch-note hot patch] _ @< >@|| || || ||# load-err[#load-err-note load error]|| || || ||# main-in-lib[#main-in-lib-note main routine in library]|| || || ||# lib-path[#lib-path-note library path]|| || || ||# lib-path-env[#lib-path-env-note library path environment variable]|| || || ||# lib-path-cmd-line[#lib-path-cmd-line-note library path command line option]|| || || ||# simple-global-identifiers[#simple-global-identifiers-note simple global identifiers]|| || || ||# multiple-label-identifiers[#multiple-label-identifiers-note multiple label identifiers]|| || || ||# label-separator[#label-separator-note label separator] _ @< >@|| || || ||# root-namespace[#root-namespace-note root namespace definition]|| || || ||# namespace-decl[#namespace-decl-note namespace declaration] _ @< >@|| ||##gray|@@//@@ not required in file containing main():## _ library foo;|| ||# child-namespace-decl[#child-namespace-decl-note child namespace declaration]|| || || ||# import-def[#import-def-note import definitions] _ @< >@|| ||import ‘foo’ show bar, baz;|| ||# import-namespace[#import-namespace-note import all definitions in namespace] _ @< >@|| ||import ‘foo’;|| ||# import-all-subnamespaces[#import-all-subnamespaces-note import all subnamespaces]|| || || ||# shadow-avoidance[#shadow-avoidance-note shadow avoidance]|| ||import ‘foo’ as fu;|| ||||||~ # user-defined-types[#user-defined-types-note user-defined-types]|| ||~ ||~ typescript||~ dart|| ||# enumerated-type[#enumerated-type-note enumerated type]||enum Color {Red, Green, Blue}; _ ##gray|@@//@@ assigns c the value 1:## _ var c: Color = Color.Green;||enum Color {red, green, blue} _ _ Color col = Color.green;|| ||# struct-def[#struct-def-note struct definition]||interface Medals { _ @< >@country: string, _ @< >@gold: number, _ @< >@silver: number, _ @< >@bronze: number _ };|| || ||# optional-struct-member[#optional-struct-member-note optional struct member]||interface Person { _ @< >@name: string, _ @< >@alma_mater?: string _ }|| || ||# struct-literal[#struct-literal-note struct literal]||var france: Medals = {country: “France”, _ @< >@gold: 8, _ @< >@silver: 7, _ @< >@bronze: 9 _ }; _ _ ##gray|@@//@@ not an error for the literal to contain members _ @@//@@ not in the struct definition##|| || ||# struct-lookup[#struct-lookup-note struct lookup]||france.gold|| || ||# struct-update[#struct-update-note struct update]||france.gold = 9; _ _ ##gray|@@//@@ assignment to members not in struct definition _ @@//@@ is permitted##|| || ||# type-alias[#type-alias-note type alias]||##gray|@@//@@ function:## _ interface BinaryOp { _ @< >@(x: number, y: number): number _ } _ _ var add: BinaryOp = (x, y) => { return x + y; } _ _ ##gray|@@//@@ array or dictionary:## _ interface NumberSeq { _ @< >@[index: number]: number _ } _ _ var primes: NumberSeq = [2, 3, 5, 7, 11];||##gray|@@//@@ function types only:## _ typedef num BinaryOp(num x, num y);|| ||||||~ # generic-types[#generic-types-note generic types]|| ||~ ||~ typescript||~ dart|| ||# generic-func[#generic-func-note generic function]||function identity(arg: T): T { _ @< >@return arg; _ } _ _ console.log(identity(“lorem ipsum”));|| || ||# generic-class[#generic-class-note generic class]||class Holder { _ @< >@constructor(public value: T) {} _ } _ _ var holder = new Holder(3); _ console.log(holder.value);|| || ||||||~ # objects[#objects-note objects]|| ||~ ||~ typescript||~ dart|| ||# def-class[#def-class-note define class] _ @< >@||class Int { _ @< >@public value: number; _ @< >@constructor(v: number) { _ @< >@@< >@this.value = v; _ @< >@} _ } _ _ ##gray|@@//@@ constructor params declared public or _ @@//@@ private become object attributes## _ class Int { _ @< >@constructor(public value: number) {} _ }||class Int { _ @< >@int value; _ @< >@Int(int n) { _ @< >@@< >@this.value = n; _ @< >@} _ }|| ||# create-obj[#create-obj-note create object] _ @< >@||var i = new Int(0); _ var i2 = new Int(7);||Int i = new Int(7);|| ||# instance-var[#instance-var-note instance variable visibility]|| || || ||# getter-setter[#getter-setter-note get and set instance variable] _ @< >@||i.value = i.value + 1;||i.value = i.value + 1; _ _ ##gray|@@//@@ inside method:## _ this.value = this.value + 1;|| ||# def-method[#def-method-note define method] _ @< >@||class Int { _ @< >@constructor(public value: number) {} _ @< >@plus(v: number) { _ @< >@@< >@this.value += v; _ @< >@} _ }||class Int { _ @< >@int value; _ @< >@Int(int n) { _ @< >@@< >@this.value = n; _ @< >@} _ @< >@void plus(num v) { _ @< >@@< >@this.value += v; _ @< >@} _ }|| ||# invoke-method[#invoke-method-note invoke method] _ @< >@||i.plus(3);||i.plus(3);|| ||# def-class-method[#def-class-method-note define class method]||class Int { _ @< >@static getInstances() { _ @< >@@< >@return Int.instances; _ @< >@} _ }||class Int { _ @< >@static int getInstances() { _ @< >@@< >@return instances; _ @< >@} _ }|| ||# invoke-class-method[#invoke-class-method-note invoke class method] _ @< >@||Int.getInstances()||Int.getInstances()|| ||# def-classs-var[#def-class-var-note define class variable]||class Int { _ @< >@static instances: number = 0; _ @< >@constructor(public value: number) { _ @< >@@< >@Int.instances += 1; _ @< >@} _ }||class Int { _ @< >@static int instances = 0; _ @< >@int value; _ @< >@Int(int n) { _ @< >@@< >@this.value = n; _ @< >@@< >@instances += 1; _ @< >@} _ }|| ||# class-var-getter-setter[#class-var-getter-setter-note get and set class variable]||Int.instances = Int.instances + 1;||##gray|@@//@@ inside class:## _ instances = instances + 1; _ _ ##gray|@@//@@ outside class:## _ Int.instances = Int.instances + 1;|| ||# method-missing[#method-missing-note handle undefined method invocation] _ @< >@|| || || ||# destructor[#destructor-note destructor] _ @< >@|| || || ||||||~ # inheritance-polymorphism[#inheritance-polymorphism-note inheritance and polymorphism]|| ||~ ||~ typescript||~ dart|| ||# inheritance[#inheritance-note subclass] _ @< >@||class Counter extends Int { _ @< >@constructor(v: number) { _ @< >@@< >@super(v); _ @< >@} _ @< >@incr() { _ @< >@@< >@this.value += 1; _ @< >@} _ }|| || ||||||~ # reflection[#reflection-note reflection]|| ||~ ||~ typescript||~ dart|| ||# object-id[#object-id-note object id] _ @< >@||##gray|//none//##|| || ||# inspect-type[#inspect-type-note inspect type] _ @< >@||typeof([]) === ‘object’||var n = 3; _ if (n is int) { _ @< >@n += 1; _ } _ _ if (n is! String) { _ @< >@n += “s”; _ }|| ||# types[#types-note basic types]||number _ string _ boolean _ undefined _ function _ object _ _ ##gray|# these evaluate as ‘object’:## _ typeof(null) _ typeof([]) _ typeof({})||dynamic _ num|| ||# inspect-class[#inspect-class-note inspect class]||##gray|@@//@@ returns prototype object:## _ Object.getPrototypeOf(o)|| || ||# inspect-class-hierarchy[#inspect-class-hierarchy-note inspect class hierarchy]||var pa = Object.getPrototypeOf(o) _ ##gray|@@//@@prototype’s of prototype object:## _ var grandpa = Object.getPrototypeOf(pa)|| || ||# has-method[#has-method-note has method?] _ @< >@||o.reverse && typeof(o.reverse) === ‘function’|| || ||# msg-passing[#msg-passing-note message passing] _ @< >@||##gray|//not a standard feature//##|| || ||# eval[#eval-note eval] _ @< >@||eval(‘1 + 1’)|| || ||# list-obj-methods[#list-obj-methods-note list object methods] _ @< >@|| || || ||# list-obj-attr[#list-obj-attr-note list object attributes] _ @< >@|| || || ||# list-loaded-lib[#list-loaded-lib-note list loaded libraries]|| || || ||# list-loaded-namespaces[#list-loaded-namespaces-note list loaded namespaces]|| || || ||# inspect-namespace[#inspect-namespace-note inspect namespace]|| || || ||# pretty-print[#pretty-print-note pretty-print] _ @< >@||var d = {"lorem”: 1, “ipsum”: [2, 3]}; _ console.log(JSON.stringify(d, null, 2));|| || ||# src-line-file[#src-line-file-note source line number and file name]|| || || ||# cmd-line-doc[#cmd-line-doc-note command line documentation]|| || || ||||||~ # net-web[#net-web-note net and web]|| ||~ ||~ typescript||~ dart|| ||# hostname-ip[#hostname-ip-note get local hostname, dns lookup, reverse dns lookup]|| || || ||# http-get[#http-get-note http get] _ @< >@||##gray|@@//@@ npm install request## _ var request = require(‘request’); _ _ request(‘@@http://www.google.com@@’, _ @< >@function(err, resp, body) { _ @< >@@< >@if (!err && resp.statusCode == 200) { _ @< >@@< >@@< >@console.log(body); _ @< >@@< >@} _ @< >@} _ );|| || ||# http-post[#http-post-note http post] _ @< >@|| || || ||# serve-pwd[#serve-pwd-note serve working directory]|| || || ||# absolute-url[#absolute-url-note absolute url] _ ##gray|//from base and relative url//##|| || || ||# parse-url[#parse-url-note parse url]|| || || ||# url-encode[#url-encode-note url encode/decode] _ @< >@|| || || ||# html-escape[#html-escape-note html escape] _ ##gray|//escape character data, escape attribute value, unescape html entities//##|| || || ||# base64[#base64-note base64 encode/decode]|| || || ||||||~ # debugging-profiling[#debugging-profiling-note debugging and profiling]|| ||~ ||~ node||~ dart|| ||# check-syntax[#check-syntax-note check syntax]||$ tsc @@–@@noEmit foo.ts|| || ||# lint[#lint-note lint]||$ npm install -g tslint _ $ tslint -c ~/.tslint.json -f foo.ts|| || ||~ ||~ ##EFEFEF|@@_________________________________________@@##||~ ##EFEFEF|@@_________________________________________@@##||
# version-note + [#version Version]
# grammar-execution-note + [#grammar-execution Grammar and Execution]
# variables-expressions-note + [#variables-expressions Variables and Expressions]
# arithmetic-logic-note + [#arithmetic-logic Arithmetic and Logic]
# strings-note + [#strings Strings]
# regexes-note + [#regexes Regexes]
# dates-time-note + [#dates-time Dates and Time]
# arrays-note + [#arrays Arrays]
# dictionaries-note + [#dictionaries Dictionaries]
# functions-note + [#functions Functions]
# execution-control-note + [#execution-control Execution Control]
# exceptions-note + [#exceptions Exceptions]
# streams-note + [#streams Streams]
# files-note + [#files Files]
# file-formats-note + [#file-formats File Formats]
# directories-note + [#directories Directories]
# processes-environment-note + [#processes-environment Processes and Environment]
# libraries-namespaces-note + [#libraries-namespaces Libraries and Namespaces]
# user-defined-types-note + [#user-defined-types User-Defined Types]
# generic-types-note + [#generic-types Generic Types]
# objects-note + [#objects Objects]
# inheritance-polymorphism-note + [#inheritance-polymorphism Inheritance and Polymorphism]
# reflection-note + [#reflection Reflection]
# net-web-note + [#net-web Net and Web]
# debugging-profiling-note + [#debugging-profiling Debugging and Profiling]
# check-syntax-note ++ [#check-syntax check syntax]
# lint-note ++ [#lint lint]
typescript:
How to get a {{tslint.json}} file:
code $ curl https://github.com/palantir/tslint/blob/master/docs/sample.tslint.json > ~/.tslint.json /code
# typescript + [#top TypeScript]
[http://www.typescriptlang.org/Handbook Handbook]
# dart + [#top Dart]
[https://www.dartlang.org/docs/ Programmer’s Guide] [https://api.dartlang.org/apidocs/channels/stable/dartdoc-viewer/home API Reference]