619 Matching Annotations
  1. Last 7 days
  2. Jul 2022
  3. May 2022
    1. let timer; // Timer identifier const waitTime = 500; // Wait time in milliseconds // Search function const search = (text) => { // TODO: Make HTTP Request HERE }; // Listen for `keyup` event const input = document.querySelector('#input-text'); input.addEventListener('keyup', (e) => { const text = e.currentTarget.value; // Clear timer clearTimeout(timer); // Wait for X ms and then process the request timer = setTimeout(() => { search(text); }, waitTime); });

      let timer; // timer identifier const waitTime = 500; // Wait time in milliseconds

      // search function const search = (text) => { // to do: make http request here }

      // Listen for keyup event const input = document.querySelector('#input-text'); input.addEventListener('keyup', (e) => { const text = e.currentTarget.value; // clear timer clearTimeout(timer);

      // Wait for X ms and then process the request timer = setTimeout(() => { search(text); }, waitTime); });

    1. // Get the input box let input = document.getElementById('my-input'); // Init a timeout variable to be used below let timeout = null; // Listen for keystroke events input.addEventListener('keyup', function (e) { // Clear the timeout if it has already been set. // This will prevent the previous task from executing // if it has been less than <MILLISECONDS> clearTimeout(timeout); // Make a new timeout set to go off in 1000ms (1 second) timeout = setTimeout(function () { console.log('Input Value:', textInput.value); }, 1000); });

      let timeout = setTimeout(callback, milliseconds); clearTimeout(timeout);

      document.getElementById("id-name"); object.addEventListener('event-name',callback);

    2. In order to execute an event listener (or any function for that matter) after the user stops typing, we need to know about the two built-in JavaScript methods setTimeout(callback, milliseconds) and clearTimeout(timeout): setTimeout is a JavaScript method that executes a provided function after a specified amount of time (in milliseconds). clearTimeout is a related method that can be used to cancel a timeout that has been queued.

      Step 1. Listen for User Input

      <input type="text" id="my-input" />

      let input = document.querySelector('#my-input'); input.addEventListener('keyup', function (e) { console.log('Value:', input.value); })

      Step2: Debounce Event Handler Function

      let input = document.getElementById('my-input'); let timeout = null;

      input.addEventListener('keyup', function(e) { clearTimeout(timeout);

      timeout = setTimeout(function() { console.llog('Input Value:', textInput.value); }, 1000); })

    1. 227 This answer is not useful Show activity on this post. Your real question seem to be: Why: null >= 0; // true But: null == 0; // false
      • ME TOO
    1. encodeURIComponent() escapes all characters except: Not Escaped: A-Z a-z 0-9 - _ . ! ~ * ' ( )
      • EXCEPTIONs
      • ( =%28
      • ) = %F29
  4. Apr 2022
    1. Stimulus is a JavaScript framework with modest ambitions. It doesn’t seek to take over your entire front-end—in fact, it’s not concerned with rendering HTML at all.
    1. 1) Use Set Using Set(), an instance of unique values will be created, implicitly using this instance will delete the duplicates. So we can make use of this instance and from there we will have to convert that instance into a new array, and that would be it: let chars = ['A', 'B', 'A', 'C', 'B']; let uniqueChars = [...new Set(chars)]; console.log(uniqueChars);
      • SET = unique values
  5. developer.mozilla.org developer.mozilla.org
    1. Basic Examplelet myFirstPromise = new Promise((resolve, reject) => { // We call resolve(...) when what we were doing asynchronously was successful, and reject(...) when it failed. // In this example, we use setTimeout(...) to simulate async code. // In reality, you will probably be using something like XHR or an HTML5 API. setTimeout( function() { resolve("Success!") // Yay! Everything went well! }, 250) }) myFirstPromise.then((successMessage) => { // successMessage is whatever we passed in the resolve(...) function above. // It doesn't have to be a string, but if it is only a succeed message, it probably will be. console.log("Yay! " + successMessage) });
      • BASIC
  6. Mar 2022
    1. let msg = res.code != 0 ? res.msg || '操作失败' : res.msg || "操作成功";

      代码优化,可读性的衡量:

      let options = res.code != 0 ? { msg: '操作失败', icon: 2} : {msg: "操作成功", icon: 1};

      msg = res.msg || options.msg;

    1. JavaScript 的数学运算

      基于 Math 类 Math.ceil() Math.floor()

      3.1415926.toFixed(2) // 保留小数位 99.89233.toPrecision(5) // 整体长度,含整数部分

      全局对象 window 的方法

      parseInt('100') parseInt(100.12) parseInt('string') // => NaN

      Number("string") // => 0

      位运算:

      | 0 , 和 0 按位或 ~~ ,两次按位非

      0,右移 0 位 << 0,左移 0 位

      0,无符号右移 0 位

  7. Feb 2022
    1. Here's a very simple solution without too much code using a very simple map of diacritics that includes some or all that map to ascii equivalents containing more than one character, i.e. Æ => AE, ffi => ffi, etc... Also included some very basic functional tests var diacriticsMap = { '\u00C0': 'A', // À => A
      • MAP of chars to change
    2. One solution that seems to be way faster by the given test : http://jsperf.com/diacritics/9 function removeDiacritics(str) { return str.replace(/[^A-Za-z0-9\s]+/g, function(a){ return diacriticsMap[a] || a; }); } removeDiacritics(teste); Working example: http://jsbin.com/sovorute/1/edit Reasoning: One reason this is much faster is because we only iterate through the special characters, picked by the negated regex pattern. The fastest of the tests (String Iteration without in) iterates 1001 on the given text, which means every character. This one iterates only 35 times and outputs the same result. Keep in mind that this will only replace what is indicated in the map. Classic article on the subject: http://alistapart.com/article/accent-folding-for-auto-complete Credit: http://semplicewebsites.com/removing-accents-javascript , also provides a nice character map.
      • GOOD SOLUTION
    3. With ES2015/ES6 String.prototype.normalize(), const str = "Crème Brulée" str.normalize("NFD").replace(/[\u0300-\u036f]/g, "") > "Creme Brulee" Two things are happening here: normalize()ing to NFD Unicode normal form decomposes combined graphemes into the combination of simple ones. The è of Crème ends up expressed as e + ̀. Using a regex character class to match the U+0300 → U+036F range, it is now trivial to globally get rid of the diacritics, which the Unicode standard conveniently groups as the Combining Diacritical Marks Unicode block. As of 2021, one can also use Unicode property escapes: str.normalize("NFD").replace(/\p{Diacritic}/gu, "")

      This solution is the only correct solution here. This works on NodeJS 4.6, Firefox 50 and Chrome 54. – david_p Dec 9, 2016 at 13:12

    4. 6 This solution is the only correct solution here. This works on NodeJS 4.6, Firefox 50 and Chrome 54. – david_p Dec 9, 2016 at 13:12

      With ES2015/ES6 String.prototype.normalize(),

      const str = "Crème Brulée" str.normalize("NFD").replace(/[\u0300-\u036f]/g, "")

      "Creme Brulee" Two things are happening here:

      normalize()ing to NFD Unicode normal form decomposes combined graphemes into the combination of simple ones. The è of Crème ends up expressed as e + ̀. Using a regex character class to match the U+0300 → U+036F range, it is now trivial to globally get rid of the diacritics, which the Unicode standard conveniently groups as the Combining Diacritical Marks Unicode block. As of 2021, one can also use Unicode property escapes:

      str.normalize("NFD").replace(/\p{Diacritic}/gu, "")

    5. 23 There's always one char that fails.. 'ąśćńżółźćę'.normalize('NFD').replace(/[\u0300-\u036f]/g, "") -> ascnzołzce (missing match for ł -> l). – Paweł Fus Jul 24, 2017 at 13:23 15 Correct me if I'm wrong but ł is a letter in itself, not an accented L. Therefore it should not be changed to l. – Lewis Diamond Jul 25, 2017 at 15:28 4 @PawełFus - the ł does not fall within the character class range. You can target it specifically as \u0142 ---SO---> 'ł'.replace(/\u0142/g, "l") – Chris Geirman Nov 26, 2017 at 19:18
      • DIACRITICS
    1. All the popular web browsers have built-in JavaScript engines. Hence, you can run JavaScript on a browser. To run JavaScript on a browser,
  8. Jan 2022
    1. nstead of using the /regex\d/g syntax, you can construct a new RegExp object: var replace = "regex\\d"; var re = new RegExp(replace,"g");
      • REGEX
      • crear regex a partir de pattern
      • CIUDADO: \b -> \b; \s -> \s en la cadena pattern
    1. My gut told me calling an async function from the setTimeout callback was a bad thing. Since the setTimeout machinery ignores the return value of the function, there is no way it was awaiting on it. This means that there will be an unhandled promise. An unhandled promise could mean problems if the function called in the callback takes a long time to complete or throws an error.
    2. The callback executed by setTimeout is not expected to return anything, it just ignores the returned value. Since once you enter the promise/async world in JavaScript you cannot escape, I was left to wonder what happens when the setTimeout callback returns a promise?
    1. test2 being marked async does wrap your return value in a new promise:
    2. const rejectedP = Promise.reject('-'); const finallyP = rejectedP.finally(); const result1 = rejectedP; const result2 = new Promise(resolve => { const rejectedP = Promise.reject('-'); const finallyP = rejectedP.finally(); resolve(rejectedP); }); we can see that the first snippet creates two promises (result1 and rejectedP being the same) while the second snippet creates three promises. All of these promises are rejected, but the rejectedP rejection is handled by the callbacks attached to it, both through ….finally() and resolve(…) (which internally does ….then(resolve, reject)). finallyP is the promise whose rejection is not handled in the both examples. In the second example, result2 is a promise distinct from rejectedP that is also not handled, causing the second event.
    1. You basically did var a = promise.then(…); var b = promise.catch(…); creating a branch in the chain. If promise is getting rejected now, the catch callback will be called and b will be a fulfilled promise just fine, but the a promise is getting rejected too and nobody handles that. Instead, you should use both arguments of then and write Requirement.create({id: id, data: req.body.data, deleted: false}) .then(requirement => { res.json(requirement); }, reason => { let err = {'error': reason}; res.json(err); });
    1. but has a critical difference: the expression console.log("before 2"); does not and cannot depend on the resolved value result. The throw propagates through all chained promises, and when it stops, there is no remaining undefined behavior! No piece of code is left in an unclear state, and therefore there is no reason to crash.
    2. Node is entirely at liberty to limit the design the same way we crash the process on errors (which browsers do not).
  9. www.npmjs.com www.npmjs.com
    1. co(function* () {  var result = yield Promise.resolve(true);  return result;}).then(function (value) {  console.log(value);}, function (err) {  console.error(err.stack);});
    2. Generator based control flow goodness for nodejs and the browser, using promises, letting you write non-blocking code in a nice-ish way.
    1. Yes, precisely because I've been involved in maintaining codebases built without real full stack frameworks is why I say what I said.The problem we have in this industry, is that somebody reads these blog posts, and the next day at work they ditch the "legacy rails" and starts rewriting the monolith in sveltekit/nextjs/whatever because that's what he/she has been told is the modern way to do full stack.No need to say those engineers will quit 1 year later after they realize the mess they've created with their lightweight and simple modern framework.I've seen this too many times already.It is not about gatekeeping. It is about engineers being humble and assume it is very likely that their code is very unlikely to be better tested, documented, cohesive and maintained than what you're given in the real full stack frameworks.Of course you can build anything even in assembler if you want. The question is if that's the most useful thing to do with your company's money.
    1. The encodeURIComponent() function encodes a URI by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character
      • ENCODEURI
    1. Decoding query parameters from a URL decodeURIComponent cannot be used directly to parse query parameters from a URL. It needs a bit of preparation. function decodeQueryParam(p) { return decodeURIComponent(p.replace(/\+/g, ' ')); } decodeQueryParam('search+query%20%28correct%29'); // 'search query (correct)'
      • DECODEURI
    1. The old versions of JavaScript had no import, include, or require, so many different approaches to this problem have been developed. But since 2015 (ES6), JavaScript has had the ES6 modules standard to import modules in Node.js, which is also supported by most modern browsers. For compatibility with older browsers, build tools like Webpack and Rollup and/or transpilation tools like Babel can be used.
      • JAVASCRIPT: IMPORT
  10. developer.mozilla.org developer.mozilla.org
    1. import La sentencia import se usa para importar funciones que han sido exportadas desde un módulo externo. Por el momento, esta característica sólo está comenzando a ser implementada de forma nativa en los navegadores. Está implementada en muchos transpiladores, tales como Typescript y Babel, y en empaquetadores como Rollup y Webpack.
      • JAVASCRIPT: IMPORT
    1. Just last year Grunt was effectively dethroned by Gulp. And now, just as Gulp and Browserify are finally reaching critical mass, Webpack threatens to unseat them both. Is there truly a compelling reason to change your front-end build process yet again?
      • CONTINUOS CHANGE!
      • reinventing the wheel
    1. IE will block appending any element created in a different window context from the window context that the element is being appending to. var childWindow = window.open('somepage.html'); //will throw the exception in IE childWindow.document.body.appendChild(document.createElement('div')); //will not throw exception in IE childWindow.document.body.appendChild(childWindow.document.createElement('div'));
      • IMPORTANT
    1. The actual problem is that when the page is loaded with document.write, IE will always load inline javascript blocks before external javascript files, regardless of which one get defined first. This is described in dynamicdrive.com/forums/blog.php?bt=173 (section II). A good workaround is to put everything as external javascript files. – sayap Jan 5 '12 at 5:05
      • IMPORTANT
  11. Dec 2021
    1. The first thing you need to know is that JavaScript and Java are two totally different languages. If you are trying to learn JavaScript, you cannot follow instructions intended for Java. The best way I've seen this explained is: "Java is to JavaScript as car is to carpet."
      • "Java is to JavaScript as car is to carpet."
    1. A JavaScript wrapper for the Hypothesis API The HelloWorldAnnotated example uses functions from a library, hlib, to post an annotation to the Hypothesis service.
      • AT LAST!
      • SEE
    1. function intersperse<T>(this: T[], mkT: (ix: number) => T): T[] { return this.reduce((acc: T[], d, ix) => [...acc, mkT(ix), d], []).slice(1); }
    1. A Map of root-level context key-value pairs to supply to the component
    1. Welcome to Accessibility WeeklyA weekly dose of web accessibility to help you bring it into your everyday work. Delivered to your inbox each Monday, curated by David A. Kennedy.

      a11y Weekly is about web accessibility. How to make the web user friendly to everyone.

  12. Nov 2021
    1. querySelector is the newer feature. getElementById is better supported than querySelector. querySelector is better supported than getElementsByClassName. querySelector lets you find elements with rules that can't be expressed with getElementById and getElementsByClassName

      Which is better?

      document.querySelector() or document.getElementById()

    1. arr.sort([compareFunction]) 参数 compareFunction 可选 用来指定按某种顺序进行排列的函数。如果省略,元素按照转换为的字符串的各个字符的Unicode位点进行排序。

      可以用箭头函数 arr.sort((a,b)=>a-b)

    1. 默认情况下,sort() 方法将按字母和升序将值作为字符串进行排序。
    2. sort() 方法对数组的项目进行排序。
    1. 比如你有一个有值的数组,你想去 map 遍历每一项,这时使用箭头函数非常理想: JavaScript 代码: 12const words = ['hello', 'WORLD', 'Whatever'];const downcasedWords = words.map((word) => word.toLowerCase());
    2. 如果您尝试使用内联单行表达式语法,但您返回的值是对象字面量。您可能会认为这看起来应该是这样的: JavaScript 代码: 1(name, description) => {name: name, description: description}; 问题是这种语法比较含糊不清,容易引起歧义 : 看起来好像你正试图创建一个传统的函数体。 如果你碰巧想要一个对象的单个表达式,请用括号包裹该对象: JavaScript 代码: 1(name, description) => ({ name: name, description: description }); 或者就是直接用 return 123(name, description) => { return { name: name, description: description };};

      箭头函数返回值为对象时的处理方法

    1. 如果要返回一个对象,就要注意,如果是单表达式,这么写的话会报错: // SyntaxError: x => { foo: x } 因为和函数体的{ ... }有语法冲突,所以要改为: // ok: x => ({ foo: x })
    2. 参数不是一个,就需要用括号()括起来
    3. 箭头函数有两种格式,一种像上面的,只包含一个表达式,连{ ... }和return都省略掉了。还有一种可以包含多条语句,这时候就不能省略{ ... }和return
    1. find() 方法返回数组中满足提供的测试函数的第一个元素的值。否则返回 undefined。

      数组find的用法

    1. arguments 是一个对应于传递给函数的参数的类数组对象。

      arguments与数组都是亲兄弟

    1. 1、当分支较多时,当时用switch的效率是很高的。因为switch是随机访问的,就是确定了选择值之后直接跳转到那个特定的分支,但是if...else是遍历所以得可能值,知道找到符合条件的分支,如此看来switch的效率确实比ifelse要高的多。 2、switch…case只能处理case为常量(是不可以改变的值)的情况,对非常量的情况是无能为力的。例如 if (a > 1 && a < 100),是无法使用switch…case来处理的。所以,switch只能是在常量选择分支时比if...else效率高,但是if...else能应用于更多的场合,if...else比较灵活。

      switch...case和if...else的区别

    1. continue和break有点类似,区别在于 continue只是终止本次循环,接着还执行下一次循环 break用于完全结束一个循环,跳出循环体执行循环后面的语句。

      js中 break 和 continue 的区别

    1. 方法 参数 返回值 slice(start, end) start(必需) -起始位置; end(可选)-结束位置,若未指定,则默认到末尾所有元素 返回 [start,end)之间的元素 substring(start, end) start(必需) -起始位置;end(可选)-结束位置,若未指定,则默认到末尾所有元素 返回 [start,end)之间的元素 substr(start, length) start(必需)-起始位置;length(可选)-所截取的元素的个数,若未指定,则默认到末尾 返回[start, start+length)之间的元素 当传的参数都为正数的时候,substring和slice没有区别。当参数为负数时,三个函数的行为不尽相同。 slice() - 将传入的负参数与字符串长度相加; substring() - 把所有的负值置为0; substr() - 将负的第一个参数与字符串长度相加,负的第二个参数置为0。

      slice()、 substring()和substr()的区别

    1. charAt() 返回指定索引位置的字符 charCodeAt() 返回指定索引位置字符的 Unicode 值 concat() 连接两个或多个字符串,返回连接后的字符串 fromCharCode() 将 Unicode 转换为字符串 indexOf() 返回字符串中检索指定字符第一次出现的位置 lastIndexOf() 返回字符串中检索指定字符最后一次出现的位置 localeCompare() 用本地特定的顺序来比较两个字符串 match() 找到一个或多个正则表达式的匹配 replace() 替换与正则表达式匹配的子串 search() 检索与正则表达式相匹配的值 slice() 提取字符串的片断,并在新的字符串中返回被提取的部分 split() 把字符串分割为子字符串数组 substr() 从起始索引号提取字符串中指定数目的字符 substring() 提取字符串中两个指定的索引号之间的字符 toLocaleLowerCase() 根据主机的语言环境把字符串转换为小写,只有几种语言(如土耳其语)具有地方特有的大小写映射 toLocaleUpperCase() 根据主机的语言环境把字符串转换为大写,只有几种语言(如土耳其语)具有地方特有的大小写映射 toLowerCase() 把字符串转换为小写 toString() 返回字符串对象值 toUpperCase() 把字符串转换为大写 trim() 移除字符串首尾空白 valueOf() 返回某个字符串对象的原始值

      常见字符串方法

    2. === 为绝对相等,即数据类型与值都必须相等。
    3. \n 换行 \r 回车 \t tab(制表符) \b 退格符 \f 换页符

      常见转义字符

    1. 事件句柄,又称事件处理函数 event handlers.指事件发生时要进行的操作。将相应的函数或语句指定给事件句柄,则在该事件发生时,浏览器便执行指定的函数或语句,从而实现网页内容与用户操作的交互。

      事件句柄的概念

    1. 事件 描述 onchange HTML 元素改变 onclick 用户点击 HTML 元素 onmouseover 用户在一个HTML元素上移动鼠标 onmouseout 用户从一个HTML元素上移开鼠标 onkeydown 用户按下键盘按键 onload 浏览器已完成页面的加载

      常见HTML事件

    2. <button onclick="this.innerHTML=Date()">现在的时间是?</button>

      this.innerHTML的用法

    3. <button onclick="getElementById('demo').innerHTML=Date()">现在的时间是?</button>

      onclick用法

    1. JavaScript 数据类型 值类型(基本类型):字符串(String)、数字(Number)、布尔(Boolean)、对空(Null)、未定义(Undefined)、Symbol。 引用数据类型:对象(Object)、数组(Array)、函数(Function)。

      javascript的常见数据类型

  13. Oct 2021
    1. const str = 'mañana mañana' const strReverse = str.split('').reverse().join('') // => "anãnam anañam" // notice how the first word has an ã rather ñ
    1. let bookmarkList = Array.from(document.querySelectorAll('.widget>.vbox')) .map(e => e.shadowRoot) .map(e => e && e.querySelector('.device-page-list')) .find(e => e); let bookmarks = Array.from(bookmarkList.querySelectorAll('.vbox')) .map(e => `[${e.querySelector('.device-page-title').innerHTML}](${e.querySelector('x-link').innerHTML})`); copy(bookmarks.join('\n'));
    1. Vue.js vs React: Comparison of Two Most Popular JS FrameworksEugeneFrontend DeveloperVueReactHomeBlogDevelopmentVue.js vs React: Comparison of Two Most Popular JS FrameworksSep 23, 202126 min readNowadays, every company aims to create a high-quality web solution within a short time frame. To put it into practice, the developers’ community chooses from many JavaScript libraries and frameworks and debates to find the best one. At Codica, we consider Vue.js and ReactJS the most rapidly developing tools for the front-end development for many reasons. While these technologies can help create the same products and applications, both of them have pros and cons. The purpose of this article is to compare Vue.js vs React.js in different aspects: from general information to technical features. Both these web development tools have mature communities, wide support and popularity, but Vue.js is a framework and React is a library. So, why do we compare oranges and apples?

      Nowadays, every company aims to create a high-quality web solution within a short time frame. To put it into practice, the developers’ community chooses from many JavaScript libraries and frameworks and debates to find the best one.

      At Codica, we consider Vue.js and ReactJS the most rapidly developing tools for the front-end development for many reasons. While these technologies can help create the same products and applications, both of them have pros and cons.

      The purpose of this article is to compare Vue.js vs React.js in different aspects: from general information to technical features. Both these web development tools have mature communities, wide support and popularity, but Vue.js is a framework and React is a library. So, why do we compare oranges and apples?

  14. Sep 2021
    1. A neural network will predict your digit in the blue square above. Your image is 784 pixels (= 28 rows by 28 columns with black=1 and white=0). Those 784 features get fed into a 3 layer neural network; Input:784 - AvgPool:196 - Dense:100 - Softmax:10.
    1. You can help make Node.js and browsers more unified. For example, Node.js has util.promisify, which is commonly used. I don’t understand why such an essential method is not also available in browsers. In turn, browsers have APIs that Node.js should have. For example, fetch, Web Streams (The Node.js stream module is awful), Web Crypto (I’ve heard rumors this one is coming), Websockets, etc.
    2. The main reason I love Node.js is that I don’t have to deal with the awfulness that is JS front-end tooling.
  15. Aug 2021
    1. Javascript required? In other words, one cannot do this on cross-site iframes (due to cross-site scripting restrictions), is that right? As @clankill3r is suggesting, this demonstrates the need for a pure CSS solution to this problem
  16. Jul 2021
    1. function omit(obj, ...props) { const result = { ...obj }; props.forEach(function(prop) { delete result[prop]; }); return result; }
  17. Jun 2021
    1. Here is an example run of the QnA model:

      This example doesn't work. The await gets an error. Since it's not inside the promise?

    1. TensorFlow.js provides theLayers API,which mirrors the Keras API as closely as possible, in-cluding the serialization format.

      Surfing TensorFlow I was orbiting this conclusion. It's good to see it it stated clearly.

    1. import { knex } from 'knex' // this is a function that you call to instantiate knex import { Knex } from 'knex' // this is a namespace, and a type of a knex object
    1. The globalThis property provides a standard way of accessing the global this value (and hence the global object itself) across environments. Unlike similar properties such as window and self, it's guaranteed to work in window and non-window contexts. In this way, you can access the global object in a consistent manner without having to know which environment the code is being run in.
  18. May 2021
    1. Building an app with all the modern best practices — code-splitting, offline support, server-rendered views with client-side hydration — is fiendishly complicated. SvelteKit does all the boring stuff for you so that you can get on with the creative part.
    2. makes your app inaccessible to users if JavaScript fails or is disabled (which happens more often than you probably think).