Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

npm #14

Open
itboos opened this issue Mar 30, 2018 · 0 comments
Open

npm #14

itboos opened this issue Mar 30, 2018 · 0 comments

Comments

@itboos
Copy link
Owner

itboos commented Mar 30, 2018

###npm 一些小的工具包的源码学习:
repeat-string
(https://github.com/jonschlinkert/repeat-string)

 /*!
 * repeat-string <https://github.com/jonschlinkert/repeat-string>
 *
 * Copyright (c) 2014-2015, Jon Schlinkert.
 * Licensed under the MIT License.
 */

'use strict';

/**
 * Results cache
 */

var res = '';
var cache;

/**
 * Expose `repeat`
 */

module.exports = repeat;

/**
 * Repeat the given `string` the specified `number`
 * of times.
 *
 * **Example:**
 *
 * ```js
 * var repeat = require('repeat-string');
 * repeat('A', 5);
 * //=> AAAAA
 * ```
 *
 * @param {String} `string` The string to repeat
 * @param {Number} `number` The number of times to repeat the string
 * @return {String} Repeated string
 * @api public
 */

function repeat(str, num) {
  if (typeof str !== 'string') {
    throw new TypeError('expected a string');
  }

  // cover common, quick use cases
  if (num === 1) return str;
  if (num === 2) return str + str;

  var max = str.length * num; 
  if (cache !== str || typeof cache === 'undefined') {
    cache = str;
    res = '';
  } else if (res.length >= max) {
    return res.substr(0, max);
  }
  while (max > res.length && num > 1) {
    if (num & 1) { // 是奇数, 奇数与奇数 & 为奇数, 与偶数 2 & 1  = 0  位操作的目的是效率更高
      res += str;
    }

    num >>= 1; // num / 2 ( 等于num整除2 )
    str += str;
  }

  res += str;
  res = res.substr(0, max);
  return res;
}

参考链接:
https://stackoverflow.com/questions/4115045/ruby-what-does-the-snippet-num-1-0-exactly-do

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant